Skip to content

Commit 5eafa23

Browse files
drakkanDaisuke Maki
authored andcommitted
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 b062940 commit 5eafa23

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
@@ -846,10 +846,11 @@ func parseJSON(buf []byte, storeProtectedHeaders bool) (*Message, error) {
846846
}
847847

848848
func parseCompact(buf []byte, storeProtectedHeaders bool) (*Message, error) {
849-
parts := bytes.Split(buf, []byte{'.'})
850-
if len(parts) != 5 {
851-
return nil, fmt.Errorf(`compact JWE format must have five parts (%d)`, len(parts))
849+
// Five parts is four separators
850+
if count := bytes.Count(buf, []byte{'.'}); count != 4 {
851+
return nil, fmt.Errorf(`compact JWE format must have five parts (%d)`, count)
852852
}
853+
parts := bytes.SplitN(buf, []byte{'.'}, 5)
853854

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

jws/jws.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -635,20 +635,22 @@ func parseJSON(data []byte) (result *Message, err error) {
635635
// SplitCompact splits a JWT and returns its three parts
636636
// separately: protected headers, payload and signature.
637637
func SplitCompact(src []byte) ([]byte, []byte, []byte, error) {
638-
parts := bytes.Split(src, []byte("."))
639-
if len(parts) < 3 {
638+
// Three parts is two separators
639+
if bytes.Count(src, []byte(".")) != 2 {
640640
return nil, nil, nil, fmt.Errorf(`invalid number of segments`)
641641
}
642+
parts := bytes.SplitN(src, []byte("."), 3)
642643
return parts[0], parts[1], parts[2], nil
643644
}
644645

645646
// SplitCompactString splits a JWT and returns its three parts
646647
// separately: protected headers, payload and signature.
647648
func SplitCompactString(src string) ([]byte, []byte, []byte, error) {
648-
parts := strings.Split(src, ".")
649-
if len(parts) < 3 {
649+
// Three parts is two separators
650+
if strings.Count(src, ".") != 2 {
650651
return nil, nil, nil, fmt.Errorf(`invalid number of segments`)
651652
}
653+
parts := strings.SplitN(src, ".", 3)
652654
return []byte(parts[0]), []byte(parts[1]), []byte(parts[2]), nil
653655
}
654656

0 commit comments

Comments
 (0)