-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.go
340 lines (310 loc) · 10.8 KB
/
auth.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package httpd
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
"github.com/Cloud-Foundations/cloud-gate/lib/constants"
)
type oauth2StateJWT struct {
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audience []string `json:"aud,omitempty"`
Expiration int64 `json:"exp,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
ReturnURL string `json:"return_url,omitempty"`
}
type accessToken struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:expires_in`
IDToken string `json:"id_token"`
}
type openidConnectUserInfo struct {
Subject string `json:"sub"`
Name string `json:"name"`
Login string `json:"login,omitempty"`
Username string `json:"username,omitempty"`
PreferredUsername string `json:"preferred_username,omitempty"`
Email string `json:"email,omitempty"`
}
func randomStringGeneration() (string, error) {
const size = 32
bytes := make([]byte, size)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(bytes), nil
}
func (s *Server) setAndStoreAuthCookie(w http.ResponseWriter, username string) error {
randomString, err := randomStringGeneration()
if err != nil {
s.logger.Println(err)
return err
}
expires := time.Now().Add(time.Hour * constants.CookieExpirationHours)
userCookie := http.Cookie{Name: authCookieName, Value: randomString, Path: "/", Expires: expires, HttpOnly: true, Secure: true}
http.SetCookie(w, &userCookie)
Cookieinfo := AuthCookie{username, userCookie.Expires}
s.cookieMutex.Lock()
s.authCookie[userCookie.Value] = Cookieinfo
s.cookieMutex.Unlock()
return nil
}
func (s *Server) getRedirURL(r *http.Request) string {
return "https://" + r.Host + constants.Oauth2redirectPath
}
func (s *Server) generateAuthCodeURL(state string, r *http.Request) string {
var buf bytes.Buffer
buf.WriteString(s.staticConfig.OpenID.AuthURL)
redirectURL := s.getRedirURL(r)
v := url.Values{
"response_type": {"code"},
"client_id": {s.staticConfig.OpenID.ClientID},
"scope": {s.staticConfig.OpenID.Scopes},
"redirect_uri": {redirectURL},
}
if state != "" {
// TODO(light): Docs say never to omit state; don't allow empty.
v.Set("state", state)
}
if strings.Contains(s.staticConfig.OpenID.AuthURL, "?") {
buf.WriteByte('&')
} else {
buf.WriteByte('?')
}
buf.WriteString(v.Encode())
return buf.String()
}
func (s *Server) generateValidStateString(r *http.Request) (string, error) {
key := []byte(s.staticConfig.Base.SharedSecrets[0])
sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT"))
if err != nil {
s.logger.Debugf(1, "New jose signer error err: %s", err)
return "", err
}
issuer := "cloud-gate"
subject := "state:" + constants.RedirCookieName
now := time.Now().Unix()
stateToken := oauth2StateJWT{Issuer: issuer,
Subject: subject,
Audience: []string{issuer},
ReturnURL: r.URL.String(),
NotBefore: now,
IssuedAt: now,
Expiration: now + constants.MaxAgeSecondsRedirCookie}
return jwt.Signed(sig).Claims(stateToken).CompactSerialize()
}
// This is where the redirect to the oath2 provider is computed.
func (s *Server) oauth2DoRedirectoToProviderHandler(w http.ResponseWriter, r *http.Request) {
stateString, err := s.generateValidStateString(r)
if err != nil {
s.logger.Printf("Error from generateValidStateString err: %s\n", err)
http.Error(w, "Internal Error ", http.StatusInternalServerError)
return
}
http.Redirect(w, r, s.generateAuthCodeURL(stateString, r), http.StatusFound)
}
// Next are the functions for checking the callback
func (s *Server) JWTClaims(t *jwt.JSONWebToken, dest ...interface{}) (err error) {
for _, key := range s.staticConfig.Base.SharedSecrets {
binkey := []byte(key)
err = t.Claims(binkey, dest...)
if err == nil {
return nil
}
}
if err != nil {
return err
}
return errors.New("No valid key found")
}
func getUsernameFromUserinfo(userInfo openidConnectUserInfo) string {
username := userInfo.Username
if len(username) < 1 {
username = userInfo.Login
}
if len(username) < 1 {
username = userInfo.PreferredUsername
}
if len(username) < 1 {
username = userInfo.Email
}
return username
}
const maxPostRetryCount = 3
// In general Post Requests are NOT idempotent, this the golang library does not try to do
// a retry for POSTS. It is also documented that when a keepalive connection exists the connection
// might get closed before the netClient internal Do operation. When this happens we get an
// unexpected EOF message. Since all of our uses por gettingPost bytes are idempotent we
// implement retry logic on only this case.
func (s *Server) getBytesFromSuccessfullPost(url string, data url.Values) ([]byte, error) {
return s.getBytesFromSuccessfullPostWithRetries(url, data, maxPostRetryCount)
}
func (s *Server) getBytesFromSuccessfullPostWithRetries(url string, data url.Values, maxRetries int) ([]byte, error) {
if maxRetries <= 0 {
return nil, fmt.Errorf("Too many reties for getBytesFromSuccessfullPostWithRetries, url=%s", url)
}
response, err := s.netClient.PostForm(url, data)
if err != nil {
if strings.Contains(err.Error(), "unexpected EOF") {
return s.getBytesFromSuccessfullPostWithRetries(url, data, maxRetries-1)
}
s.logger.Debugf(1, "client post error err: %s\n", err)
return nil, err
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
s.logger.Debugf(1, "Error reading http responseBody err: %s\n", err)
return nil, err
}
if response.StatusCode >= 300 {
s.logger.Debugf(1, string(responseBody))
return nil, errors.New("invalid status code")
}
return responseBody, nil
}
func (s *Server) getVerifyReturnStateJWT(r *http.Request) (oauth2StateJWT, error) {
inboundJWT := oauth2StateJWT{}
serializedState := r.URL.Query().Get("state")
if len(serializedState) < 1 {
return inboundJWT, errors.New("null inbound state")
}
tok, err := jwt.ParseSigned(serializedState)
if err != nil {
return inboundJWT, err
}
if err := s.JWTClaims(tok, &inboundJWT); err != nil {
s.logger.Debugf(1, "error parsing claims err: %s\n", err)
return inboundJWT, err
}
// At this point we know the signature is valid, but now we must
// validate the contents of the JWT token
issuer := "cloud-gate"
subject := "state:" + constants.RedirCookieName
if inboundJWT.Issuer != issuer || inboundJWT.Subject != subject ||
inboundJWT.NotBefore > time.Now().Unix() || inboundJWT.Expiration < time.Now().Unix() {
err = errors.New("invalid JWT values")
return inboundJWT, err
}
return inboundJWT, nil
}
func (s *Server) oauth2RedirectPathHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
s.logger.Printf("Bad method on redirect, should only be GET")
http.Error(w, "Invalid method", http.StatusMethodNotAllowed)
return
}
authCode := r.URL.Query().Get("code")
if len(authCode) < 1 {
s.logger.Println("null code")
http.Error(w, "null code", http.StatusUnauthorized)
return
}
inboundJWT, err := s.getVerifyReturnStateJWT(r)
if err != nil {
s.logger.Printf("error processing state err: %s\n", err)
http.Error(w, "null or bad inboundState", http.StatusUnauthorized)
return
}
// OK state is valid.. now we perform the token exchange
redirectURL := s.getRedirURL(r)
tokenRespBody, err := s.getBytesFromSuccessfullPost(s.staticConfig.OpenID.TokenURL,
url.Values{"redirect_uri": {redirectURL},
"code": {authCode},
"grant_type": {"authorization_code"},
"client_id": {s.staticConfig.OpenID.ClientID},
"client_secret": {s.staticConfig.OpenID.ClientSecret},
})
if err != nil {
s.logger.Printf("Error getting byes fom post err: %s", err)
http.Error(w, "bad transaction with openic context ", http.StatusInternalServerError)
return
}
var oauth2AccessToken accessToken
err = json.Unmarshal(tokenRespBody, &oauth2AccessToken)
if err != nil {
s.logger.Printf(string(tokenRespBody))
http.Error(w, "cannot decode oath2 response for token ", http.StatusInternalServerError)
return
}
// TODO: tolower
if oauth2AccessToken.TokenType != "Bearer" || len(oauth2AccessToken.AccessToken) < 1 {
s.logger.Printf("token type invalid token=%s", string(tokenRespBody))
http.Error(w, "invalid accessToken ", http.StatusInternalServerError)
return
}
// Now we use the access_token (from token exchange) to get userinfo
userInfoRespBody, err := s.getBytesFromSuccessfullPost(s.staticConfig.OpenID.UserinfoURL,
url.Values{"access_token": {oauth2AccessToken.AccessToken}})
if err != nil {
s.logger.Println(err)
http.Error(w, "bad transaction with openic context ", http.StatusInternalServerError)
return
}
var userInfo openidConnectUserInfo
err = json.Unmarshal(userInfoRespBody, &userInfo)
if err != nil {
s.logger.Printf("Error unmarshalling userinfo ")
s.logger.Debugf(1, "unmarshal error %s\n", string(tokenRespBody))
http.Error(w, "cannot decode oath2 userinfo token ", http.StatusInternalServerError)
return
}
username := getUsernameFromUserinfo(userInfo)
err = s.setAndStoreAuthCookie(w, username)
if err != nil {
s.logger.Println(err)
http.Error(w, "cannot set auth Cookie", http.StatusInternalServerError)
return
}
destinationPath := inboundJWT.ReturnURL
http.Redirect(w, r, destinationPath, http.StatusFound)
}
func setupSecurityHeaders(w http.ResponseWriter) error {
// All common security headers go here
w.Header().Set("Strict-Transport-Security", "max-age=31536")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-XSS-Protection", "1")
w.Header().Set("Content-Security-Policy", "default-src 'self' ;style-src 'self' maxcdn.bootstrapcdn.com fonts.googleapis.com 'unsafe-inline'; font-src maxcdn.bootstrapcdn.com fonts.gstatic.com fonts.googleapis.com")
return nil
}
func (s *Server) getRemoteUserName(w http.ResponseWriter, r *http.Request) (string, error) {
// If you have a verified cert, no need for cookies
if r.TLS != nil {
if len(r.TLS.VerifiedChains) > 0 {
clientName := r.TLS.VerifiedChains[0][0].Subject.CommonName
return clientName, nil
}
}
setupSecurityHeaders(w)
remoteCookie, err := r.Cookie(authCookieName)
if err != nil {
s.logger.Debugf(1, "Err cookie %s", err)
s.oauth2DoRedirectoToProviderHandler(w, r)
return "", err
}
s.cookieMutex.Lock()
defer s.cookieMutex.Unlock()
authInfo, ok := s.authCookie[remoteCookie.Value]
if !ok {
s.oauth2DoRedirectoToProviderHandler(w, r)
return "", errors.New("Cookie not found")
}
if authInfo.ExpiresAt.Before(time.Now()) {
s.oauth2DoRedirectoToProviderHandler(w, r)
return "", errors.New("Expired Cookie")
}
return authInfo.Username, nil
}