Commit 0a6df4a8 authored by Adam Langley's avatar Adam Langley Committed by Russ Cox

encoding/asn1: don't parse invalid UTF-8.

Invalid UTF-8 triggers an error when marshaling but, previously, not
when unmarshaling. This means that ASN.1 structures were not
round-tripping.

This change makes invalid UTF-8 in a string marked as UTF-8 to be an
error when Unmarshaling.

Fixes #11126.

Change-Id: Ic37be84d21dc5c03983525e244d955a8b1e1ff14
Reviewed-on: https://go-review.googlesource.com/11056
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: default avatarBrad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: default avatarRuss Cox <rsc@golang.org>
parent fdd921c9
...@@ -26,6 +26,7 @@ import ( ...@@ -26,6 +26,7 @@ import (
"reflect" "reflect"
"strconv" "strconv"
"time" "time"
"unicode/utf8"
) )
// A StructuralError suggests that the ASN.1 data is valid, but the Go type // A StructuralError suggests that the ASN.1 data is valid, but the Go type
...@@ -389,6 +390,9 @@ func parseT61String(bytes []byte) (ret string, err error) { ...@@ -389,6 +390,9 @@ func parseT61String(bytes []byte) (ret string, err error) {
// parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
// array and returns it. // array and returns it.
func parseUTF8String(bytes []byte) (ret string, err error) { func parseUTF8String(bytes []byte) (ret string, err error) {
if !utf8.Valid(bytes) {
return "", errors.New("asn1: invalid UTF-8 string")
}
return string(bytes), nil return string(bytes), nil
} }
......
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
"fmt" "fmt"
"math/big" "math/big"
"reflect" "reflect"
"strings"
"testing" "testing"
"time" "time"
) )
...@@ -922,3 +923,20 @@ func TestTruncatedExplicitTag(t *testing.T) { ...@@ -922,3 +923,20 @@ func TestTruncatedExplicitTag(t *testing.T) {
t.Error("Unmarshal returned without error") t.Error("Unmarshal returned without error")
} }
} }
type invalidUTF8Test struct {
Str string `asn1:"utf8"`
}
func TestUnmarshalInvalidUTF8(t *testing.T) {
data := []byte("0\x05\f\x03a\xc9c")
var result invalidUTF8Test
_, err := Unmarshal(data, &result)
const expectedSubstring = "UTF"
if err == nil {
t.Fatal("Successfully unmarshaled invalid UTF-8 data")
} else if !strings.Contains(err.Error(), expectedSubstring) {
t.Fatalf("Expected error to mention %q but error was %q", expectedSubstring, err.Error())
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment