Skip to content

Commit d0bb461

Browse files
authored
jws/jwe: split token into fixed number of parts (#1308)
this avoid to use eccessive memory when processing maliciously crafted tokens with a large number of '.' characters Signed-off-by: Nicola Murino <nicola.murino@gmail.com>
1 parent 0076496 commit d0bb461

File tree

2 files changed

+10
-7
lines changed

2 files changed

+10
-7
lines changed

jwe/jwe.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -886,10 +886,11 @@ func parseJSON(buf []byte, storeProtectedHeaders bool) (*Message, error) {
886886
}
887887

888888
func parseCompact(buf []byte, storeProtectedHeaders bool) (*Message, error) {
889-
parts := bytes.Split(buf, []byte{'.'})
890-
if len(parts) != 5 {
891-
return nil, fmt.Errorf(`compact JWE format must have five parts (%d)`, len(parts))
889+
// Five parts is four separators
890+
if count := bytes.Count(buf, []byte{'.'}); count != 4 {
891+
return nil, fmt.Errorf(`compact JWE format must have five parts (%d)`, count)
892892
}
893+
parts := bytes.SplitN(buf, []byte{'.'}, 5)
893894

894895
hdrbuf, err := base64.Decode(parts[0])
895896
if err != nil {

jws/jws.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -625,10 +625,11 @@ func parseJSON(data []byte) (result *Message, err error) {
625625
//
626626
// On error, returns a jws.ParseError.
627627
func SplitCompact(src []byte) ([]byte, []byte, []byte, error) {
628-
parts := bytes.Split(src, []byte("."))
629-
if len(parts) < 3 {
628+
// Three parts is two separators
629+
if bytes.Count(src, []byte(".")) != 2 {
630630
return nil, nil, nil, parseerr(`invalid number of segments`)
631631
}
632+
parts := bytes.SplitN(src, []byte("."), 3)
632633
return parts[0], parts[1], parts[2], nil
633634
}
634635

@@ -637,10 +638,11 @@ func SplitCompact(src []byte) ([]byte, []byte, []byte, error) {
637638
//
638639
// On error, returns a jws.ParseError.
639640
func SplitCompactString(src string) ([]byte, []byte, []byte, error) {
640-
parts := strings.Split(src, ".")
641-
if len(parts) < 3 {
641+
// Three parts is two separators
642+
if strings.Count(src, ".") != 2 {
642643
return nil, nil, nil, parseerr(`invalid number of segments`)
643644
}
645+
parts := strings.SplitN(src, ".", 3)
644646
return []byte(parts[0]), []byte(parts[1]), []byte(parts[2]), nil
645647
}
646648

0 commit comments

Comments
 (0)