Skip to content

Commit d9d763d

Browse files
enjncdc
authored andcommitted
UPSTREAM: 121196: Prevent rapid reset http2 DOS on API server
This change fully addresses CVE-2023-44487 and CVE-2023-39325 for the API server when the client is unauthenticated. The changes to util/runtime are required because otherwise a large number of requests can get blocked on the time.Sleep calls. For unauthenticated clients (either via 401 or the anonymous user), we simply no longer allow such clients to hold open http2 connections. They can use http2, but with the performance of http1 (with keep-alive disabled). Since this change has the potential to cause issues, the UnauthenticatedHTTP2DOSMitigation feature gate can be disabled to remove this protection (it is enabled by default). For example, when the API server is fronted by an L7 load balancer that is set up to mitigate http2 attacks, unauthenticated clients could force disable connection reuse between the load balancer and the API server (many incoming connections could share the same backend connection). An API server that is on a private network may opt to disable this protection to prevent performance regressions for unauthenticated clients. For all other clients, we rely on the golang.org/x/net fix in golang/net@b225e7c That change is not sufficient to adequately protect against a motivated client - future changes to Kube and/or golang.org/x/net will be explored to address this gap. The Kube API server now uses a max stream of 100 instead of 250 (this matches the Go http2 client default). This lowers the abuse limit from 1000 to 400. Signed-off-by: Monis Khan <[email protected]> (cherry picked from commit 238d89c)
1 parent ac4be70 commit d9d763d

File tree

6 files changed

+296
-7
lines changed

6 files changed

+296
-7
lines changed

staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -126,14 +126,17 @@ type rudimentaryErrorBackoff struct {
126126
// OnError will block if it is called more often than the embedded period time.
127127
// This will prevent overly tight hot error loops.
128128
func (r *rudimentaryErrorBackoff) OnError(error) {
129+
now := time.Now() // start the timer before acquiring the lock
129130
r.lastErrorTimeLock.Lock()
130-
defer r.lastErrorTimeLock.Unlock()
131-
d := time.Since(r.lastErrorTime)
132-
if d < r.minPeriod {
133-
// If the time moves backwards for any reason, do nothing
134-
time.Sleep(r.minPeriod - d)
135-
}
131+
d := now.Sub(r.lastErrorTime)
136132
r.lastErrorTime = time.Now()
133+
r.lastErrorTimeLock.Unlock()
134+
135+
// Do not sleep with the lock held because that causes all callers of HandleError to block.
136+
// We only want the current goroutine to block.
137+
// A negative or zero duration causes time.Sleep to return immediately.
138+
// If the time moves backwards for any reason, do nothing.
139+
time.Sleep(r.minPeriod - d)
137140
}
138141

139142
// GetCaller returns the caller of the function that calls it.

staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@ import (
2424
"os"
2525
"regexp"
2626
"strings"
27+
"sync"
2728
"testing"
29+
"time"
2830
)
2931

3032
func TestHandleCrash(t *testing.T) {
@@ -156,3 +158,27 @@ func captureStderr(f func()) (string, error) {
156158

157159
return <-resultCh, nil
158160
}
161+
162+
func Test_rudimentaryErrorBackoff_OnError_ParallelSleep(t *testing.T) {
163+
r := &rudimentaryErrorBackoff{
164+
minPeriod: time.Second,
165+
}
166+
167+
start := make(chan struct{})
168+
var wg sync.WaitGroup
169+
for i := 0; i < 30; i++ {
170+
wg.Add(1)
171+
go func() {
172+
<-start
173+
r.OnError(nil) // input error is ignored
174+
wg.Done()
175+
}()
176+
}
177+
st := time.Now()
178+
close(start)
179+
wg.Wait()
180+
181+
if since := time.Since(st); since > 5*time.Second {
182+
t.Errorf("OnError slept for too long: %s", since)
183+
}
184+
}

staging/src/k8s.io/apiserver/pkg/endpoints/filters/authentication.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,11 @@ import (
2929
"k8s.io/apiserver/pkg/authentication/authenticator"
3030
"k8s.io/apiserver/pkg/authentication/authenticatorfactory"
3131
"k8s.io/apiserver/pkg/authentication/request/headerrequest"
32+
"k8s.io/apiserver/pkg/authentication/user"
3233
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
3334
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
35+
genericfeatures "k8s.io/apiserver/pkg/features"
36+
utilfeature "k8s.io/apiserver/pkg/util/feature"
3437
"k8s.io/klog/v2"
3538
)
3639

@@ -101,13 +104,36 @@ func withAuthentication(handler http.Handler, auth authenticator.Request, failed
101104
)
102105
}
103106

107+
// http2 is an expensive protocol that is prone to abuse,
108+
// see CVE-2023-44487 and CVE-2023-39325 for an example.
109+
// Do not allow unauthenticated clients to keep these
110+
// connections open (i.e. basically degrade them to the
111+
// performance of http1 with keep-alive disabled).
112+
if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.UnauthenticatedHTTP2DOSMitigation) && req.ProtoMajor == 2 && isAnonymousUser(resp.User) {
113+
// limit this connection to just this request,
114+
// and then send a GOAWAY and tear down the TCP connection
115+
// https://github.com/golang/net/commit/97aa3a539ec716117a9d15a4659a911f50d13c3c
116+
w.Header().Set("Connection", "close")
117+
}
118+
104119
req = req.WithContext(genericapirequest.WithUser(req.Context(), resp.User))
105120
handler.ServeHTTP(w, req)
106121
})
107122
}
108123

