GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — SNOW-28345: verify host in OKTA authentication · byule/snowflake-connector-python@1c4bc8b

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • compat.py
  • errorcode.py
  • network.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎compat.py‎

Copy file name to clipboardExpand all lines: compat.py
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import urllib
3030
import httplib
3131
import Queue
32+
from HTMLParser import HTMLParser
3233

3334
GET_CWD = os.getcwdu
3435
BASE_EXCEPTION_CLASS = StandardError
@@ -54,6 +55,8 @@
5455
urlencode = urllib.urlencode
5556
proxy_bypass = urllib.proxy_bypass
5657

58+
unescape = HTMLParser().unescape
59+
5760
EmptyQueue = Queue.Empty
5861
Queue = Queue.Queue
5962

@@ -62,6 +65,7 @@
6265
import http.client
6366
import urllib.request
6467
import queue
68+
import html
6569

6670
GET_CWD = os.getcwd
6771
BASE_EXCEPTION_CLASS = Exception
@@ -70,6 +74,7 @@
7074
urlsplit = urllib.parse.urlsplit
7175
urlunsplit = urllib.parse.urlunsplit
7276
urlencode = urllib.parse.urlencode
77+
unescape = html.unescape
7378
NUM_DATA_TYPES += [int, float, decimal.Decimal]
7479
PKCS5_UNPAD = lambda v: v[0:-v[-1]]
7580
PKCS5_OFFSET = lambda v: v[-1]
Collapse file

‎errorcode.py‎

Copy file name to clipboardExpand all lines: errorcode.py
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
ER_SERVER_CERTIFICATE_REVOKED = 250004
1313
ER_NOT_HTTPS_USED = 250005
1414
ER_FAILED_TO_SERVER = 250006
15+
ER_IDP_CONNECTION_ERROR = 25007
16+
ER_INCORRECT_DESTINATION = 25008
1517

1618
# connection
1719
ER_NO_ACCOUNT_NAME = 251001
Collapse file

‎network.py‎

Copy file name to clipboardExpand all lines: network.py
+121-12Lines changed: 121 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,15 @@
2929
from .compat import (
3030
BAD_REQUEST, SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT,
3131
FORBIDDEN, BAD_GATEWAY,
32-
UNAUTHORIZED, INTERNAL_SERVER_ERROR, OK, BadStatusLine)
32+
UNAUTHORIZED, INTERNAL_SERVER_ERROR, OK, BadStatusLine,
33+
urlsplit, unescape)
3334
from .compat import (Queue, EmptyQueue)
3435
from .compat import (TO_UNICODE, urlencode)
3536
from .compat import proxy_bypass
3637
from .errorcode import (ER_FAILED_TO_CONNECT_TO_DB, ER_CONNECTION_IS_CLOSED,
3738
ER_FAILED_TO_REQUEST, ER_FAILED_TO_RENEW_SESSION,
38-
ER_FAILED_TO_SERVER)
39+
ER_FAILED_TO_SERVER, ER_IDP_CONNECTION_ERROR,
40+
ER_INCORRECT_DESTINATION)
3941
from .errors import (Error, OperationalError, DatabaseError, ProgrammingError,
4042
GatewayTimeoutError, ServiceUnavailableError,
4143
InterfaceError, InternalServerError, ForbiddenError,
@@ -102,12 +104,51 @@
102104
}
103105

104106

