From 7bd3a587de42cc5b7bfa5ecb1393fbc435c7ced4 Mon Sep 17 00:00:00 2001 From: Emir Aganovic Date: Thu, 17 Oct 2024 09:08:40 +0200 Subject: [PATCH] fix: handle lower case digest algorith #24 --- client.go | 6 ++++++ client_test.go | 15 +++++++++++++++ sip/utils.go | 27 +++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/client.go b/client.go index 17d28bc..717b54c 100644 --- a/client.go +++ b/client.go @@ -430,6 +430,9 @@ func digestProxyAuthApply(req *sip.Request, res *sip.Response, opts digest.Optio return fmt.Errorf("fail to parse challenge authHeader=%q: %w", authHeader.Value(), err) } + // Fix lower case algorithm although not supported by rfc + chal.Algorithm = sip.ASCIIToUpper(chal.Algorithm) + // Reply with digest cred, err := digest.Digest(chal, opts) if err != nil { @@ -448,6 +451,9 @@ func digestAuthApply(req *sip.Request, res *sip.Response, opts digest.Options) e return fmt.Errorf("fail to parse chalenge wwwauth=%q: %w", wwwAuth.Value(), err) } + // Fix lower case algorithm although not supported by rfc + chal.Algorithm = sip.ASCIIToUpper(chal.Algorithm) + // Reply with digest cred, err := digest.Digest(chal, opts) if err != nil { diff --git a/client_test.go b/client_test.go index bcfda96..ee7b910 100644 --- a/client_test.go +++ b/client_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/emiago/sipgo/sip" + "github.com/icholy/digest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -202,3 +203,17 @@ func TestClientRequestOptions(t *testing.T) { conn, err := tp.ClientRequestConnection(context.TODO(), req) } */ + +func TestDigestAuthLowerCase(t *testing.T) { + challenge := `Digest username="user", realm="asterisk", nonce="662d65a084b88c6d2a745a9de086fa91", uri="sip:+user@example.com", algorithm=sha-256, response="3681b63e5d9c3bb80e5350e2783d7b88"` + chal, err := digest.ParseChallenge(challenge) + require.NoError(t, err) + chal.Algorithm = sip.ASCIIToUpper(chal.Algorithm) + + _, err = digest.Digest(chal, digest.Options{ + Method: "INVITE", + Username: "user", + URI: "sip:+user@example.com", + }) + require.NoError(t, err) +} diff --git a/sip/utils.go b/sip/utils.go index 4d6ff21..9cc518d 100644 --- a/sip/utils.go +++ b/sip/utils.go @@ -109,6 +109,33 @@ func ASCIIToLowerInPlace(s []byte) { } } +func ASCIIToUpper(s string) string { + // first check is ascii already up to avoid alloc + nonLowInd := -1 + for i, c := range s { + if 'A' <= c && c <= 'Z' { + continue + } + nonLowInd = i + break + } + if nonLowInd < 0 { + return s + } + + var b strings.Builder + b.Grow(len(s)) + b.WriteString(s[:nonLowInd]) + for i := nonLowInd; i < len(s); i++ { + c := s[i] + if 'a' <= c && c <= 'z' { + c -= 'a' - 'A' + } + b.WriteByte(c) + } + return b.String() +} + // HeaderToLower is fast ASCII lower string func HeaderToLower(s string) string { // Avoid allocations