109124
func Unauthorized(s runtime.NegotiatedSerializer) http.Handler {
110125
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
126+
// http2 is an expensive protocol that is prone to abuse,
127+
// see CVE-2023-44487 and CVE-2023-39325 for an example.
128+
// Do not allow unauthenticated clients to keep these
129+
// connections open (i.e. basically degrade them to the
130+
// performance of http1 with keep-alive disabled).
131+
if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.UnauthenticatedHTTP2DOSMitigation) && req.ProtoMajor == 2 {
132+
// limit this connection to just this request,
133+
// and then send a GOAWAY and tear down the TCP connection
134+
// https://github.com/golang/net/commit/97aa3a539ec716117a9d15a4659a911f50d13c3c
135+
w.Header().Set("Connection", "close")
136+
}
111137
ctx := req.Context()
112138
requestInfo, found := genericapirequest.RequestInfoFrom(ctx)
113139
if !found {
@@ -127,3 +153,15 @@ func audiencesAreAcceptable(apiAuds, responseAudiences authenticator.Audiences)
127153

128154
return len(apiAuds.Intersect(responseAudiences)) > 0
129155
}
156+
157+
func isAnonymousUser(u user.Info) bool {
158+
if u.GetName() == user.Anonymous {
159+
return true
160+
}
161+
for _, group := range u.GetGroups() {
162+
if group == user.AllUnauthenticated {
163+
return true
164+
}
165+
}
166+
return false
167+
}

staging/src/k8s.io/apiserver/pkg/endpoints/filters/authentication_test.go

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,31 @@ package filters
1818

1919
import (
2020
"context"
21+
"crypto/tls"
22+
"crypto/x509"
2123
"errors"
24+
"io"
25+
"net"
2226
"net/http"
2327
"net/http/httptest"
28+
"sync/atomic"
2429
"testing"
2530
"time"
2631

2732
"github.com/google/go-cmp/cmp"
2833
"github.com/stretchr/testify/assert"
34+
"golang.org/x/net/http2"
2935

3036
"k8s.io/apiserver/pkg/authentication/authenticator"
3137
"k8s.io/apiserver/pkg/authentication/authenticatorfactory"
38+
"k8s.io/apiserver/pkg/authentication/request/anonymous"
3239
"k8s.io/apiserver/pkg/authentication/request/headerrequest"
3340
"k8s.io/apiserver/pkg/authentication/user"
3441
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
42+
"k8s.io/apiserver/pkg/features"
43+
utilfeature "k8s.io/apiserver/pkg/util/feature"
44+
"k8s.io/client-go/kubernetes/scheme"
45+
featuregatetesting "k8s.io/component-base/featuregate/testing"
3546
)
3647

