Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent database connections to sqlite #9218

Merged
merged 3 commits into from
Mar 2, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions superset/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,10 @@ class CeleryConfig: # pylint: disable=too-few-public-methods
# SQLALCHEMY_DATABASE_URI by default if set to `None`
SQLALCHEMY_EXAMPLES_URI = None

# Some sqlalchemy connection strings can open Superset to security risks.
# Typically these should not be allowed.
PREVENT_UNSAFE_DB_CONNECTIONS = True

# SIP-15 should be enabled for all new Superset deployments which ensures that the time
# range endpoints adhere to [start, end). For existing deployments admins should provide
# a dedicated period of time to allow chart producers to update their charts before
Expand Down
30 changes: 30 additions & 0 deletions superset/security/analytics_db_safety.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.


class DBSecurityException(Exception):
""" Exception to prevent a security issue with connecting a DB """

status = 400


def check_sqlalchemy_uri(uri):
if uri.startswith("sqlite"):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@suddjian should this be if uri.drivername == "sqlite":? Also could you add typing to this method so it's apparent the type of the uri method.

Copy link
Member Author

@suddjian suddjian Mar 4, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is merged but I can add typing in a new PR.

uri is a string so I assume you're referring to the output of make_url from sqlalchemy. make_url(uri).drivername == "sqlite" won't quite work in all cases because there are actually multiple drivers available for sqlite, each with their own protocol portion of the URI. We would need multiple checks, or make_url(uri).drivername.startswith("sqlite"). Any sqlite URI will start with "sqlite", however, so I think this way is simpler.

# sqlite creates a local DB, which allows mapping server's filesystem
raise DBSecurityException(
"SQLite database cannot be used as a data source for security reasons."
)
9 changes: 9 additions & 0 deletions superset/views/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@
from superset.models.slice import Slice
from superset.models.sql_lab import Query, TabState
from superset.models.user_attributes import UserAttribute
from superset.security.analytics_db_safety import (
check_sqlalchemy_uri,
DBSecurityException,
)
from superset.sql_parse import ParsedQuery
from superset.sql_validators import get_validator_by_name
from superset.utils import core as utils, dashboard_import_export
Expand Down Expand Up @@ -1314,6 +1318,8 @@ def testconn(self):
db_name = request.json.get("name")
uri = request.json.get("uri")
try:
if app.config.get("PREVENT_UNSAFE_DB_CONNECTIONS"):
suddjian marked this conversation as resolved.
Show resolved Hide resolved
check_sqlalchemy_uri(uri)
# if the database already exists in the database, only its safe (password-masked) URI
# would be shown in the UI and would be passed in the form data.
# so if the database already exists and the form was submitted with the safe URI,
Expand Down Expand Up @@ -1365,6 +1371,9 @@ def testconn(self):
return json_error_response(
_("Connection failed, please check your connection settings."), 400
)
except DBSecurityException as e:
logger.warning("Stopped an unsafe database connection. %s", e)
return json_error_response(_(str(e)))
except Exception as e:
logger.error("Unexpected error %s", e)
return json_error_response(_("Unexpected error occurred."), 400)
Expand Down
5 changes: 4 additions & 1 deletion superset/views/database/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
from flask_babel import lazy_gettext as _
from sqlalchemy import MetaData

from superset import security_manager
from superset import app, security_manager
from superset.exceptions import SupersetException
from superset.security.analytics_db_safety import check_sqlalchemy_uri
from superset.utils import core as utils
from superset.views.database.filters import DatabaseFilter

Expand Down Expand Up @@ -191,6 +192,8 @@ class DatabaseMixin:
}

def _pre_add_update(self, database):
if app.config.get("PREVENT_UNSAFE_DB_CONNECTIONS"):
suddjian marked this conversation as resolved.
Show resolved Hide resolved
check_sqlalchemy_uri(database.sqlalchemy_uri)
self.check_extra(database)
self.check_encrypted_extra(database)
database.set_sqlalchemy_uri(database.sqlalchemy_uri)
Expand Down
32 changes: 32 additions & 0 deletions tests/security/analytics_db_safety_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

from superset.security.analytics_db_safety import (
check_sqlalchemy_uri,
DBSecurityException,
)

from ..base_tests import SupersetTestCase


class DBConnectionsTest(SupersetTestCase):
def test_check_sqlalchemy_uri_ok(self):
check_sqlalchemy_uri("postgres://user:password@test.com")

def test_check_sqlalchemy_url_sqlite(self):
with self.assertRaises(DBSecurityException):
check_sqlalchemy_uri("sqlite:///home/superset/bad.db")