107+
def _is_prefix_equal(url1, url2):
108+
"""
109+
Checks if URL prefixes are identical. The scheme, hostname and port number
110+
are compared. If the port number is not specified and the scheme is https,
111+
the port number is assumed to be 443.
112+
"""
113+
parsed_url1 = urlsplit(url1)
114+
parsed_url2 = urlsplit(url2)
115+
116+
port1 = parsed_url1.port
117+
if not port1 and parsed_url1.scheme == 'https':
118+
port1 = '443'
119+
port2 = parsed_url1.port
120+
if not port2 and parsed_url2.scheme == 'https':
121+
port2 = '443'
122+
123+
return parsed_url1.hostname == parsed_url2.hostname and \
124+
port1 == port2 and \
125+
parsed_url1.scheme == parsed_url2.scheme
126+
127+
128+
def _get_post_back_url_from_html(html):
129+
"""
130+
Gets the post back URL.
131+
132+
Since the HTML is not well formed, minidom cannot be used to convert to
133+
DOM. The first discovered form is assumed to be the form to post back
134+
and the URL is taken from action attributes.
135+
"""
136+
logger.debug(html)
137+
138+
idx = html.find('<form')
139+
start_idx = html.find('action="', idx)
140+
end_idx = html.find('"', start_idx + 8)
141+
return unescape(html[start_idx + 8:end_idx])
142+
143+
105144
class RequestRetry(Exception):
106145
pass
107146

108147

109148
class SnowflakeAuth(AuthBase):
110-
"""Attaches HTTP Authorization header for Snowflake"""
149+
"""
150+
Attaches HTTP Authorization header for Snowflake
151+
"""
111152

112153
def __init__(self, token):
113154
# setup any auth-related data here
@@ -125,7 +166,7 @@ def __call__(self, r):
125166

126167