3748
func TestAuthenticateRequestWithAud(t *testing.T) {
@@ -465,3 +476,191 @@ func TestAuthenticateRequestClearHeaders(t *testing.T) {
465476
})
466477
}
467478
}
479+
480+
func TestUnauthenticatedHTTP2ClientConnectionClose(t *testing.T) {
481+
s := httptest.NewUnstartedServer(WithAuthentication(
482+
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }),
483+
authenticator.RequestFunc(func(r *http.Request) (*authenticator.Response, bool, error) {
484+
switch r.Header.Get("Authorization") {
485+
case "known":
486+
return &authenticator.Response{User: &user.DefaultInfo{Name: "panda"}}, true, nil
487+
case "error":
488+
return nil, false, errors.New("authn err")
489+
case "anonymous":
490+
return anonymous.NewAuthenticator().AuthenticateRequest(r)
491+
case "anonymous_group":
492+
return &authenticator.Response{User: &user.DefaultInfo{Groups: []string{user.AllUnauthenticated}}}, true, nil
493+
default:
494+
return nil, false, nil
495+
}
496+
}),
497+
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
498+
r = r.WithContext(genericapirequest.WithRequestInfo(r.Context(), &genericapirequest.RequestInfo{}))
499+
Unauthorized(scheme.Codecs).ServeHTTP(w, r)
500+
}),
501+
nil,
502+
nil,
503+
))
504+
505+
http2Options := &http2.Server{}
506+
507+
if err := http2.ConfigureServer(s.Config, http2Options); err != nil {
508+
t.Fatal(err)
509+
}
510+
511+
s.TLS = s.Config.TLSConfig
512+
513+
s.StartTLS()
514+
t.Cleanup(s.Close)
515+
516+
const reqs = 4
517+
518+
cases := []struct {
519+
name string
520+
authorizationHeader string
521+
skipHTTP2DOSMitigation bool
522+
expectConnections uint64
523+
}{
524+
{
525+
name: "known",
526+
authorizationHeader: "known",
527+
skipHTTP2DOSMitigation: false,
528+
expectConnections: 1,
529+
},
530+
{
531+
name: "error",
532+
authorizationHeader: "error",
533+
skipHTTP2DOSMitigation: false,
534+
expectConnections: reqs,
535+
},
536+
{
537+
name: "anonymous",
538+
authorizationHeader: "anonymous",
539+
skipHTTP2DOSMitigation: false,
540+
expectConnections: reqs,
541+
},
542+
{
543+
name: "anonymous_group",
544+
authorizationHeader: "anonymous_group",
545+
skipHTTP2DOSMitigation: false,
546+
expectConnections: reqs,
547+
},
548+
{
549+
name: "other",
550+
authorizationHeader: "other",
551+
skipHTTP2DOSMitigation: false,
552+
expectConnections: reqs,
553+
},
554+
555+
{
556+
name: "known skip=true",
557+
authorizationHeader: "known",
558+
skipHTTP2DOSMitigation: true,
559+
expectConnections: 1,
560+
},
561+
{
562+
name: "error skip=true",
563+
authorizationHeader: "error",
564+
skipHTTP2DOSMitigation: true,
565+
expectConnections: 1,
566+
},
567+
{
568+
name: "anonymous skip=true",
569+
authorizationHeader: "anonymous",
570+
skipHTTP2DOSMitigation: true,
571+
expectConnections: 1,
572+
},
573+
{
574+
name: "anonymous_group skip=true",
575+
authorizationHeader: "anonymous_group",
576+
skipHTTP2DOSMitigation: true,
577+
expectConnections: 1,
578+
},
579+
{
580+
name: "other skip=true",
581+
authorizationHeader: "other",
582+
skipHTTP2DOSMitigation: true,
583+
expectConnections: 1,
584+
},
585+
}
586+
587+
rootCAs := x509.NewCertPool()
588+
rootCAs.AddCert(s.Certificate())
589+
590+
for _, tc := range cases {
591+
t.Run(tc.name, func(t *testing.T) {
592+
f := func(t *testing.T, nextProto string, expectConnections uint64) {
593+
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.UnauthenticatedHTTP2DOSMitigation, !tc.skipHTTP2DOSMitigation)()
594+
595+
var localAddrs atomic.Uint64 // indicates how many TCP connection set up
596+
597+
tlsConfig := &tls.Config{
598+
RootCAs: rootCAs,
599+
NextProtos: []string{nextProto},
600+
}
601+
602+
dailer := tls.Dialer{
603+
Config: tlsConfig,
604+
}
605+
606+
tr := &http.Transport{
607+
TLSHandshakeTimeout: 10 * time.Second,
608+
TLSClientConfig: tlsConfig,
609+
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
610+
conn, err := dailer.DialContext(ctx, network, addr)
611+
if err != nil {
612+
return nil, err
613+
}
614+
615+
localAddrs.Add(1)
616+
617+
return conn, nil
618+
},
619+
}
620+
621+
tr.MaxIdleConnsPerHost = 1 // allow http1 to have keep alive connections open
622+
if nextProto == http2.NextProtoTLS {
623+
// Disable connection pooling to avoid additional connections
624+
// that cause the test to flake
625+
tr.MaxIdleConnsPerHost = -1
626+
if err := http2.ConfigureTransport(tr); err != nil {
627+
t.Fatal(err)
628+
}
629+
}
630+
631+
client := &http.Client{
632+
Transport: tr,
633+
}
634+
635+
for i := 0; i < reqs; i++ {
636+
req, err := http.NewRequest(http.MethodGet, s.URL, nil)
637+
if err != nil {
638+
t.Fatal(err)
639+
}
640+
if len(tc.authorizationHeader) > 0 {
641+
req.Header.Set("Authorization", tc.authorizationHeader)
642+
}
643+
644+
resp, err := client.Do(req)
645+
if err != nil {
646+
t.Fatal(err)
647+
}
648+
_, _ = io.Copy(io.Discard, resp.Body)
649+
_ = resp.Body.Close()
650+
}
651+
652+
if expectConnections != localAddrs.Load() {
653+
t.Fatalf("expect TCP connection: %d, actual: %d", expectConnections, localAddrs.Load())
654+
}
655+
}
656+
657+
t.Run(http2.NextProtoTLS, func(t *testing.T) {
658+
f(t, http2.NextProtoTLS, tc.expectConnections)
659+
})
660+
661+
t.Run("http/1.1", func(t *testing.T) {
662+
f(t, "http/1.1", 1)
663+
})
664+
})
665+
}
666+
}

