git.iko.soy/typeable/oauth2-proxy
on master help sign in
fix: runtime error: index out of range (0) with length 0 (#2328)

* Issue 2311: runtime error: index out of range [0] with length 0 while extracting state of of the csrf --------- Co-authored-by: tuunit <jan@larwig.com>

commitff761d2523c2b4e1fd291b8833e667bb65b41de5 authorNuno Miguel Micaelo Borges <miguelborges99@gmail.com> dateTue 8 Oct 2024, 13:40 (2 years ago) parent642ba17
4 files changed+54−28
CHANGELOG.md+1 oauthproxy.go+39−9 pkg/cookies/csrf.go+8−15 pkg/cookies/csrf_test.go+6−4
CHANGELOG.md+1
@@ -10,6 +10,7 @@
1010
1111- [#2803](https://github.com/oauth2-proxy/oauth2-proxy/pull/2803) fix: self signed certificate handling in v7.7.0 (@tuunit)
1212- [#2619](https://github.com/oauth2-proxy/oauth2-proxy/pull/2619) fix: unable to use hyphen in JSON path for oidc-groups-claim option (@rd-danny-fleer)
13+- [#2311](https://github.com/oauth2-proxy/oauth2-proxy/pull/2311) fix: runtime error: index out of range (0) with length 0 (@miguelborges99 / @tuunit)
1314
1415# V7.7.0
1516
oauthproxy.go+39−9
@@ -870,9 +870,22 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
870870 return
871871 }
872872
873− csrf, err := cookies.LoadCSRFCookie(req, p.CookieOptions)
873+ nonce, appRedirect, err := decodeState(req.Form.Get("state"), p.encodeState)
874+ if err != nil {
875+ logger.Errorf("Error while parsing OAuth2 state: %v", err)
876+ p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
877+ return
878+ }
879+
880+ // calculate the cookie name
881+ cookieName := cookies.GenerateCookieName(p.CookieOptions, nonce)
882+ // Try to find the CSRF cookie and decode it
883+ csrf, err := cookies.LoadCSRFCookie(req, cookieName, p.CookieOptions)
874884 if err != nil {
875− logger.Println(req, logger.AuthFailure, "Invalid authentication via OAuth2. Error while loading CSRF cookie:", err.Error())
885+ // There are a lot of issues opened complaining about missing CSRF cookies.
886+ // Try to log the INs and OUTs of OAuthProxy, to be easier to analyse these issues.
887+ LoggingCSRFCookiesInOAuthCallback(req, cookieName)
888+ logger.Println(req, logger.AuthFailure, "Invalid authentication via OAuth2: unable to obtain CSRF cookie: %s (state=%s)", err, nonce)
876889 p.ErrorPage(rw, req, http.StatusForbidden, err.Error(), "Login Failed: Unable to find a valid CSRF token. Please try again.")
877890 return
878891 }
@@ -893,13 +906,6 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
893906
894907 csrf.ClearCookie(rw, req)
895908
896− nonce, appRedirect, err := decodeState(req.Form.Get("state"), p.encodeState)
897− if err != nil {
898− logger.Errorf("Error while parsing OAuth2 state: %v", err)
899− p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
900− return
901− }
902−
903909 if !csrf.CheckOAuthState(nonce) {
904910 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: CSRF token mismatch, potential attack")
905911 p.ErrorPage(rw, req, http.StatusForbidden, "CSRF token mismatch, potential attack", "Login Failed: Unable to find a valid CSRF token. Please try again.")
@@ -1297,3 +1303,27 @@ func (p *OAuthProxy) errorJSON(rw http.ResponseWriter, code int) {
12971303 // application/json
12981304 rw.Write([]byte("{}"))
12991305}
1306+
1307+// LoggingCSRFCookiesInOAuthCallback Log all CSRF cookies found in HTTP request OAuth callback,
1308+// which were successfully parsed
1309+func LoggingCSRFCookiesInOAuthCallback(req *http.Request, cookieName string) {
1310+ cookies := req.Cookies()
1311+ if len(cookies) == 0 {
1312+ logger.Println(req, logger.AuthFailure, "No cookies were found in OAuth callback.")
1313+ return
1314+ }
1315+
1316+ for _, c := range cookies {
1317+ if cookieName == c.Name {
1318+ logger.Println(req, logger.AuthFailure, "CSRF cookie %s was found in OAuth callback.", c.Name)
1319+ return
1320+ }
1321+
1322+ if strings.HasSuffix(c.Name, "_csrf") {
1323+ logger.Println(req, logger.AuthFailure, "CSRF cookie %s was found in OAuth callback, but it is not the expected one (%s).", c.Name, cookieName)
1324+ return
1325+ }
1326+ }
1327+
1328+ logger.Println(req, logger.AuthFailure, "Cookies were found in OAuth callback, but none was a CSRF cookie.")
1329+}
pkg/cookies/csrf.go+8−15
@@ -72,9 +72,7 @@ func NewCSRF(opts *options.Cookie, codeVerifier string) (CSRF, error) {
7272}
7373
7474// LoadCSRFCookie loads a CSRF object from a request's CSRF cookie
75−func LoadCSRFCookie(req *http.Request, opts *options.Cookie) (CSRF, error) {
76− cookieName := GenerateCookieName(req, opts)
77−
75+func LoadCSRFCookie(req *http.Request, cookieName string, opts *options.Cookie) (CSRF, error) {
7876 cookies := req.Cookies()
7977 for _, cookie := range cookies {
8078 if cookie.Name != cookieName {
@@ -89,17 +87,17 @@ func LoadCSRFCookie(req *http.Request, opts *options.Cookie) (CSRF, error) {
8987 return csrf, nil
9088 }
9189
92− return nil, errors.New("CSRF cookie not found")
90+ return nil, fmt.Errorf("CSRF cookie with name '%v' was not found", cookieName)
9391}
9492
9593// GenerateCookieName in case cookie options state that CSRF cookie has fixed name then set fixed name, otherwise
9694// build name based on the state
97−func GenerateCookieName(req *http.Request, opts *options.Cookie) string {
95+func GenerateCookieName(opts *options.Cookie, state string) string {
9896 stateSubstring := ""
9997 if opts.CSRFPerRequest {
10098 // csrfCookieName will include a substring of the state to enable multiple csrf cookies
10199 // in case of parallel requests
102− stateSubstring = ExtractStateSubstring(req)
100+ stateSubstring = ExtractStateSubstring(state)
103101 }
104102 return csrfCookieName(opts, stateSubstring)
105103}
@@ -218,20 +216,15 @@ func csrfCookieName(opts *options.Cookie, stateSubstring string) string {
218216 if stateSubstring == "" {
219217 return fmt.Sprintf("%v_csrf", opts.Name)
220218 }
221− return fmt.Sprintf("%v_csrf_%v", opts.Name, stateSubstring)
219+ return fmt.Sprintf("%v_%v_csrf", opts.Name, stateSubstring)
222220}
223221
224222// ExtractStateSubstring extract the initial state characters, to add it to the CSRF cookie name
225−func ExtractStateSubstring(req *http.Request) string {
223+func ExtractStateSubstring(state string) string {
226224 lastChar := csrfStateLength - 1
227225 stateSubstring := ""
228−
229− state := req.URL.Query()["state"]
230− if state[0] != "" {
231− state := state[0]
232− if lastChar <= len(state) {
233− stateSubstring = state[0:lastChar]
234− }
226+ if lastChar <= len(state) {
227+ stateSubstring = state[0:lastChar]
235228 }
236229 return stateSubstring
237230}
pkg/cookies/csrf_test.go+6−4
@@ -19,6 +19,7 @@ var _ = Describe("CSRF Cookie Tests", func() {
1919 cookieOpts *options.Cookie
2020 publicCSRF CSRF
2121 privateCSRF *csrf
22+ csrfName string
2223 )
2324
2425 BeforeEach(func() {
@@ -39,6 +40,7 @@ var _ = Describe("CSRF Cookie Tests", func() {
3940 Expect(err).ToNot(HaveOccurred())
4041
4142 privateCSRF = publicCSRF.(*csrf)
43+ csrfName = GenerateCookieName(cookieOpts, csrfNonce)
4244 })
4345
4446 Context("NewCSRF", func() {
@@ -175,7 +177,7 @@ var _ = Describe("CSRF Cookie Tests", func() {
175177 })
176178
177179 It("should return error when no cookie is set", func() {
178− csrf, err := LoadCSRFCookie(req, cookieOpts)
180+ csrf, err := LoadCSRFCookie(req, csrfName, cookieOpts)
179181 Expect(err).To(HaveOccurred())
180182 Expect(csrf).To(BeNil())
181183 })
@@ -191,7 +193,7 @@ var _ = Describe("CSRF Cookie Tests", func() {
191193 Value: encoded,
192194 })
193195
194− csrf, err := LoadCSRFCookie(req, cookieOpts)
196+ csrf, err := LoadCSRFCookie(req, csrfName, cookieOpts)
195197 Expect(err).ToNot(HaveOccurred())
196198 Expect(csrf).ToNot(BeNil())
197199 })
@@ -202,7 +204,7 @@ var _ = Describe("CSRF Cookie Tests", func() {
202204 Value: "invalid",
203205 })
204206
205− csrf, err := LoadCSRFCookie(req, cookieOpts)
207+ csrf, err := LoadCSRFCookie(req, csrfName, cookieOpts)
206208 Expect(err).To(HaveOccurred())
207209 Expect(csrf).To(BeNil())
208210 })
@@ -223,7 +225,7 @@ var _ = Describe("CSRF Cookie Tests", func() {
223225 Value: encoded,
224226 })
225227
226− csrf, err := LoadCSRFCookie(req, cookieOpts)
228+ csrf, err := LoadCSRFCookie(req, csrfName, cookieOpts)
227229 Expect(err).ToNot(HaveOccurred())
228230 Expect(csrf).ToNot(BeNil())
229231 })