|
29 | 29 | from .compat import ( |
30 | 30 | BAD_REQUEST, SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT, |
31 | 31 | FORBIDDEN, BAD_GATEWAY, |
32 | | - UNAUTHORIZED, INTERNAL_SERVER_ERROR, OK, BadStatusLine) |
| 32 | + UNAUTHORIZED, INTERNAL_SERVER_ERROR, OK, BadStatusLine, |
| 33 | + urlsplit, unescape) |
33 | 34 | from .compat import (Queue, EmptyQueue) |
34 | 35 | from .compat import (TO_UNICODE, urlencode) |
35 | 36 | from .compat import proxy_bypass |
36 | 37 | from .errorcode import (ER_FAILED_TO_CONNECT_TO_DB, ER_CONNECTION_IS_CLOSED, |
37 | 38 | 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) |
39 | 41 | from .errors import (Error, OperationalError, DatabaseError, ProgrammingError, |
40 | 42 | GatewayTimeoutError, ServiceUnavailableError, |
41 | 43 | InterfaceError, InternalServerError, ForbiddenError, |
|
102 | 104 | } |
103 | 105 |
|
104 | 106 |
|
| 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 | + |
105 | 144 | class RequestRetry(Exception): |
106 | 145 | pass |
107 | 146 |
|
108 | 147 |
|
109 | 148 | class SnowflakeAuth(AuthBase): |
110 | | - """Attaches HTTP Authorization header for Snowflake""" |
| 149 | + """ |
| 150 | + Attaches HTTP Authorization header for Snowflake |
| 151 | + """ |
111 | 152 |
|
112 | 153 | def __init__(self, token): |
113 | 154 | # setup any auth-related data here |
@@ -125,7 +166,7 @@ def __call__(self, r): |
125 | 166 |
|
126 | 167 |
|
127 | 168 | class SnowflakeRestful(object): |
128 | | - u""" |
| 169 | + """ |
129 | 170 | Snowflake Restful class |
130 | 171 | """ |
131 | 172 |
|
@@ -604,7 +645,8 @@ def _post_request(self, url, headers, body, token=None, |
604 | 645 |
|
605 | 646 | return ret |
606 | 647 |
|
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): |
608 | 650 | """ Curried API request with session management. """ |
609 | 651 | if timeout is not None and 'timeouts' in kwargs: |
610 | 652 | raise TypeError("Mutually exclusive args: timeout, timeouts") |
@@ -877,8 +919,29 @@ def make_requests_session(self): |
877 | 919 | def authenticate_by_saml(self, authenticator, account, user, password): |
878 | 920 | u""" |
879 | 921 | 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. |
880 | 942 | """ |
881 | 943 | logger.info(u'authenticating by SAML') |
| 944 | + logger.debug(u'step 1: query GS to obtain IDP token and SSO url') |
882 | 945 | headers = { |
883 | 946 | u'Content-Type': CONTENT_TYPE_APPLICATION_JSON, |
884 | 947 | u"accept": CONTENT_TYPE_APPLICATION_JSON, |
@@ -900,7 +963,6 @@ def authenticate_by_saml(self, authenticator, account, user, password): |
900 | 963 | account, authenticator, |
901 | 964 | ) |
902 | 965 |
|
903 | | - # Get OKTA token |
904 | 966 | ret = self._post_request( |
905 | 967 | url, headers, json.dumps(body), |
906 | 968 | timeout=self._connection._login_timeout) |
@@ -928,15 +990,38 @@ def authenticate_by_saml(self, authenticator, account, user, password): |
928 | 990 | token_url = data[u'tokenUrl'] |
929 | 991 | sso_url = data[u'ssoUrl'] |
930 | 992 |
|
| 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') |
931 | 1014 | data = { |
932 | 1015 | u'username': user, |
933 | 1016 | u'password': password, |
934 | 1017 | } |
935 | 1018 | ret = self.fetch(u'post', token_url, headers, data=json.dumps(data), |
936 | 1019 | timeout=self._connection._login_timeout, |
937 | 1020 | catch_okta_unauthorized_error=True) |
938 | | - |
939 | 1021 | one_time_token = ret[u'cookieToken'] |
| 1022 | + |
| 1023 | + logger.debug(u'step 4: query IDP URL snowflake app to get SAML ' |
| 1024 | + u'response') |
940 | 1025 | url_parameters = { |
941 | 1026 | u'RelayState': u"/some/deep/link", |
942 | 1027 | u'onetimetoken': one_time_token, |
@@ -946,9 +1031,33 @@ def authenticate_by_saml(self, authenticator, account, user, password): |
946 | 1031 | headers = { |
947 | 1032 | u"Accept": u'*/*', |
948 | 1033 | } |
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 |
952 | 1061 |
|
953 | 1062 | @contextlib.contextmanager |
954 | 1063 | def _use_requests_session(self): |
@@ -961,7 +1070,7 @@ def _use_requests_session(self): |
961 | 1070 | session = self.make_requests_session() |
962 | 1071 | self._active_sessions.add(session) |
963 | 1072 | 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))) |
965 | 1074 | try: |
966 | 1075 | yield session |
967 | 1076 | finally: |
@@ -970,4 +1079,4 @@ def _use_requests_session(self): |
970 | 1079 | active = len(self._active_sessions) |
971 | 1080 | idle = len(self._idle_sessions) |
972 | 1081 | logger.info("Active requests sessions: %d, idle: %d" % (active, |
973 | | - idle)) |
| 1082 | + idle)) |