staging/src/k8s.io/apiserver/pkg/features/kube_features.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,24 @@ const (
182182
// Enables server-side field validation.
183183
ServerSideFieldValidation featuregate.Feature = "ServerSideFieldValidation"
184184

185+
// owner: @enj
186+
// beta: v1.29
187+
//
188+
// Enables http2 DOS mitigations for unauthenticated clients.
189+
//
190+
// Some known reasons to disable these mitigations:
191+
//
192+
// An API server that is fronted by an L7 load balancer that is set up
193+
// to mitigate http2 attacks may opt to disable this protection to prevent
194+
// unauthenticated clients from disabling connection reuse between the load
195+
// balancer and the API server (many incoming connections could share the
196+
// same backend connection).
197+
//
198+
// An API server that is on a private network may opt to disable this
199+
// protection to prevent performance regressions for unauthenticated
200+
// clients.
201+
UnauthenticatedHTTP2DOSMitigation featuregate.Feature = "UnauthenticatedHTTP2DOSMitigation"
202+
185203
// owner: @caesarxuchao @roycaihw
186204
// alpha: v1.20
187205
//
@@ -276,6 +294,8 @@ var defaultKubernetesFeatureGates = map[featuregate.Feature]featuregate.FeatureS
276294

277295
StorageVersionHash: {Default: true, PreRelease: featuregate.Beta},
278296

297+
UnauthenticatedHTTP2DOSMitigation: {Default: true, PreRelease: featuregate.Beta},
298+
279299
WatchBookmark: {Default: true, PreRelease: featuregate.GA, LockToDefault: true},
280300

281301
InPlacePodVerticalScaling: {Default: false, PreRelease: featuregate.Alpha},

staging/src/k8s.io/apiserver/pkg/server/secure_serving.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,10 @@ func (s *SecureServingInfo) Serve(handler http.Handler, shutdownTimeout time.Dur
189189
if s.HTTP2MaxStreamsPerConnection > 0 {
190190
http2Options.MaxConcurrentStreams = uint32(s.HTTP2MaxStreamsPerConnection)
191191
} else {
192-
http2Options.MaxConcurrentStreams = 250
192+
// match http2.initialMaxConcurrentStreams used by clients
193+
// this makes it so that a malicious client can only open 400 streams before we forcibly close the connection
194+
// https://github.com/golang/net/commit/b225e7ca6dde1ef5a5ae5ce922861bda011cfabd
195+
http2Options.MaxConcurrentStreams = 100
193196
}
194197

195198
// increase the connection buffer size from the 1MB default to handle the specified number of concurrent streams

0 commit comments

Comments
 (0)