Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: [#630] Use the correct algorithm for at_hash and c_hash #659

Merged
merged 4 commits into from
Apr 16, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions handler/openid/flow_hybrid.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ package openid

import (
"context"
"encoding/base64"
"time"

"github.com/ory/x/errorsx"
Expand Down Expand Up @@ -122,11 +121,11 @@ func (c *OpenIDConnectHybridHandler) HandleAuthorizeEndpointRequest(ctx context.
resp.AddParameter("code", code)
ar.SetResponseTypeHandled("code")

hash, err := c.Enigma.Hash(ctx, []byte(resp.GetParameters().Get("code")))
hash, err := c.IDTokenHandleHelper.ComputeHash(ctx, sess, resp.GetParameters().Get("code"))
if err != nil {
return err
}
claims.CodeHash = base64.RawURLEncoding.EncodeToString([]byte(hash[:c.Enigma.GetSigningMethodLength()/2]))
claims.CodeHash = hash

if ar.GetGrantedScopes().Has("openid") {
if err := c.OpenIDConnectRequestStorage.CreateOpenIDConnectSession(ctx, resp.GetCode(), ar.Sanitize(oidcParameters)); err != nil {
Expand All @@ -143,11 +142,11 @@ func (c *OpenIDConnectHybridHandler) HandleAuthorizeEndpointRequest(ctx context.
}
ar.SetResponseTypeHandled("token")

hash, err := c.Enigma.Hash(ctx, []byte(resp.GetParameters().Get("access_token")))
hash, err := c.IDTokenHandleHelper.ComputeHash(ctx, sess, resp.GetParameters().Get("access_token"))
if err != nil {
return err
}
claims.AccessTokenHash = base64.RawURLEncoding.EncodeToString([]byte(hash[:c.Enigma.GetSigningMethodLength()/2]))
claims.AccessTokenHash = hash
}

if resp.GetParameters().Get("state") == "" {
Expand Down
5 changes: 2 additions & 3 deletions handler/openid/flow_implicit.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ package openid

import (
"context"
"encoding/base64"

"github.com/ory/x/errorsx"

Expand Down Expand Up @@ -93,12 +92,12 @@ func (c *OpenIDConnectImplicitHandler) HandleAuthorizeEndpointRequest(ctx contex
}

ar.SetResponseTypeHandled("token")
hash, err := c.RS256JWTStrategy.Hash(ctx, []byte(resp.GetParameters().Get("access_token")))
hash, err := c.ComputeHash(ctx, sess, resp.GetParameters().Get("access_token"))
if err != nil {
return err
}

claims.AccessTokenHash = base64.RawURLEncoding.EncodeToString([]byte(hash[:c.RS256JWTStrategy.GetSigningMethodLength()/2]))
claims.AccessTokenHash = hash
} else {
resp.AddParameter("state", ar.GetState())
}
Expand Down
44 changes: 44 additions & 0 deletions handler/openid/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ import (
"bytes"
"context"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"hash"
"strconv"

"github.com/ory/fosite"
)
Expand All @@ -36,6 +39,16 @@ type IDTokenHandleHelper struct {

func (i *IDTokenHandleHelper) GetAccessTokenHash(ctx context.Context, requester fosite.AccessRequester, responder fosite.AccessResponder) string {
token := responder.GetAccessToken()
// The session should always be a openid.Session but best to safely cast
if session, ok := requester.GetSession().(Session); ok {
val, err := i.ComputeHash(ctx, session, token)
if err != nil {
// this should never happen
panic(err)
}

return val
}

buffer := bytes.NewBufferString(token)
hash := sha256.New()
Expand Down Expand Up @@ -76,3 +89,34 @@ func (i *IDTokenHandleHelper) IssueExplicitIDToken(ctx context.Context, ar fosit
resp.SetExtra("id_token", token)
return nil
}

// ComputeHash computes the hash using the alg defined in the id_token header
func (i *IDTokenHandleHelper) ComputeHash(ctx context.Context, sess Session, token string) (string, error) {
var err error
hashSize := 256
if alg, ok := sess.IDTokenHeaders().Get("alg").(string); ok {
hashSize, err = strconv.Atoi(alg[2:])
if err != nil {
hashSize = 256
}
}

var hash hash.Hash
if hashSize == 384 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would make sense to set hash directly, without the intermediate hashSize variable :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, could you elaborate on this please? The alg may or may not be present in the header, so the first step here is to compute the hash size.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess something along this pseudo-code:

hash := sha256.New()

if alg, ok := sess.IDTokenHeaders().Get("alg").(string); ok {
 		hashSize, _ := strconv.Atoi(alg[2:]) // 0 per default
 		switch hashSize {
 			case 384
				hash = sha512.New()
 			// ...
 		}
 	}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aeneasr Made the change.

hash = sha512.New384()
} else if hashSize == 512 {
hash = sha512.New()
} else {
// fallback to 256
hash = sha256.New()
}

buffer := bytes.NewBufferString(token)
_, err = hash.Write(buffer.Bytes())
if err != nil {
return "", err
}
hashBuf := bytes.NewBuffer(hash.Sum([]byte{}))

return base64.RawURLEncoding.EncodeToString(hashBuf.Bytes()[:hashBuf.Len()/2]), nil
}
22 changes: 22 additions & 0 deletions handler/openid/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,32 @@ func TestGetAccessTokenHash(t *testing.T) {

defer ctrl.Finish()

req.EXPECT().GetSession().Return(nil)
resp.EXPECT().GetAccessToken().Return("7a35f818-9164-48cb-8c8f-e1217f44228431c41102-d410-4ed5-9276-07ba53dfdcd8")

h := &IDTokenHandleHelper{IDTokenStrategy: strat}

hash := h.GetAccessTokenHash(nil, req, resp)
assert.Equal(t, "Zfn_XBitThuDJiETU3OALQ", hash)
}

func TestGetAccessTokenHashWithDifferentKeyLength(t *testing.T) {
ctrl := gomock.NewController(t)
req := internal.NewMockAccessRequester(ctrl)
resp := internal.NewMockAccessResponder(ctrl)

defer ctrl.Finish()

headers := &jwt.Headers{
Extra: map[string]interface{}{
"alg": "RS384",
},
}
req.EXPECT().GetSession().Return(&DefaultSession{Headers: headers})
resp.EXPECT().GetAccessToken().Return("7a35f818-9164-48cb-8c8f-e1217f44228431c41102-d410-4ed5-9276-07ba53dfdcd8")

h := &IDTokenHandleHelper{IDTokenStrategy: strat}

hash := h.GetAccessTokenHash(nil, req, resp)
assert.Equal(t, "VNX38yiOyeqBPheW5jDsWQKa6IjJzK66", hash)
}