-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.go
2416 lines (2146 loc) · 71.1 KB
/
main.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"database/sql"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/Symantec/Dominator/lib/log"
"github.com/Symantec/Dominator/lib/log/serverlogger"
"github.com/Symantec/Dominator/lib/srpc"
"github.com/Symantec/keymaster/keymasterd/admincache"
"github.com/Symantec/keymaster/keymasterd/eventnotifier"
"github.com/Symantec/keymaster/lib/authutil"
"github.com/Symantec/keymaster/lib/certgen"
"github.com/Symantec/keymaster/lib/pwauth"
"github.com/Symantec/keymaster/lib/webapi/v0/proto"
"github.com/Symantec/keymaster/proto/eventmon"
"github.com/Symantec/tricorder/go/healthserver"
"github.com/Symantec/tricorder/go/tricorder"
"github.com/Symantec/tricorder/go/tricorder/units"
"github.com/prometheus/client_golang/prometheus"
"github.com/tstranex/u2f"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
"golang.org/x/crypto/ssh"
"golang.org/x/net/context"
)
const (
AuthTypeNone = 0
AuthTypePassword = 1 << iota
AuthTypeFederated
AuthTypeU2F
AuthTypeSymantecVIP
)
const AuthTypeAny = 0xFFFF
type authInfo struct {
ExpiresAt time.Time
Username string
AuthType int
}
type authInfoJWT 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"`
TokenType string `json:"token_type"`
AuthType int `json:"auth_type"`
}
type storageStringDataJWT struct {
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audience []string `json:"aud,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Expiration int64 `json:"exp"`
IssuedAt int64 `json:"iat,omitempty"`
TokenType string `json:"token_type"`
DataType int `json:"data_type"`
Data string `json:"data"`
}
type u2fAuthData struct {
Enabled bool
CreatedAt time.Time
CreatorAddr string
Counter uint32
Name string
Registration *u2f.Registration
}
type userProfile struct {
U2fAuthData map[int64]*u2fAuthData
RegistrationChallenge *u2f.Challenge
//U2fAuthChallenge *u2f.Challenge
}
type localUserData struct {
U2fAuthChallenge *u2f.Challenge
ExpiresAt time.Time
}
type pendingAuth2Request struct {
ExpiresAt time.Time
state string
ctx context.Context
}
type pushPollTransaction struct {
ExpiresAt time.Time
Username string
TransactionID string
}
type RuntimeState struct {
Config AppConfigFile
SSHCARawFileContent []byte
Signer crypto.Signer
ClientCAPool *x509.CertPool
HostIdentity string
KerberosRealm *string
caCertDer []byte
//authCookie map[string]authInfo
vipPushCookie map[string]pushPollTransaction
localAuthData map[string]localUserData
SignerIsReady chan bool
Mutex sync.Mutex
//userProfile map[string]userProfile
pendingOauth2 map[string]pendingAuth2Request
storageRWMutex sync.RWMutex
db *sql.DB
dbType string
cacheDB *sql.DB
remoteDBQueryTimeout time.Duration
htmlTemplate *template.Template
passwordChecker pwauth.PasswordAuthenticator
KeymasterPublicKeys []crypto.PublicKey
isAdminCache *admincache.Cache
}
const redirectPath = "/auth/oauth2/callback"
const secsBetweenCleanup = 30
const maxAgeU2FVerifySeconds = 30
var (
Version = "No version provided"
configFilename = flag.String("config", "/etc/keymaster/config.yml",
"The filename of the configuration")
generateConfig = flag.Bool("generateConfig", false,
"Generate new valid configuration")
u2fAppID = "https://www.example.com:33443"
u2fTrustedFacets = []string{}
metricsMutex = &sync.Mutex{}
certGenCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "keymaster_certificate_issuance_counter",
Help: "Keymaster certificate issuance counter.",
},
[]string{"username", "type"},
)
authOperationCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "keymaster_auth_operation_counter",
Help: "Keymaster_auth_operation_counter",
},
[]string{"client_type", "type", "result"},
)
externalServiceDurationTotal = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "keymaster_external_service_request_duration",
Help: "Total amount of time spent non-errored external checks in ms",
Buckets: []float64{5, 7.5, 10, 15, 25, 50, 75, 100, 150, 250, 500, 750, 1000, 1500, 2500, 5000},
},
[]string{"service_name"},
)
tricorderLDAPExternalServiceDurationTotal = tricorder.NewGeometricBucketer(5, 5000.0).NewCumulativeDistribution()
tricorderStorageExternalServiceDurationTotal = tricorder.NewGeometricBucketer(1, 2000.0).NewCumulativeDistribution()
tricorderVIPExternalServiceDurationTotal = tricorder.NewGeometricBucketer(5, 5000.0).NewCumulativeDistribution()
certDurationHistogram = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "keymaster_cert_duration",
Help: "Duration of certs in seconds",
Buckets: []float64{15, 30, 60, 120, 300, 600, 3600, 7200, 36000, 57600, 72000, 86400, 172800},
},
[]string{"cert_type", "stage"},
)
logger log.DebugLogger
// TODO(rgooch): Pass this in rather than use a global variable.
eventNotifier *eventnotifier.EventNotifier
)
func metricLogAuthOperation(clientType string, authType string, success bool) {
validStr := strconv.FormatBool(success)
metricsMutex.Lock()
defer metricsMutex.Unlock()
authOperationCounter.WithLabelValues(clientType, authType, validStr).Inc()
}
func metricLogExternalServiceDuration(service string, duration time.Duration) {
val := duration.Seconds() * 1000
metricsMutex.Lock()
defer metricsMutex.Unlock()
externalServiceDurationTotal.WithLabelValues(service).Observe(val)
switch service {
case "ldap":
tricorderLDAPExternalServiceDurationTotal.Add(duration)
case "vip":
tricorderVIPExternalServiceDurationTotal.Add(duration)
case "storage-read":
tricorderStorageExternalServiceDurationTotal.Add(duration)
case "storage-save":
tricorderStorageExternalServiceDurationTotal.Add(duration)
}
}
func metricLogCertDuration(certType string, stage string, val float64) {
metricsMutex.Lock()
defer metricsMutex.Unlock()
certDurationHistogram.WithLabelValues(certType, stage).Observe(val)
}
func getHostIdentity() (string, error) {
return os.Hostname()
}
func exitsAndCanRead(fileName string, description string) ([]byte, error) {
if _, err := os.Stat(fileName); os.IsNotExist(err) {
return nil, err
}
buffer, err := ioutil.ReadFile(fileName)
if err != nil {
err = errors.New("cannot read " + description + "file")
return nil, err
}
return buffer, err
}
func getSignerFromPEMBytes(privateKey []byte) (crypto.Signer, error) {
return certgen.GetSignerFromPEMBytes(privateKey)
}
// Assumes the runtime state signer has been loaded!
func generateCADer(state *RuntimeState, keySigner crypto.Signer) ([]byte, error) {
organizationName := state.HostIdentity
if state.KerberosRealm != nil {
organizationName = *state.KerberosRealm
}
return certgen.GenSelfSignedCACert(state.HostIdentity, organizationName, keySigner)
}
func (state *RuntimeState) performStateCleanup(secsBetweenCleanup int) {
for {
state.Mutex.Lock()
//
initPendingSize := len(state.pendingOauth2)
for key, oauth2Pending := range state.pendingOauth2 {
if oauth2Pending.ExpiresAt.Before(time.Now()) {
delete(state.pendingOauth2, key)
}
}
finalPendingSize := len(state.pendingOauth2)
//localAuthData
initPendingLocal := len(state.localAuthData)
for key, localAuth := range state.localAuthData {
if localAuth.ExpiresAt.Before(time.Now()) {
delete(state.localAuthData, key)
}
}
finalPendingLocal := len(state.localAuthData)
for key, vipCookie := range state.vipPushCookie {
if vipCookie.ExpiresAt.Before(time.Now()) {
delete(state.vipPushCookie, key)
}
}
state.Mutex.Unlock()
logger.Debugf(3, "Pending Cookie sizes: before(%d) after(%d)",
initPendingSize, finalPendingSize)
logger.Debugf(3, "Pending Cookie sizes: before(%d) after(%d)",
initPendingLocal, finalPendingLocal)
time.Sleep(time.Duration(secsBetweenCleanup) * time.Second)
}
}
func convertToBindDN(username string, bind_pattern string) string {
return fmt.Sprintf(bind_pattern, username)
}
func checkUserPassword(username string, password string, config AppConfigFile, passwordChecker pwauth.PasswordAuthenticator, r *http.Request) (bool, error) {
clientType := getClientType(r)
if passwordChecker != nil {
logger.Debugf(3, "checking auth with passwordChecker")
isLDAP := false
if len(config.Ldap.LDAPTargetURLs) > 0 {
isLDAP = true
}
start := time.Now()
valid, err := passwordChecker.PasswordAuthenticate(username, []byte(password))
if err != nil {
return false, err
}
if isLDAP {
metricLogExternalServiceDuration("ldap", time.Since(start))
}
logger.Debugf(3, "pwdChaker output = %d", valid)
metricLogAuthOperation(clientType, "password", valid)
return valid, nil
}
if config.Base.HtpasswdFilename != "" {
logger.Debugf(3, "I have htpasswed filename")
buffer, err := ioutil.ReadFile(config.Base.HtpasswdFilename)
if err != nil {
return false, err
}
valid, err := authutil.CheckHtpasswdUserPassword(username, password, buffer)
if err != nil {
return false, err
}
metricLogAuthOperation(clientType, "password", valid)
return valid, nil
}
metricLogAuthOperation(clientType, "password", false)
return false, nil
}
// returns application/json or text/html depending on the request. By default we assume the requester wants json
func getPreferredAcceptType(r *http.Request) string {
preferredAcceptType := "application/json"
acceptHeader, ok := r.Header["Accept"]
if ok {
for _, acceptValue := range acceptHeader {
if strings.Contains(acceptValue, "text/html") {
logger.Printf("Got it %+v", acceptValue)
preferredAcceptType = "text/html"
}
}
}
return preferredAcceptType
}
func browserSupportsU2F(r *http.Request) bool {
if strings.Contains(r.UserAgent(), "Chrome/") {
return true
}
if strings.Contains(r.UserAgent(), "Presto/") {
return true
}
//Once FF support reaches main we can remove these silly checks
if strings.Contains(r.UserAgent(), "Firefox/57") ||
strings.Contains(r.UserAgent(), "Firefox/58") ||
strings.Contains(r.UserAgent(), "Firefox/59") ||
strings.Contains(r.UserAgent(), "Firefox/6") {
return true
}
return false
}
func getClientType(r *http.Request) string {
if r == nil {
return "unknown"
}
preferredAcceptType := getPreferredAcceptType(r)
switch preferredAcceptType {
case "text/html":
return "browser"
case "application/json":
if len(r.Referer()) > 1 {
return "browser"
}
return "cli"
default:
return "unknown"
}
}
func (state *RuntimeState) writeHTML2FAAuthPage(w http.ResponseWriter, r *http.Request,
loginDestination string, tryShowU2f bool) error {
JSSources := []string{"/static/jquery-1.12.4.patched.min.js", "/static/u2f-api.js", "/static/webui-2fa-symc-vip.js"}
showU2F := browserSupportsU2F(r) && tryShowU2f
if showU2F {
JSSources = []string{"/static/jquery-1.12.4.patched.min.js", "/static/u2f-api.js", "/static/webui-2fa-u2f.js", "/static/webui-2fa-symc-vip.js"}
}
displayData := secondFactorAuthTemplateData{
Title: "Keymaster 2FA Auth",
JSSources: JSSources,
ShowOTP: state.Config.SymantecVIP.Enabled,
ShowU2F: showU2F,
LoginDestination: loginDestination}
err := state.htmlTemplate.ExecuteTemplate(w, "secondFactorLoginPage", displayData)
if err != nil {
logger.Printf("Failed to execute %v", err)
http.Error(w, "error", http.StatusInternalServerError)
return err
}
return nil
}
func (state *RuntimeState) writeHTMLLoginPage(w http.ResponseWriter, r *http.Request,
loginDestination string, errorMessage string) error {
//footerText := state.getFooterText()
displayData := loginPageTemplateData{
Title: "Keymaster Login",
ShowOauth2: state.Config.Oauth2.Enabled,
HideStdLogin: state.Config.Base.HideStandardLogin,
LoginDestination: loginDestination,
ErrorMessage: errorMessage}
err := state.htmlTemplate.ExecuteTemplate(w, "loginPage", displayData)
if err != nil {
logger.Printf("Failed to execute %v", err)
http.Error(w, "error", http.StatusInternalServerError)
return err
}
return nil
}
func (state *RuntimeState) writeFailureResponse(w http.ResponseWriter, r *http.Request, code int, message string) {
returnAcceptType := getPreferredAcceptType(r)
if code == http.StatusUnauthorized && returnAcceptType != "text/html" {
w.Header().Set("WWW-Authenticate", `Basic realm="User Credentials"`)
}
w.WriteHeader(code)
publicErrorText := fmt.Sprintf("%d %s %s\n", code, http.StatusText(code), message)
switch code {
case http.StatusUnauthorized:
switch returnAcceptType {
case "text/html":
var authCookie *http.Cookie
for _, cookie := range r.Cookies() {
if cookie.Name != authCookieName {
continue
}
authCookie = cookie
}
loginDestnation := profilePath
if r.URL.Path == idpOpenIDCAuthorizationPath {
loginDestnation = r.URL.String()
}
if r.Method == "POST" {
/// assume it has been parsed... otherwise why are we here?
if r.Form.Get("login_destination") != "" {
loginDestnation = r.Form.Get("login_destination")
}
}
if authCookie == nil {
// TODO: change by a message followed by an HTTP redirection
state.writeHTMLLoginPage(w, r, loginDestnation, message)
return
}
info, err := state.getAuthInfoFromAuthJWT(authCookie.Value)
if err != nil {
logger.Debugf(3, "write failure state, error from getinfo authInfoJWT")
state.writeHTMLLoginPage(w, r, loginDestnation, "")
return
}
if info.ExpiresAt.Before(time.Now()) {
state.writeHTMLLoginPage(w, r, loginDestnation, "")
return
}
if (info.AuthType & AuthTypePassword) == AuthTypePassword {
state.writeHTML2FAAuthPage(w, r, loginDestnation, true)
return
}
state.writeHTMLLoginPage(w, r, loginDestnation, message)
return
default:
w.Write([]byte(publicErrorText))
}
default:
w.Write([]byte(publicErrorText))
}
}
// returns true if the system is locked and sends message to the requester
func (state *RuntimeState) sendFailureToClientIfLocked(w http.ResponseWriter, r *http.Request) bool {
var signerIsNull bool
state.Mutex.Lock()
signerIsNull = (state.Signer == nil)
state.Mutex.Unlock()
//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 'none'; script-src 'self' code.jquery.com; connect-src 'self'; img-src 'self'; style-src 'self';")
w.Header().Set("Content-Security-Policy", "default-src 'self' ;style-src 'self' fonts.googleapis.com 'unsafe-inline'; font-src fonts.gstatic.com fonts.googleapis.com")
if signerIsNull {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
logger.Printf("Signer has not been unlocked")
return true
}
return false
}
func (state *RuntimeState) setNewAuthCookie(w http.ResponseWriter, username string, authlevel int) (string, error) {
cookieVal, err := state.genNewSerializedAuthJWT(username, authlevel)
if err != nil {
logger.Println(err)
return "", err
}
expiration := time.Now().Add(time.Duration(maxAgeSecondsAuthCookie) * time.Second)
authCookie := http.Cookie{Name: authCookieName, Value: cookieVal, Expires: expiration, Path: "/", HttpOnly: true, Secure: true}
//use handler with original request.
if w != nil {
http.SetCookie(w, &authCookie)
}
return cookieVal, nil
}
func (state *RuntimeState) updateAuthCookieAuthlevel(w http.ResponseWriter, r *http.Request, authlevel int) (string, error) {
var authCookie *http.Cookie
for _, cookie := range r.Cookies() {
if cookie.Name != authCookieName {
continue
}
authCookie = cookie
}
if authCookie == nil {
err := errors.New("cannot find authCookie")
return "", err
}
var err error
cookieVal, err := state.updateAuthJWTWithNewAuthLevel(authCookie.Value, authlevel)
if err != nil {
return "", err
}
updatedAuthCookie := http.Cookie{Name: authCookieName, Value: cookieVal, Expires: authCookie.Expires, Path: "/", HttpOnly: true, Secure: true}
logger.Debugf(3, "about to update authCookie")
http.SetCookie(w, &updatedAuthCookie)
return authCookie.Value, nil
}
// Inspired by http://stackoverflow.com/questions/21936332/idiomatic-way-of-requiring-http-basic-auth-in-go
func (state *RuntimeState) checkAuth(w http.ResponseWriter, r *http.Request, requiredAuthType int) (string, int, error) {
// Check csrf
if r.Method != "GET" {
referer := r.Referer()
if len(referer) > 0 && len(r.Host) > 0 {
logger.Debugf(3, "ref =%s, host=%s", referer, r.Host)
refererURL, err := url.Parse(referer)
if err != nil {
return "", AuthTypeNone, err
}
logger.Debugf(3, "refHost =%s, host=%s", refererURL.Host, r.Host)
if refererURL.Host != r.Host {
logger.Printf("CSRF detected.... rejecting with a 400")
state.writeFailureResponse(w, r, http.StatusUnauthorized, "")
err := errors.New("CSRF detected... rejecting")
return "", AuthTypeNone, err
}
}
}
// We first check for cookies
var authCookie *http.Cookie
for _, cookie := range r.Cookies() {
if cookie.Name != authCookieName {
continue
}
authCookie = cookie
}
if authCookie == nil {
if (AuthTypePassword & requiredAuthType) == 0 {
state.writeFailureResponse(w, r, http.StatusUnauthorized, "")
err := errors.New("Insufficeint Auth Level passwd")
return "", AuthTypeNone, err
}
//For now try also http basic (to be deprecated)
user, pass, ok := r.BasicAuth()
if !ok {
state.writeFailureResponse(w, r, http.StatusUnauthorized, "")
//toLoginOrBasicAuth(w, r)
err := errors.New("check_Auth, Invalid or no auth header")
return "", AuthTypeNone, err
}
state.Mutex.Lock()
config := state.Config
state.Mutex.Unlock()
valid, err := checkUserPassword(user, pass, config, state.passwordChecker, r)
if err != nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
return "", AuthTypeNone, err
}
if !valid {
state.writeFailureResponse(w, r, http.StatusUnauthorized, "Invalid Username/Password")
err := errors.New("Invalid Credentials")
return "", AuthTypeNone, err
}
return user, AuthTypePassword, nil
}
//Critical section
info, err := state.getAuthInfoFromAuthJWT(authCookie.Value)
if err != nil {
//TODO check between internal and bad cookie error
state.writeFailureResponse(w, r, http.StatusUnauthorized, "")
err := errors.New("Invalid Cookie")
return "", AuthTypeNone, err
}
//check for expiration...
if info.ExpiresAt.Before(time.Now()) {
state.writeFailureResponse(w, r, http.StatusUnauthorized, "")
err := errors.New("Expired Cookie")
return "", AuthTypeNone, err
}
if (info.AuthType & requiredAuthType) == 0 {
state.writeFailureResponse(w, r, http.StatusUnauthorized, "")
err := errors.New("Insufficeint Auth Level")
return "", info.AuthType, err
}
return info.Username, info.AuthType, nil
}
func (state *RuntimeState) getRequiredWebUIAuthLevel() int {
AuthLevel := 0
for _, webUIPref := range state.Config.Base.AllowedAuthBackendsForWebUI {
if webUIPref == proto.AuthTypePassword {
AuthLevel |= AuthTypePassword
}
if webUIPref == proto.AuthTypeFederated {
AuthLevel |= AuthTypeFederated
}
if webUIPref == proto.AuthTypeU2F {
AuthLevel |= AuthTypeU2F
}
if webUIPref == proto.AuthTypeSymantecVIP {
AuthLevel |= AuthTypeSymantecVIP
}
}
return AuthLevel
}
const certgenPath = "/certgen/"
func (state *RuntimeState) certGenHandler(w http.ResponseWriter, r *http.Request) {
var signerIsNull bool
var keySigner crypto.Signer
// copy runtime singer if not nil
state.Mutex.Lock()
signerIsNull = (state.Signer == nil)
if !signerIsNull {
keySigner = state.Signer
}
state.Mutex.Unlock()
//local sanity tests
if signerIsNull {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
logger.Printf("Signer not loaded")
return
}
/*
*/
// TODO(camilo_viecco1): reorder checks so that simple checks are done before checking user creds
authUser, authLevel, err := state.checkAuth(w, r, AuthTypeAny)
if err != nil {
logger.Printf("%v", err)
return
}
sufficientAuthLevel := false
// We should do an intersection operation here
for _, certPref := range state.Config.Base.AllowedAuthBackendsForCerts {
if certPref == proto.AuthTypePassword {
sufficientAuthLevel = true
}
if certPref == proto.AuthTypeU2F && ((authLevel & AuthTypeU2F) == AuthTypeU2F) {
sufficientAuthLevel = true
}
if certPref == proto.AuthTypeSymantecVIP && ((authLevel & AuthTypeSymantecVIP) == AuthTypeSymantecVIP) {
sufficientAuthLevel = true
}
}
// if you have u2f you can always get the cert
if (authLevel & AuthTypeU2F) == AuthTypeU2F {
sufficientAuthLevel = true
}
if !sufficientAuthLevel {
logger.Printf("Not enough auth level for getting certs")
state.writeFailureResponse(w, r, http.StatusBadRequest, "Not enough auth level for getting certs")
return
}
targetUser := r.URL.Path[len(certgenPath):]
if authUser != targetUser {
state.writeFailureResponse(w, r, http.StatusForbidden, "")
logger.Printf("User %s asking for creds for %s", authUser, targetUser)
return
}
logger.Debugf(3, "auth succedded for %s", authUser)
switch r.Method {
case "GET":
logger.Debugf(3, "Got client GET connection")
err = r.ParseForm()
if err != nil {
logger.Println(err)
state.writeFailureResponse(w, r, http.StatusBadRequest, "Error parsing form")
return
}
case "POST":
logger.Debugf(3, "Got client POST connection")
err = r.ParseMultipartForm(1e7)
if err != nil {
logger.Println(err)
state.writeFailureResponse(w, r, http.StatusBadRequest, "Error parsing form")
return
}
default:
state.writeFailureResponse(w, r, http.StatusMethodNotAllowed, "")
return
}
duration := time.Duration(24 * time.Hour)
if formDuration, ok := r.Form["duration"]; ok {
stringDuration := formDuration[0]
newDuration, err := time.ParseDuration(stringDuration)
if err != nil {
logger.Println(err)
state.writeFailureResponse(w, r, http.StatusBadRequest, "Error parsing form (duration)")
return
}
metricLogCertDuration("unparsed", "requested", float64(newDuration.Seconds()))
if newDuration > duration {
logger.Println(err)
state.writeFailureResponse(w, r, http.StatusBadRequest, "Error parsing form (invalid duration)")
return
}
duration = newDuration
}
certType := "ssh"
if val, ok := r.Form["type"]; ok {
certType = val[0]
}
logger.Printf("cert type =%s", certType)
switch certType {
case "ssh":
state.postAuthSSHCertHandler(w, r, targetUser, keySigner, duration)
return
case "x509":
state.postAuthX509CertHandler(w, r, targetUser, keySigner, duration, false)
return
case "x509-kubernetes":
state.postAuthX509CertHandler(w, r, targetUser, keySigner, duration, true)
return
default:
state.writeFailureResponse(w, r, http.StatusBadRequest, "Unrecognized cert type")
return
}
//SHOULD have never reached this!
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
logger.Printf("Escape from default paths")
return
}
func (state *RuntimeState) postAuthSSHCertHandler(
w http.ResponseWriter, r *http.Request, targetUser string,
keySigner crypto.Signer, duration time.Duration) {
signer, err := ssh.NewSignerFromSigner(keySigner)
if err != nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
logger.Printf("Signer failed to load")
return
}
var cert string
var certBytes []byte
switch r.Method {
case "GET":
cert, certBytes, err = certgen.GenSSHCertFileStringFromSSSDPublicKey(targetUser, signer, state.HostIdentity, duration)
if err != nil {
http.NotFound(w, r)
return
}
case "POST":
file, _, err := r.FormFile("pubkeyfile")
if err != nil {
logger.Println(err)
state.writeFailureResponse(w, r, http.StatusBadRequest, "Missing public key file")
return
}
defer file.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(file)
userPubKey := buf.String()
//validKey, err := regexp.MatchString("^(ssh-rsa|ssh-dss|ecdsa-sha2-nistp256|ssh-ed25519) [a-zA-Z0-9/+]+=?=? .*$", userPubKey)
validKey, err := regexp.MatchString("^(ssh-rsa|ssh-dss|ecdsa-sha2-nistp256|ssh-ed25519) [a-zA-Z0-9/+]+=?=? ?.{0,512}\n?$", userPubKey)
if err != nil {
logger.Println(err)
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
return
}
if !validKey {
state.writeFailureResponse(w, r, http.StatusBadRequest, "Invalid File, bad re")
logger.Printf("invalid file, bad re")
return
}
cert, certBytes, err = certgen.GenSSHCertFileString(targetUser, userPubKey, signer, state.HostIdentity, duration)
if err != nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
logger.Printf("signUserPubkey Err")
return
}
default:
state.writeFailureResponse(w, r, http.StatusMethodNotAllowed, "")
return
}
eventNotifier.PublishSSH(certBytes)
metricLogCertDuration("ssh", "granted", float64(duration.Seconds()))
w.Header().Set("Content-Disposition", `attachment; filename="id_rsa-cert.pub"`)
w.WriteHeader(200)
fmt.Fprintf(w, "%s", cert)
logger.Printf("Generated SSH Certifcate for %s", targetUser)
go func(username string, certType string) {
metricsMutex.Lock()
defer metricsMutex.Unlock()
certGenCounter.WithLabelValues(username, certType).Inc()
}(targetUser, "ssh")
}
func (state *RuntimeState) getUserGroups(username string) ([]string, error) {
ldapConfig := state.Config.UserInfo.Ldap
var timeoutSecs uint
timeoutSecs = 2
//for _, ldapUrl := range ldapConfig.LDAPTargetURLs {
for _, ldapUrl := range strings.Split(ldapConfig.LDAPTargetURLs, ",") {
if len(ldapUrl) < 1 {
continue
}
u, err := authutil.ParseLDAPURL(ldapUrl)
if err != nil {
logger.Printf("Failed to parse ldapurl '%s'", ldapUrl)
continue
}
groups, err := authutil.GetLDAPUserGroups(*u,
ldapConfig.BindUsername, ldapConfig.BindPassword,
timeoutSecs, nil, username,
ldapConfig.UserSearchBaseDNs, ldapConfig.UserSearchFilter)
if err != nil {
continue
}
return groups, nil
}
if ldapConfig.LDAPTargetURLs == "" {
var emptyGroup []string
return emptyGroup, nil
}
err := errors.New("error getting the groups")
return nil, err
}
func (state *RuntimeState) postAuthX509CertHandler(
w http.ResponseWriter, r *http.Request, targetUser string,
keySigner crypto.Signer, duration time.Duration,
withUserGroups bool) {
var userGroups []string
var err error
if withUserGroups {
userGroups, err = state.getUserGroups(targetUser)
if err != nil {
//logger.Println("error getting user groups")
logger.Println(err)
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
return
}
//logger.Printf("%v", userGroups)
} else {
userGroups = append(userGroups, "keymaster")
}
var cert string
switch r.Method {
case "POST":
file, _, err := r.FormFile("pubkeyfile")
if err != nil {
logger.Println(err)
state.writeFailureResponse(w, r, http.StatusBadRequest, "Missing public key file")
return
}
defer file.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(file)
block, _ := pem.Decode(buf.Bytes())
if block == nil || block.Type != "PUBLIC KEY" {
state.writeFailureResponse(w, r, http.StatusBadRequest, "Invalid File, Unable to decode pem")
logger.Printf("invalid file, unable to decode pem")
return
}
userPub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
state.writeFailureResponse(w, r, http.StatusBadRequest, "Cannot parse public key")
logger.Printf("Cannot parse public key")
return
}
//tate.caCertDer
caCert, err := x509.ParseCertificate(state.caCertDer)
if err != nil {
//state.writeFailureResponse(w, http.StatusBadRequest, "Cannot parse public key")
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
logger.Printf("Cannot parse CA Der data")
return
}
derCert, err := certgen.GenUserX509Cert(targetUser, userPub, caCert, keySigner, state.KerberosRealm, duration, &userGroups)
if err != nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
logger.Printf("Cannot Generate x509cert")
return
}
eventNotifier.PublishX509(derCert)
cert = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derCert}))
default:
state.writeFailureResponse(w, r, http.StatusMethodNotAllowed, "")
return
}
metricLogCertDuration("x509", "granted", float64(duration.Seconds()))
w.Header().Set("Content-Disposition", `attachment; filename="userCert.pem"`)
w.WriteHeader(200)
fmt.Fprintf(w, "%s", cert)
logger.Printf("Generated x509 Certifcate for %s", targetUser)
go func(username string, certType string) {
metricsMutex.Lock()
defer metricsMutex.Unlock()
certGenCounter.WithLabelValues(username, certType).Inc()
}(targetUser, "x509")
}
const secretInjectorPath = "/admin/inject"
func (state *RuntimeState) secretInjectorHandler(w http.ResponseWriter, r *http.Request) {
// checks this is only allowed when using TLS client certs.. all other authn
// mechanisms are considered invalid... for now no authz mechanisms are in place ie
// Any user with a valid cert can use this handler
if r.TLS == nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "")
logger.Printf("We require TLS\n")
return
}
if len(r.TLS.VerifiedChains) < 1 {
state.writeFailureResponse(w, r, http.StatusForbidden, "")
logger.Printf("Forbidden\n")
return
}
clientName := r.TLS.VerifiedChains[0][0].Subject.CommonName
logger.Printf("Got connection from %s", clientName)
r.ParseForm()
sshCAPassword, ok := r.Form["ssh_ca_password"]
if !ok {
state.writeFailureResponse(w, r, http.StatusBadRequest, "Invalid Post, missing data")
logger.Printf("missing ssh_ca_password")
return
}
state.Mutex.Lock()
defer state.Mutex.Unlock()
// TODO.. make network error blocks to goroutines