1
0
mirror of https://github.com/golang/go synced 2024-11-20 10:44:41 -07:00

encoding/asn1: return error for unexported fields in Marshal, Unmarshal

The old code cannot handle unexported fields, it panics.
The new code returns error instead.

Fixes #17462

Change-Id: I927fc46b21d60e86cb52e84c65f2122f9159b21d
Reviewed-on: https://go-review.googlesource.com/31540
Run-TryBot: Russ Cox <rsc@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
This commit is contained in:
Hiroshi Ioka 2016-10-21 09:00:07 +09:00 committed by Russ Cox
parent be7c50a710
commit 154d013155
3 changed files with 43 additions and 1 deletions

View File

@ -841,6 +841,13 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
case reflect.Struct: case reflect.Struct:
structType := fieldType structType := fieldType
for i := 0; i < structType.NumField(); i++ {
if structType.Field(i).PkgPath != "" {
err = StructuralError{"struct contains unexported fields"}
return
}
}
if structType.NumField() > 0 && if structType.NumField() > 0 &&
structType.Field(0).Type == rawContentsType { structType.Field(0).Type == rawContentsType {
bytes := bytes[initOffset:offset] bytes := bytes[initOffset:offset]

View File

@ -967,7 +967,7 @@ func TestUnmarshalInvalidUTF8(t *testing.T) {
func TestMarshalNilValue(t *testing.T) { func TestMarshalNilValue(t *testing.T) {
nilValueTestData := []interface{}{ nilValueTestData := []interface{}{
nil, nil,
struct{ v interface{} }{}, struct{ V interface{} }{},
} }
for i, test := range nilValueTestData { for i, test := range nilValueTestData {
if _, err := Marshal(test); err == nil { if _, err := Marshal(test); err == nil {
@ -975,3 +975,32 @@ func TestMarshalNilValue(t *testing.T) {
} }
} }
} }
type unexported struct {
X int
y int
}
type exported struct {
X int
Y int
}
func TestUnexportedStructField(t *testing.T) {
want := StructuralError{"struct contains unexported fields"}
_, err := Marshal(unexported{X: 5, y: 1})
if err != want {
t.Errorf("got %v, want %v", err, want)
}
bs, err := Marshal(exported{X: 5, Y: 1})
if err != nil {
t.Fatal(err)
}
var u unexported
_, err = Unmarshal(bs, &u)
if err != want {
t.Errorf("got %v, want %v", err, want)
}
}

View File

@ -427,6 +427,12 @@ func makeBody(value reflect.Value, params fieldParameters) (e encoder, err error
case reflect.Struct: case reflect.Struct:
t := v.Type() t := v.Type()
for i := 0; i < t.NumField(); i++ {
if t.Field(i).PkgPath != "" {
return nil, StructuralError{"struct contains unexported fields"}
}
}
startingField := 0 startingField := 0
n := t.NumField() n := t.NumField()