forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authokta.go
325 lines (311 loc) · 9.18 KB
/
authokta.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Copyright (c) 2017-2018 Snowflake Computing Inc. All right reserved.
package gosnowflake
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
"github.com/satori/go.uuid"
)
type authOKTARequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type authOKTAResponse struct {
CookieToken string `json:"cookieToken"`
}
/*
authenticateBySAML authenticates a user by SAML
SAML Authentication
1. query GS to obtain IDP token and SSO url
2. IMPORTANT Client side validation:
validate both token url and sso url contains same prefix
(protocol + host + port) as the given authenticator url.
Explanation:
This provides a way for the user to 'authenticate' the IDP it is
sending his/her credentials to. Without such a check, the user could
be coerced to provide credentials to an IDP impersonator.
3. query IDP token url to authenticate and retrieve access token
4. given access token, query IDP URL snowflake app to get SAML response
5. IMPORTANT Client side validation:
validate the post back url come back with the SAML response
contains the same prefix as the Snowflake's server url, which is the
intended destination url to Snowflake.
Explanation:
This emulates the behavior of IDP initiated login flow in the user
browser where the IDP instructs the browser to POST the SAML
assertion to the specific SP endpoint. This is critical in
preventing a SAML assertion issued to one SP from being sent to
another SP.
*/
func authenticateBySAML(
sr *snowflakeRestful,
authenticator string,
application string,
account string,
user string,
password string,
) (samlResponse []byte, err error) {
glog.V(2).Info("step 1: query GS to obtain IDP token and SSO url")
headers := make(map[string]string)
headers["Content-Type"] = headerContentTypeApplicationJSON
headers["accept"] = headerContentTypeApplicationJSON
headers["User-Agent"] = userAgent
clientEnvironment := authRequestClientEnvironment{
Application: application,
OsVersion: platform,
}
requestMain := authRequestData{
ClientAppID: clientType,
ClientAppVersion: SnowflakeGoDriverVersion,
AccountName: account,
ClientEnvironment: clientEnvironment,
Authenticator: authenticator,
}
authRequest := authRequest{
Data: requestMain,
}
params := &url.Values{}
jsonBody, err := json.Marshal(authRequest)
if err != nil {
return nil, err
}
glog.V(2).Infof("PARAMS for Auth: %v, %v", params, sr)
respd, err := sr.FuncPostAuthSAML(sr, headers, jsonBody, sr.LoginTimeout)
if err != nil {
return nil, err
}
if !respd.Success {
glog.V(1).Infoln("Authentication FAILED")
glog.Flush()
sr.Token = ""
sr.MasterToken = ""
sr.SessionID = -1
code, err := strconv.Atoi(respd.Code)
if err != nil {
code = -1
return nil, err
}
return nil, &SnowflakeError{
Number: code,
SQLState: SQLStateConnectionRejected,
Message: respd.Message,
}
}
glog.V(2).Info("step 2: validate Token and SSO URL has the same prefix as authenticator")
var b1, b2 bool
if b1, err = isPrefixEqual(authenticator, respd.Data.TokenURL); err != nil {
return nil, err
}
if b2, err = isPrefixEqual(authenticator, respd.Data.SSOURL); err != nil {
return nil, err
}
if !b1 || !b2 {
return nil, &SnowflakeError{
Number: ErrCodeIdpConnectionError,
SQLState: SQLStateConnectionRejected,
Message: errMsgIdpConnectionError,
MessageArgs: []interface{}{authenticator, respd.Data.TokenURL, respd.Data.SSOURL},
}
}
glog.V(2).Info("step 3: query IDP token url to authenticate and retrieve access token")
jsonBody, err = json.Marshal(authOKTARequest{
Username: user,
Password: password,
})
if err != nil {
return nil, err
}
respa, err := sr.FuncPostAuthOKTA(sr, headers, jsonBody, respd.Data.TokenURL, sr.LoginTimeout)
if err != nil {
return nil, err
}
glog.V(2).Info("step 4: query IDP URL snowflake app to get SAML response")
params = &url.Values{}
params.Add("RelayState", "/some/deep/link")
params.Add("onetimetoken", respa.CookieToken)
headers = make(map[string]string)
headers["accept"] = "*/*"
bd, err := sr.FuncGetSSO(sr, params, headers, respd.Data.SSOURL, sr.LoginTimeout)
if err != nil {
return nil, err
}
glog.V(2).Info("step 5: validate post_back_url matches Snowflake URL")
tgtURL, err := postBackURL(bd)
if err != nil {
return nil, err
}
fullURL := fmt.Sprintf("%s://%s:%d", sr.Protocol, sr.Host, sr.Port)
glog.V(2).Infof("tgtURL: %v, origURL: %v", tgtURL, fullURL)
if b2, err = isPrefixEqual(tgtURL, fullURL); err != nil {
return nil, err
}
if !b2 {
return nil, &SnowflakeError{
Number: ErrCodeSSOURLNotMatch,
SQLState: SQLStateConnectionRejected,
Message: errMsgSSOURLNotMatch,
MessageArgs: []interface{}{tgtURL, fullURL},
}
}
return bd, nil
}
func postBackURL(htmlData []byte) (urlp string, err error) {
idx0 := bytes.Index(htmlData, []byte("<form"))
if idx0 < 0 {
return "", fmt.Errorf("failed to find a form tag in HTML response: %v", htmlData)
}
idx := bytes.Index(htmlData[idx0:], []byte("action=\""))
if idx < 0 {
return "", fmt.Errorf("failed to find action field in HTML response: %v", htmlData[idx0:])
}
idx += idx0
endIdx := bytes.Index(htmlData[idx+8:], []byte("\""))
if endIdx < 0 {
return "", fmt.Errorf("failed to find the end of action field: %v", htmlData[idx+8:])
}
r := html.UnescapeString(string(htmlData[idx+8 : idx+8+endIdx]))
return r, nil
}
func isPrefixEqual(url1 string, url2 string) (bool, error) {
var err error
var u1, u2 *url.URL
u1, err = url.Parse(url1)
if err != nil {
return false, fmt.Errorf("failed to parse URL. %v", url1)
}
u2, err = url.Parse(url2)
if err != nil {
return false, fmt.Errorf("failed to parse URL. %v", url2)
}
p1 := u1.Port()
if p1 == "" && u1.Scheme == "https" {
p1 = "443"
}
p2 := u1.Port()
if p2 == "" && u1.Scheme == "https" {
p2 = "443"
}
return u1.Hostname() == u2.Hostname() && p1 == p2 && u1.Scheme == u2.Scheme, nil
}
func postAuthSAML(
sr *snowflakeRestful,
headers map[string]string,
body []byte,
timeout time.Duration) (
data *authResponse, err error) {
requestID := fmt.Sprintf("requestId=%v", uuid.NewV4().String())
fullURL := fmt.Sprintf(
"%s://%s:%d%s", sr.Protocol, sr.Host, sr.Port,
"/session/authenticator-request?"+requestID)
glog.V(2).Infof("fullURL: %v", fullURL)
resp, err := sr.FuncPost(context.TODO(), sr, fullURL, headers, body, timeout)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
glog.V(2).Infof("postAuthSAML: resp: %v", resp)
var respd authResponse
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
glog.V(1).Infof("failed to decode JSON. err: %v", err)
glog.Flush()
return nil, err
}
return &respd, nil
}
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
glog.V(1).Infof("failed to extract HTTP response body. err: %v", err)
glog.Flush()
return nil, err
}
glog.Flush()
return nil, &SnowflakeError{
Number: ErrFailedToAuthSAML,
SQLState: SQLStateConnectionRejected,
Message: errMsgFailedToAuthSAML,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}
func postAuthOKTA(
sr *snowflakeRestful,
headers map[string]string,
body []byte,
fullURL string,
timeout time.Duration) (
data *authOKTAResponse, err error) {
glog.V(2).Infof("fullURL: %v", fullURL)
resp, err := sr.FuncPost(context.TODO(), sr, fullURL, headers, body, timeout)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
glog.V(2).Infof("postAuthOKTA: resp: %v", resp)
var respd authOKTAResponse
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
glog.V(1).Infof("failed to decode JSON. err: %v", err)
glog.Flush()
return nil, err
}
return &respd, nil
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
glog.V(1).Infof("failed to extract HTTP response body. err: %v", err)
glog.Flush()
return nil, err
}
glog.V(1).Infof("HTTP: %v, URL: %v, Body: %v", resp.StatusCode, fullURL, b)
glog.V(1).Infof("Header: %v", resp.Header)
glog.Flush()
return nil, &SnowflakeError{
Number: ErrFailedToAuthOKTA,
SQLState: SQLStateConnectionRejected,
Message: errMsgFailedToAuthOKTA,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}
func getSSO(
sr *snowflakeRestful,
params *url.Values,
headers map[string]string,
url string,
timeout time.Duration) (
bd []byte, err error) {
fullURL := fmt.Sprintf("%s?%s", url, params.Encode())
glog.V(2).Infof("fullURL: %v", fullURL)
resp, err := sr.FuncGet(context.TODO(), sr, fullURL, headers, timeout)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
glog.V(1).Infof("failed to extract HTTP response body. err: %v", err)
glog.Flush()
return nil, err
}
if resp.StatusCode == http.StatusOK {
glog.V(2).Infof("getSSO: resp: %v", resp)
return b, nil
}
glog.V(1).Infof("HTTP: %v, URL: %v, Body: %v", resp.StatusCode, fullURL, b)
glog.V(1).Infof("Header: %v", resp.Header)
glog.Flush()
return nil, &SnowflakeError{
Number: ErrFailedToGetSSO,
SQLState: SQLStateConnectionRejected,
Message: errMsgFailedToGetSSO,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}