127168
class SnowflakeRestful(object):
128-
u"""
169+
"""
129170
Snowflake Restful class
130171
"""
131172

@@ -604,7 +645,8 @@ def _post_request(self, url, headers, body, token=None,
604645

605646
return ret
606647

607-
def fetch(self, method, full_url, headers, data=None, timeout=None, **kwargs):
648+
def fetch(self, method, full_url, headers, data=None, timeout=None,
649+
**kwargs):
608650
""" Curried API request with session management. """
609651
if timeout is not None and 'timeouts' in kwargs:
610652
raise TypeError("Mutually exclusive args: timeout, timeouts")
@@ -877,8 +919,29 @@ def make_requests_session(self):
877919
def authenticate_by_saml(self, authenticator, account, user, password):
878920
u"""
879921
SAML Authentication
922+
1. query GS to obtain IDP token and SSO url
923+
2. IMPORTANT Client side validation:
924+
validate both token url and sso url contains same prefix
925+
(protocol + host + port) as the given authenticator url.
926+
Explanation:
927+
This provides a way for the user to 'authenticate' the IDP it is
928+
sending his/her credentials to. Without such a check, the user could
929+
be coerced to provide credentials to an IDP impersonator.
930+
3. query IDP token url to authenticate and retrieve access token
931+
4. given access token, query IDP URL snowflake app to get SAML response
932+
5. IMPORTANT Client side validation:
933+
validate the post back url come back with the SAML response
934+
contains the same prefix as the Snowflake's server url, which is the
935+
intended destination url to Snowflake.
936+
Explanation:
937+
This emulates the behavior of IDP initiated login flow in the user
938+
browser where the IDP instructs the browser to POST the SAML
939+
assertion to the specific SP endpoint. This is critical in
940+
preventing a SAML assertion issued to one SP from being sent to
941+
another SP.
880942
"""
881943
logger.info(u'authenticating by SAML')
944+
logger.debug(u'step 1: query GS to obtain IDP token and SSO url')
882945
headers = {
883946
u'Content-Type': CONTENT_TYPE_APPLICATION_JSON,
884947
u"accept": CONTENT_TYPE_APPLICATION_JSON,
@@ -900,7 +963,6 @@ def authenticate_by_saml(self, authenticator, account, user, password):
900963
account, authenticator,
901964
)
902965

903-
# Get OKTA token
904966
ret = self._post_request(
905967
url, headers, json.dumps(body),
906968
timeout=self._connection._login_timeout)
@@ -928,15 +990,38 @@ def authenticate_by_saml(self, authenticator, account, user, password):
928990
token_url = data[u'tokenUrl']
929991
sso_url = data[u'ssoUrl']
930992

993+
logger.debug(u'step 2: validate Token and SSO URL has the same prefix '
994+
u'as authenticator')
995+
if not _is_prefix_equal(authenticator, token_url) or \
996+
not _is_prefix_equal(authenticator, sso_url):
997+
Error.errorhandler_wrapper(
998+
self._connection, None, DatabaseError,
999+
{
1000+
u'msg': (u"The specified authenticator is not supported: "
1001+
u"{authenticator}, token_url: {token_url}, "
1002+
u"sso_url: {sso_url}".format(
1003+
authenticator=authenticator,
1004+
token_url=token_url,
1005+
sso_url=sso_url,
1006+
)),
1007+
u'errno': ER_IDP_CONNECTION_ERROR,
1008+
u'sqlstate': SQLSTATE_CONNECTION_WAS_NOT_ESTABLISHED
1009+
}
1010+
)
1011+
1012+
logger.debug(u'step 3: query IDP token url to authenticate and '
1013+
u'retrieve access token')
9311014
data = {
9321015
u'username': user,
9331016
u'password': password,
9341017
}
9351018
ret = self.fetch(u'post', token_url, headers, data=json.dumps(data),
9361019
timeout=self._connection._login_timeout,
9371020
catch_okta_unauthorized_error=True)
938-
9391021
one_time_token = ret[u'cookieToken']
1022+
1023+
logger.debug(u'step 4: query IDP URL snowflake app to get SAML '
1024+
u'response')
9401025
url_parameters = {
9411026
u'RelayState': u"/some/deep/link",
9421027
u'onetimetoken': one_time_token,
@@ -946,9 +1031,33 @@ def authenticate_by_saml(self, authenticator, account, user, password):
9461031
headers = {
9471032
u"Accept": u'*/*',
9481033
}
949-
return self.fetch(u'get', sso_url, headers,
950-
timeout=self._connection._login_timeout,
951-
is_raw_text=True)
1034+
response_html = self.fetch(u'get', sso_url, headers,
1035+
timeout=self._connection._login_timeout,
1036+
is_raw_text=True)
1037+
1038+
logger.debug(u'step 5: validate post_back_url matches Snowflake URL')
1039+
post_back_url = _get_post_back_url_from_html(response_html)
1040+
full_url = u'{protocol}://{host}:{port}'.format(
1041+
protocol=self._protocol,
1042+
host=self._host,
1043+
port=self._port,
1044+
)
1045+
if not _is_prefix_equal(post_back_url, full_url):
1046+
Error.errorhandler_wrapper(
1047+
self._connection, None, DatabaseError,
1048+
{
1049+
u'msg': (u"The specified authenticator and destination "
1050+
u"URL in the SAML assertion do not match: "
1051+
u"expected: {url}, "
1052+
u"post back: {post_back_url}".format(
1053+
url=full_url,
1054+
post_back_url=post_back_url,
1055+
)),
1056+
u'errno': ER_INCORRECT_DESTINATION,
1057+
u'sqlstate': SQLSTATE_CONNECTION_WAS_NOT_ESTABLISHED
1058+
}
1059+
)
1060+
return response_html
9521061

9531062
@contextlib.contextmanager
9541063
def _use_requests_session(self):
@@ -961,7 +1070,7 @@ def _use_requests_session(self):
9611070
session = self.make_requests_session()
9621071
self._active_sessions.add(session)
9631072
logger.info("Active requests sessions: %d, idle: %d" % (
964-
len(self._active_sessions), len(self._idle_sessions)))
1073+
len(self._active_sessions), len(self._idle_sessions)))
9651074
try:
9661075
yield session
9671076
finally:
@@ -970,4 +1079,4 @@ def _use_requests_session(self):
9701079
active = len(self._active_sessions)
9711080
idle = len(self._idle_sessions)
9721081
logger.info("Active requests sessions: %d, idle: %d" % (active,
973-
idle))
1082+
idle))

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.