blob: 09d7db8cc903989221f00ebfe1db7b8fd35b4906 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package filters
18
19import (
20 "errors"
21 "fmt"
22 "net/http"
23 "strings"
24
25 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26 utilruntime "k8s.io/apimachinery/pkg/util/runtime"
27 auditinternal "k8s.io/apiserver/pkg/apis/audit"
28 "k8s.io/apiserver/pkg/audit"
29 "k8s.io/apiserver/pkg/audit/policy"
30 "k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
31)
32
33// WithFailedAuthenticationAudit decorates a failed http.Handler used in WithAuthentication handler.
34// It is meant to log only failed authentication requests.
35func WithFailedAuthenticationAudit(failedHandler http.Handler, sink audit.Sink, policy policy.Checker) http.Handler {
36 if sink == nil || policy == nil {
37 return failedHandler
38 }
39 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
40 req, ev, omitStages, err := createAuditEventAndAttachToContext(req, policy)
41 if err != nil {
42 utilruntime.HandleError(fmt.Errorf("failed to create audit event: %v", err))
43 responsewriters.InternalError(w, req, errors.New("failed to create audit event"))
44 return
45 }
46 if ev == nil {
47 failedHandler.ServeHTTP(w, req)
48 return
49 }
50
51 ev.ResponseStatus = &metav1.Status{}
52 ev.ResponseStatus.Message = getAuthMethods(req)
53 ev.Stage = auditinternal.StageResponseStarted
54
55 rw := decorateResponseWriter(w, ev, sink, omitStages)
56 failedHandler.ServeHTTP(rw, req)
57 })
58}
59
60func getAuthMethods(req *http.Request) string {
61 authMethods := []string{}
62
63 if _, _, ok := req.BasicAuth(); ok {
64 authMethods = append(authMethods, "basic")
65 }
66
67 auth := strings.TrimSpace(req.Header.Get("Authorization"))
68 parts := strings.Split(auth, " ")
69 if len(parts) > 1 && strings.ToLower(parts[0]) == "bearer" {
70 authMethods = append(authMethods, "bearer")
71 }
72
73 token := strings.TrimSpace(req.URL.Query().Get("access_token"))
74 if len(token) > 0 {
75 authMethods = append(authMethods, "access_token")
76 }
77
78 if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
79 authMethods = append(authMethods, "x509")
80 }
81
82 if len(authMethods) > 0 {
83 return fmt.Sprintf("Authentication failed, attempted: %s", strings.Join(authMethods, ", "))
84 }
85 return "Authentication failed, no credentials provided"
86}