| 1 |
/* |
| 2 |
Copyright 2014 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package filters |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"net/http" |
| 24 |
"time" |
| 25 |
|
| 26 |
apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 27 |
"k8s.io/apimachinery/pkg/runtime" |
| 28 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 29 |
"k8s.io/apiserver/pkg/authentication/authenticator" |
| 30 |
"k8s.io/apiserver/pkg/authentication/authenticatorfactory" |
| 31 |
"k8s.io/apiserver/pkg/authentication/request/headerrequest" |
| 32 |
"k8s.io/apiserver/pkg/authentication/user" |
| 33 |
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" |
| 34 |
genericapirequest "k8s.io/apiserver/pkg/endpoints/request" |
| 35 |
genericfeatures "k8s.io/apiserver/pkg/features" |
| 36 |
utilfeature "k8s.io/apiserver/pkg/util/feature" |
| 37 |
"k8s.io/klog/v2" |
| 38 |
) |
| 39 |
|
| 40 |
type authenticationRecordMetricsFunc func(context.Context, *authenticator.Response, bool, error, authenticator.Audiences, time.Time, time.Time) |
| 41 |
|
| 42 |
// WithAuthentication creates an http handler that tries to authenticate the given request as a user, and then |
| 43 |
// stores any such user found onto the provided context for the request. If authentication fails or returns an error |
| 44 |
// the failed handler is used. On success, "Authorization" header is removed from the request and handler |
| 45 |
// is invoked to serve the request. |
| 46 |
func WithAuthentication(handler http.Handler, auth authenticator.Request, failed http.Handler, apiAuds authenticator.Audiences, requestHeaderConfig *authenticatorfactory.RequestHeaderConfig) http.Handler { |
| 47 |
return withAuthentication(handler, auth, failed, apiAuds, requestHeaderConfig, recordAuthenticationMetrics) |
| 48 |
} |
| 49 |
|
| 50 |
func withAuthentication(handler http.Handler, auth authenticator.Request, failed http.Handler, apiAuds authenticator.Audiences, requestHeaderConfig *authenticatorfactory.RequestHeaderConfig, metrics authenticationRecordMetricsFunc) http.Handler { |
| 51 |
if auth == nil { |
| 52 |
klog.Warning("Authentication is disabled") |
| 53 |
return handler |
| 54 |
} |
| 55 |
standardRequestHeaderConfig := &authenticatorfactory.RequestHeaderConfig{ |
| 56 |
UsernameHeaders: headerrequest.StaticStringSlice{"X-Remote-User"}, |
| 57 |
UIDHeaders: headerrequest.StaticStringSlice{"X-Remote-Uid"}, |
| 58 |
GroupHeaders: headerrequest.StaticStringSlice{"X-Remote-Group"}, |
| 59 |
ExtraHeaderPrefixes: headerrequest.StaticStringSlice{"X-Remote-Extra-"}, |
| 60 |
} |
| 61 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 62 |
authenticationStart := time.Now() |
| 63 |
|
| 64 |
if len(apiAuds) > 0 { |
| 65 |
req = req.WithContext(authenticator.WithAudiences(req.Context(), apiAuds)) |
| 66 |
} |
| 67 |
resp, ok, err := auth.AuthenticateRequest(req) |
| 68 |
authenticationFinish := time.Now() |
| 69 |
defer func() { |
| 70 |
metrics(req.Context(), resp, ok, err, apiAuds, authenticationStart, authenticationFinish) |
| 71 |
genericapirequest.TrackAuthenticationLatency(req.Context(), authenticationFinish.Sub(authenticationStart)) |
| 72 |
}() |
| 73 |
if err != nil || !ok { |
| 74 |
if err != nil { |
| 75 |
klog.ErrorS(err, "Unable to authenticate the request") |
| 76 |
} |
| 77 |
failed.ServeHTTP(w, req) |
| 78 |
return |
| 79 |
} |
| 80 |
|
| 81 |
if !audiencesAreAcceptable(apiAuds, resp.Audiences) { |
| 82 |
err = fmt.Errorf("unable to match the audience: %v , accepted: %v", resp.Audiences, apiAuds) |
| 83 |
klog.Error(err) |
| 84 |
failed.ServeHTTP(w, req) |
| 85 |
return |
| 86 |
} |
| 87 |
|
| 88 |
// authorization header is not required anymore in case of a successful authentication. |
| 89 |
req.Header.Del("Authorization") |
| 90 |
|
| 91 |
// delete standard front proxy headers |
| 92 |
headerrequest.ClearAuthenticationHeaders( |
| 93 |
req.Header, |
| 94 |
standardRequestHeaderConfig.UsernameHeaders, |
| 95 |
standardRequestHeaderConfig.UIDHeaders, |
| 96 |
standardRequestHeaderConfig.GroupHeaders, |
| 97 |
standardRequestHeaderConfig.ExtraHeaderPrefixes, |
| 98 |
) |
| 99 |
|
| 100 |
// also delete any custom front proxy headers |
| 101 |
if requestHeaderConfig != nil { |
| 102 |
headerrequest.ClearAuthenticationHeaders( |
| 103 |
req.Header, |
| 104 |
requestHeaderConfig.UsernameHeaders, |
| 105 |
requestHeaderConfig.UIDHeaders, |
| 106 |
requestHeaderConfig.GroupHeaders, |
| 107 |
requestHeaderConfig.ExtraHeaderPrefixes, |
| 108 |
) |
| 109 |
} |
| 110 |
|
| 111 |
// http2 is an expensive protocol that is prone to abuse, |
| 112 |
// see CVE-2023-44487 and CVE-2023-39325 for an example. |
| 113 |
// Do not allow unauthenticated clients to keep these |
| 114 |
// connections open (i.e. basically degrade them to the |
| 115 |
// performance of http1 with keep-alive disabled). |
| 116 |
if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.UnauthenticatedHTTP2DOSMitigation) && req.ProtoMajor == 2 && isAnonymousUser(resp.User) { |
| 117 |
// limit this connection to just this request, |
| 118 |
// and then send a GOAWAY and tear down the TCP connection |
| 119 |
// https://github.com/golang/net/commit/97aa3a539ec716117a9d15a4659a911f50d13c3c |
| 120 |
w.Header().Set("Connection", "close") |
| 121 |
} |
| 122 |
req = req.WithContext(genericapirequest.WithUser(req.Context(), resp.User)) |
| 123 |
handler.ServeHTTP(w, req) |
| 124 |
}) |
| 125 |
} |
| 126 |
|
| 127 |
func Unauthorized(s runtime.NegotiatedSerializer) http.Handler { |
| 128 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 129 |
// http2 is an expensive protocol that is prone to abuse, |
| 130 |
// see CVE-2023-44487 and CVE-2023-39325 for an example. |
| 131 |
// Do not allow unauthenticated clients to keep these |
| 132 |
// connections open (i.e. basically degrade them to the |
| 133 |
// performance of http1 with keep-alive disabled). |
| 134 |
if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.UnauthenticatedHTTP2DOSMitigation) && req.ProtoMajor == 2 { |
| 135 |
// limit this connection to just this request, |
| 136 |
// and then send a GOAWAY and tear down the TCP connection |
| 137 |
// https://github.com/golang/net/commit/97aa3a539ec716117a9d15a4659a911f50d13c3c |
| 138 |
w.Header().Set("Connection", "close") |
| 139 |
} |
| 140 |
ctx := req.Context() |
| 141 |
requestInfo, found := genericapirequest.RequestInfoFrom(ctx) |
| 142 |
if !found { |
| 143 |
responsewriters.InternalError(w, req, errors.New("no RequestInfo found in the context")) |
| 144 |
return |
| 145 |
} |
| 146 |
|
| 147 |
gv := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion} |
| 148 |
responsewriters.ErrorNegotiated(apierrors.NewUnauthorized("Unauthorized"), s, gv, w, req) |
| 149 |
}) |
| 150 |
} |
| 151 |
|
| 152 |
func audiencesAreAcceptable(apiAuds, responseAudiences authenticator.Audiences) bool { |
| 153 |
if len(apiAuds) == 0 || len(responseAudiences) == 0 { |
| 154 |
return true |
| 155 |
} |
| 156 |
|
| 157 |
return len(apiAuds.Intersect(responseAudiences)) > 0 |
| 158 |
} |
| 159 |
|
| 160 |
func isAnonymousUser(u user.Info) bool { |
| 161 |
if u.GetName() == user.Anonymous { |
| 162 |
return true |
| 163 |
} |
| 164 |
for _, group := range u.GetGroups() { |
| 165 |
if group == user.AllUnauthenticated { |
| 166 |
return true |
| 167 |
} |
| 168 |
} |
| 169 |
return false |
| 170 |
} |