forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
saml_client.go
369 lines (316 loc) · 11.2 KB
/
saml_client.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package saml
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"encoding/xml"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/crewjam/saml"
"github.com/crewjam/saml/samlsp"
"github.com/gorilla/mux"
"github.com/rancher/rancher/pkg/auth/tokens"
"github.com/rancher/types/apis/management.cattle.io/v3"
log "github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type IDPMetadata struct {
XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:metadata EntityDescriptor"`
ValidUntil time.Time `xml:"validUntil,attr"`
EntityID string `xml:"entityID,attr"`
IDPSSODescriptors []saml.IDPSSODescriptor `xml:"IDPSSODescriptor"`
SPSSODescriptors []saml.SPSSODescriptor `xml:"SPSSODescriptor"`
}
var root *mux.Router
var appliedVersion string
var initMu sync.Mutex
func InitializeSamlServiceProvider(configToSet *v3.SamlConfig, name string) error {
initMu.Lock()
defer initMu.Unlock()
if configToSet.ResourceVersion == appliedVersion {
return nil
}
var privKey *rsa.PrivateKey
var cert *x509.Certificate
var err error
var ok bool
if configToSet.IDPMetadataContent == "" {
return fmt.Errorf("SAML: Cannot initialize saml SP properly, missing IDP URL/metadata in the config %v", configToSet)
}
if configToSet.SpCert == "" {
return fmt.Errorf("SAML: Cannot initialize saml SP properly, missing SpCert in the config %v", configToSet)
}
if configToSet.SpKey == "" {
return fmt.Errorf("SAML: Cannot initialize saml SP properly, missing SpKey in the config %v", configToSet)
}
if configToSet.SpKey != "" {
// used from ssh.ParseRawPrivateKey
block, _ := pem.Decode([]byte(configToSet.SpKey))
if block == nil {
return fmt.Errorf("SAML: no key found")
}
if strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED") {
return fmt.Errorf("SAML: cannot decode encrypted private keys")
}
switch block.Type {
case "RSA PRIVATE KEY":
privKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return fmt.Errorf("SAML: error parsing PKCS1 RSA key: %v", err)
}
case "PRIVATE KEY":
pk, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return fmt.Errorf("SAML: error parsing PKCS8 RSA key: %v", err)
}
privKey, ok = pk.(*rsa.PrivateKey)
if !ok {
return fmt.Errorf("SAML: unable to get rsa key")
}
default:
return fmt.Errorf("SAML: unsupported key type %q", block.Type)
}
}
if configToSet.SpCert != "" {
block, _ := pem.Decode([]byte(configToSet.SpCert))
if block == nil {
return fmt.Errorf("SAML: failed to parse PEM block containing the private key")
}
cert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("SAML: failed to parse DER encoded public key: " + err.Error())
}
}
provider := SamlProviders[name]
rancherAPIHost := strings.TrimRight(configToSet.RancherAPIHost, "/")
samlURL := rancherAPIHost + "/v1-saml/"
samlURL += name
actURL, err := url.Parse(samlURL)
if err != nil {
return fmt.Errorf("SAML: error in parsing URL")
}
metadataURL := *actURL
metadataURL.Path = metadataURL.Path + "/saml/metadata"
acsURL := *actURL
acsURL.Path = acsURL.Path + "/saml/acs"
sp := saml.ServiceProvider{
Key: privKey,
Certificate: cert,
MetadataURL: metadataURL,
AcsURL: acsURL,
}
// XML unmarshal throws an error for IdP Metadata cacheDuration field, as it's of type xml Duration. Using a separate struct for unmarshaling for now
idm := &IDPMetadata{}
if configToSet.IDPMetadataContent != "" {
sp.IDPMetadata = &saml.EntityDescriptor{}
if err := xml.NewDecoder(strings.NewReader(configToSet.IDPMetadataContent)).Decode(idm); err != nil {
return fmt.Errorf("SAML: cannot initialize saml SP, cannot decode IDP Metadata content from the config %v, error %v", configToSet, err)
}
}
sp.IDPMetadata.XMLName = idm.XMLName
sp.IDPMetadata.ValidUntil = idm.ValidUntil
sp.IDPMetadata.EntityID = idm.EntityID
sp.IDPMetadata.SPSSODescriptors = idm.SPSSODescriptors
sp.IDPMetadata.IDPSSODescriptors = idm.IDPSSODescriptors
if name == ADFSName {
sp.AuthnNameIDFormat = saml.UnspecifiedNameIDFormat
}
provider.serviceProvider = &sp
cookieStore := samlsp.ClientCookies{
ServiceProvider: &sp,
Name: "token",
Domain: actURL.Host,
}
provider.clientState = &cookieStore
SamlProviders[name] = provider
switch name {
case PingName:
root.Get("PingACS").HandlerFunc(provider.ServeHTTP)
root.Get("PingMetadata").HandlerFunc(provider.ServeHTTP)
case ADFSName:
root.Get("AdfsACS").HandlerFunc(provider.ServeHTTP)
root.Get("AdfsMetadata").HandlerFunc(provider.ServeHTTP)
case KeyCloakName:
root.Get("KeyCloakACS").HandlerFunc(provider.ServeHTTP)
root.Get("KeyCloakMetadata").HandlerFunc(provider.ServeHTTP)
}
appliedVersion = configToSet.ResourceVersion
return nil
}
func AuthHandler() http.Handler {
root = mux.NewRouter()
root.Methods("POST").Path("/v1-saml/ping/saml/acs").Name("PingACS")
root.Methods("GET").Path("/v1-saml/ping/saml/metadata").Name("PingMetadata")
root.Methods("POST").Path("/v1-saml/adfs/saml/acs").Name("AdfsACS")
root.Methods("GET").Path("/v1-saml/adfs/saml/metadata").Name("AdfsMetadata")
root.Methods("POST").Path("/v1-saml/keycloak/saml/acs").Name("KeyCloakACS")
root.Methods("GET").Path("/v1-saml/keycloak/saml/metadata").Name("KeyCloakMetadata")
return root
}
func (s *Provider) getSamlPrincipals(config *v3.SamlConfig, samlData map[string][]string) (v3.Principal, []v3.Principal, error) {
var userPrincipal v3.Principal
var groupPrincipals []v3.Principal
uid, ok := samlData[config.UIDField]
if !ok {
// UID field provided by user is actually not there in SAMLResponse, without this we cannot differentiate between users and create separate principals
return userPrincipal, groupPrincipals, fmt.Errorf("SAML: Unique ID field is not provided in SAML Response")
}
userPrincipal = v3.Principal{
ObjectMeta: metav1.ObjectMeta{Name: s.userType + "://" + uid[0]},
Provider: s.name,
PrincipalType: "user",
Me: true,
}
displayName, ok := samlData[config.DisplayNameField]
if ok {
userPrincipal.DisplayName = displayName[0]
}
userName, ok := samlData[config.UserNameField]
if ok {
userPrincipal.LoginName = userName[0]
}
groups, ok := samlData[config.GroupsField]
if ok {
for _, group := range groups {
group := v3.Principal{
ObjectMeta: metav1.ObjectMeta{Name: s.groupType + "://" + group},
DisplayName: group,
Provider: s.name,
PrincipalType: "group",
MemberOf: true,
}
groupPrincipals = append(groupPrincipals, group)
}
}
return userPrincipal, groupPrincipals, nil
}
// HandleSamlAssertion processes/handles the assertion obtained by the POST to /saml/acs from IdP
func (s *Provider) HandleSamlAssertion(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) {
var groupPrincipals []v3.Principal
var userPrincipal v3.Principal
if relayState := r.Form.Get("RelayState"); relayState != "" {
// delete the cookie
s.clientState.DeleteState(w, r, relayState)
}
redirectURL := s.clientState.GetState(r, "Rancher_FinalRedirectURL")
samlData := make(map[string][]string)
for _, attributeStatement := range assertion.AttributeStatements {
for _, attr := range attributeStatement.Attributes {
attrName := attr.FriendlyName
if attrName == "" {
attrName = attr.Name
}
for _, value := range attr.Values {
samlData[attrName] = append(samlData[attrName], value.Value)
}
}
}
config, err := s.getSamlConfig()
if err != nil {
log.Errorf("SAML: Error getting saml config %v", err)
http.Redirect(w, r, redirectURL+"/login?errorCode=500", http.StatusFound)
return
}
userPrincipal, groupPrincipals, err = s.getSamlPrincipals(config, samlData)
if err != nil {
log.Error(err)
http.Redirect(w, r, redirectURL+"/login?errorCode=500", http.StatusFound)
return
}
allowedPrincipals := config.AllowedPrincipalIDs
allowed, err := s.userMGR.CheckAccess(config.AccessMode, allowedPrincipals, userPrincipal, groupPrincipals)
if err != nil {
log.Errorf("SAML: Error during login while checking access %v", err)
http.Redirect(w, r, redirectURL+"/login?errorCode=500", http.StatusFound)
return
}
if !allowed {
log.Errorf("SAML: User does not have access %v", err)
http.Redirect(w, r, redirectURL+"/login?errorCode=403", http.StatusFound)
return
}
userID := s.clientState.GetState(r, "Rancher_UserID")
rancherAction := s.clientState.GetState(r, "Rancher_Action")
if userID != "" && rancherAction == "testAndEnable" {
user, err := s.userMGR.SetPrincipalOnCurrentUserByUserID(userID, userPrincipal)
if err != nil {
log.Errorf("SAML: Error setting principal on current user %v", err)
http.Redirect(w, r, redirectURL+"/login?errorCode=500", http.StatusFound)
return
}
config.Enabled = true
err = s.saveSamlConfig(config)
if err != nil {
log.Errorf("SAML: Error saving saml config %v", err)
http.Redirect(w, r, redirectURL+"/login?errorCode=500", http.StatusFound)
return
}
isSecure := false
if r.URL.Scheme == "https" {
isSecure = true
}
err = setRancherToken(w, r, s.tokenMGR, user.Name, userPrincipal, groupPrincipals, isSecure)
if err != nil {
log.Errorf("SAML: Failed creating token with error: %v", err)
http.Redirect(w, r, redirectURL+"/login?errorCode=500", http.StatusFound)
}
// delete the cookies
s.clientState.DeleteState(w, r, "Rancher_UserID")
s.clientState.DeleteState(w, r, "Rancher_Action")
redirectURL := s.clientState.GetState(r, "Rancher_FinalRedirectURL")
s.clientState.DeleteState(w, r, "Rancher_FinalRedirectURL")
if redirectURL != "" {
// delete the cookie
s.clientState.DeleteState(w, r, "Rancher_FinalRedirectURL")
http.Redirect(w, r, redirectURL, http.StatusFound)
}
return
}
displayName := userPrincipal.DisplayName
if displayName == "" {
displayName = userPrincipal.LoginName
}
user, err := s.userMGR.EnsureUser(userPrincipal.Name, displayName)
if err != nil {
log.Errorf("SAML: Failed getting user with error: %v", err)
http.Redirect(w, r, redirectURL+"/login?errorCode=500", http.StatusFound)
return
}
if user.Enabled != nil && !*user.Enabled {
log.Errorf("SAML: User %v permission denied", user.Name)
http.Redirect(w, r, redirectURL+"/login?errorCode=403", http.StatusFound)
return
}
err = setRancherToken(w, r, s.tokenMGR, user.Name, userPrincipal, groupPrincipals, true)
if err != nil {
log.Errorf("SAML: Failed creating token with error: %v", err)
http.Redirect(w, r, redirectURL+"/login?errorCode=500", http.StatusFound)
}
redirectURL = s.clientState.GetState(r, "Rancher_FinalRedirectURL")
if redirectURL != "" {
// delete the cookie
s.clientState.DeleteState(w, r, "Rancher_FinalRedirectURL")
http.Redirect(w, r, redirectURL, http.StatusFound)
}
return
}
func setRancherToken(w http.ResponseWriter, r *http.Request, tokenMGR *tokens.Manager, userID string, userPrincipal v3.Principal,
groupPrincipals []v3.Principal, isSecure bool) error {
rToken, err := tokenMGR.NewLoginToken(userID, userPrincipal, groupPrincipals, "", 0, "")
if err != nil {
return err
}
tokenCookie := &http.Cookie{
Name: "R_SESS",
Value: rToken.ObjectMeta.Name + ":" + rToken.Token,
Secure: isSecure,
Path: "/",
HttpOnly: true,
}
http.SetCookie(w, tokenCookie)
return nil
}