File size: 6,537 Bytes
117149d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
diff --git a/pkg/cookies/cookies.go b/pkg/cookies/cookies.go
index be5ee451..5427b20d 100644
--- a/pkg/cookies/cookies.go
+++ b/pkg/cookies/cookies.go
@@ -60,14 +60,30 @@ func MakeCookieFromOptions(req *http.Request, opts *CookieOptions) *http.Cookie
 // by checking the X-Fowarded-Host and host header of an an http request
 func GetCookieDomain(req *http.Request, cookieDomains []string) string {
 	host := requestutil.GetRequestHost(req)
+	if h, _, err := net.SplitHostPort(host); err == nil {
+		host = h
+	}
 	for _, domain := range cookieDomains {
-		if strings.HasSuffix(host, domain) {
+		if hostInDomain(host, domain) {
 			return domain
 		}
 	}
 	return ""
 }
 
+// hostInDomain reports whether host sits inside the cookie domain. Membership
+// is decided on whole DNS labels: sharing a character suffix with the domain
+// is not the same as being part of it.
+func hostInDomain(host, domain string) bool {
+	if host == "" || domain == "" {
+		return false
+	}
+	if strings.HasPrefix(domain, ".") {
+		return strings.HasSuffix(host, domain)
+	}
+	return host == domain || strings.HasSuffix(host, "."+domain)
+}
+
 // ParseSameSite a valid http.SameSite value from a user supplied string for use of making cookies.
 func ParseSameSite(v string) http.SameSite {
 	switch v {
diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go
index 2614f378..ddd09737 100644
--- a/pkg/cookies/csrf.go
+++ b/pkg/cookies/csrf.go
@@ -191,24 +191,52 @@ func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *ht
 	}
 
 	decodedCookies := []*csrf{}
+	undecodableCookies := []*http.Cookie{}
 	for _, cookie := range existingCsrfCookies {
 		decodedCookie, err := decodeCSRFCookie(cookie, opts)
 		if err != nil {
+			undecodableCookies = append(undecodableCookies, cookie)
 			continue
 		}
 		decodedCookies = append(decodedCookies, decodedCookie)
 	}
 
-	// delete the X oldest cookies
+	// delete the X oldest cookies, counting every CSRF cookie the request
+	// carries. Cookies that no longer decode can never be used again, so they
+	// go first.
 	slices.SortStableFunc(decodedCookies, func(a, b *csrf) int {
 		return a.clock().Compare(b.clock())
 	})
 
-	for i := 0; i < len(decodedCookies)-opts.CSRFPerRequestLimit; i++ {
+	excess := len(existingCsrfCookies) - opts.CSRFPerRequestLimit
+	for _, cookie := range undecodableCookies {
+		if excess <= 0 {
+			break
+		}
+		clearCsrfCookieByName(opts, rw, req, cookie.Name)
+		excess--
+	}
+	for i := 0; i < len(decodedCookies) && excess > 0; i++ {
 		decodedCookies[i].ClearCookie(rw, req)
+		excess--
 	}
 }
 
+// clearCsrfCookieByName removes a CSRF cookie the proxy could not decode, and
+// so has no csrf value to rebuild the name from.
+func clearCsrfCookieByName(opts *options.Cookie, rw http.ResponseWriter, req *http.Request, name string) {
+	http.SetCookie(rw, MakeCookieFromOptions(req, &CookieOptions{
+		Name:       name,
+		Value:      "",
+		Domains:    opts.Domains,
+		Expiration: time.Hour * -1,
+		SameSite:   getCSRFSameSite(opts),
+		Path:       opts.Path,
+		HTTPOnly:   opts.HTTPOnly,
+		Secure:     opts.Secure,
+	}))
+}
+
 // ClearCookie removes the CSRF cookie
 func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) {
 	csrfCookieOptions := &CookieOptions{
diff --git a/pkg/sessions/cookie/session_store.go b/pkg/sessions/cookie/session_store.go
index a4da3734..3e44a99a 100644
--- a/pkg/sessions/cookie/session_store.go
+++ b/pkg/sessions/cookie/session_store.go
@@ -5,7 +5,8 @@ import (
 	"errors"
 	"fmt"
 	"net/http"
-	"regexp"
+	"strconv"
+	"strings"
 	"time"
 
 	"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
@@ -71,30 +72,47 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
 // Clear clears any saved session information by writing a cookie to
 // clear the session
 func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
-	// matches CookieName, CookieName_<number>
-	var cookieNameRegex = regexp.MustCompile(fmt.Sprintf("^%s(_\\d+)?$", s.Cookie.Name))
-
 	for _, c := range req.Cookies() {
-		if cookieNameRegex.MatchString(c.Name) {
-			sessionCookieOptions := &pkgcookies.CookieOptions{
-				Name:       c.Name,
-				Value:      "",
-				Domains:    s.Cookie.Domains,
-				Expiration: time.Hour * -1,
-				SameSite:   s.Cookie.SameSite,
-				Path:       s.Cookie.Path,
-				HTTPOnly:   s.Cookie.HTTPOnly,
-				Secure:     s.Cookie.Secure,
-			}
-			clearCookie := pkgcookies.MakeCookieFromOptions(req, sessionCookieOptions)
-
-			http.SetCookie(rw, clearCookie)
+		if s.ownsCookieName(c.Name) {
+			http.SetCookie(rw, s.expireCookie(req, c.Name))
 		}
 	}
 
 	return nil
 }
 
+// ownsCookieName reports whether name is one of the names this store writes
+// the session under: the configured name, or one of the chunk names produced
+// by splitCookieName for it.
+func (s *SessionStore) ownsCookieName(name string) bool {
+	if name == s.Cookie.Name {
+		return true
+	}
+	i := strings.LastIndex(name, "_")
+	if i < 0 {
+		return false
+	}
+	count, err := strconv.Atoi(name[i+1:])
+	if err != nil || count < 0 {
+		return false
+	}
+	return splitCookieName(s.Cookie.Name, count) == name
+}
+
+// expireCookie builds a cookie that asks the client to drop name.
+func (s *SessionStore) expireCookie(req *http.Request, name string) *http.Cookie {
+	return pkgcookies.MakeCookieFromOptions(req, &pkgcookies.CookieOptions{
+		Name:       name,
+		Value:      "",
+		Domains:    s.Cookie.Domains,
+		Expiration: time.Hour * -1,
+		SameSite:   s.Cookie.SameSite,
+		Path:       s.Cookie.Path,
+		HTTPOnly:   s.Cookie.HTTPOnly,
+		Secure:     s.Cookie.Secure,
+	})
+}
+
 // VerifyConnection always return no-error, as there's no connection
 // in this store
 func (s *SessionStore) VerifyConnection(_ context.Context) error {
@@ -121,8 +139,21 @@ func (s *SessionStore) setSessionCookie(rw http.ResponseWriter, req *http.Reques
 	if err != nil {
 		return err
 	}
+	written := make(map[string]struct{}, len(cookies))
 	for _, c := range cookies {
 		http.SetCookie(rw, c)
+		written[c.Name] = struct{}{}
+	}
+	// A session that needs a different number of cookies than the one already
+	// on the client leaves names behind. Those are still sent back on the next
+	// request and would be joined into the value, so expire them here.
+	for _, c := range req.Cookies() {
+		if _, rewritten := written[c.Name]; rewritten {
+			continue
+		}
+		if s.ownsCookieName(c.Name) {
+			http.SetCookie(rw, s.expireCookie(req, c.Name))
+		}
 	}
 	return nil
 }