Commit 9929ee92 authored by Adam Langley's avatar Adam Langley

asn1: Enumerated, Flag and GeneralizedTime support.

        Add support for ASN.1 ENUMERATED types.

        Add a magic type, asn1.Flag, for the cases where the presence of an
        empty explicit tag is semantically meaningful.

        Add support for GeneralizedTime.

R=rsc
CC=golang-dev
https://golang.org/cl/1684055
parent 02786d26
...@@ -150,6 +150,20 @@ func parseBitString(bytes []byte) (ret BitString, err os.Error) { ...@@ -150,6 +150,20 @@ func parseBitString(bytes []byte) (ret BitString, err os.Error) {
// An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER. // An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
type ObjectIdentifier []int type ObjectIdentifier []int
// Equal returns true iff oi and other represent the same identifier.
func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {
if len(oi) != len(other) {
return false
}
for i := 0; i < len(oi); i++ {
if oi[i] != other[i] {
return false
}
}
return true
}
// parseObjectIdentifier parses an OBJECT IDENTIFER from the given bytes and // parseObjectIdentifier parses an OBJECT IDENTIFER from the given bytes and
// returns it. An object identifer is a sequence of variable length integers // returns it. An object identifer is a sequence of variable length integers
// that are assigned in a hierarachy. // that are assigned in a hierarachy.
...@@ -179,6 +193,17 @@ func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) { ...@@ -179,6 +193,17 @@ func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) {
return return
} }
// ENUMERATED
// An Enumerated is represented as a plain int.
type Enumerated int
// FLAG
// A Flag accepts any data and is set to true if present.
type Flag bool
// parseBase128Int parses a base-128 encoded int from the given offset in the // parseBase128Int parses a base-128 encoded int from the given offset in the
// given byte array. It returns the value and the new offset. // given byte array. It returns the value and the new offset.
func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Error) { func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Error) {
...@@ -202,101 +227,20 @@ func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Erro ...@@ -202,101 +227,20 @@ func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Erro
// UTCTime // UTCTime
func isDigit(b byte) bool { return '0' <= b && b <= '9' }
// twoDigits returns the value of two, base 10 digits.
func twoDigits(bytes []byte, max int) (int, bool) {
for i := 0; i < 2; i++ {
if !isDigit(bytes[i]) {
return 0, false
}
}
value := (int(bytes[0])-'0')*10 + int(bytes[1]-'0')
if value > max {
return 0, false
}
return value, true
}
// parseUTCTime parses the UTCTime from the given byte array and returns the
// resulting time.
func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) { func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) {
// A UTCTime can take the following formats: s := string(bytes)
// ret, err = time.Parse("0601021504Z0700", s)
// 1111111 if err == nil {
// 01234567890123456
//
// YYMMDDhhmmZ
// YYMMDDhhmm+hhmm
// YYMMDDhhmm-hhmm
// YYMMDDhhmmssZ
// YYMMDDhhmmss+hhmm
// YYMMDDhhmmss-hhmm
if len(bytes) < 11 {
err = SyntaxError{"UTCTime too short"}
return
}
ret = new(time.Time)
var ok1, ok2, ok3, ok4, ok5 bool
year, ok1 := twoDigits(bytes[0:2], 99)
// RFC 5280, section 5.1.2.4 says that years 2050 or later use another date
// scheme.
if year >= 50 {
ret.Year = 1900 + int64(year)
} else {
ret.Year = 2000 + int64(year)
}
ret.Month, ok2 = twoDigits(bytes[2:4], 12)
ret.Day, ok3 = twoDigits(bytes[4:6], 31)
ret.Hour, ok4 = twoDigits(bytes[6:8], 23)
ret.Minute, ok5 = twoDigits(bytes[8:10], 59)
if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 {
goto Error
}
bytes = bytes[10:]
switch bytes[0] {
case '0', '1', '2', '3', '4', '5', '6':
if len(bytes) < 3 {
goto Error
}
ret.Second, ok1 = twoDigits(bytes[0:2], 60) // 60, not 59, because of leap seconds.
if !ok1 {
goto Error
}
bytes = bytes[2:]
}
if len(bytes) == 0 {
goto Error
}
switch bytes[0] {
case 'Z':
if len(bytes) != 1 {
goto Error
}
return return
case '-', '+':
if len(bytes) != 5 {
goto Error
}
hours, ok1 := twoDigits(bytes[1:3], 12)
minutes, ok2 := twoDigits(bytes[3:5], 59)
if !ok1 || !ok2 {
goto Error
}
sign := 1
if bytes[0] == '-' {
sign = -1
}
ret.ZoneOffset = sign * (60 * (hours*60 + minutes))
default:
goto Error
} }
ret, err = time.Parse("060102150405Z0700", s)
return return
}
Error: // parseGeneralizedTime parses the GeneralizedTime from the given byte array
err = SyntaxError{"invalid UTCTime"} // and returns the resulting time.
return func parseGeneralizedTime(bytes []byte) (ret *time.Time, err os.Error) {
return time.Parse("20060102150405Z0700", string(bytes))
} }
// PrintableString // PrintableString
...@@ -351,6 +295,7 @@ type RawValue struct { ...@@ -351,6 +295,7 @@ type RawValue struct {
Class, Tag int Class, Tag int
IsCompound bool IsCompound bool
Bytes []byte Bytes []byte
FullBytes []byte // includes the tag and length
} }
// RawContent is used to signal that the undecoded, DER data needs to be // RawContent is used to signal that the undecoded, DER data needs to be
...@@ -462,6 +407,8 @@ func parseSequenceOf(bytes []byte, sliceType *reflect.SliceType, elemType reflec ...@@ -462,6 +407,8 @@ func parseSequenceOf(bytes []byte, sliceType *reflect.SliceType, elemType reflec
var ( var (
bitStringType = reflect.Typeof(BitString{}) bitStringType = reflect.Typeof(BitString{})
objectIdentifierType = reflect.Typeof(ObjectIdentifier{}) objectIdentifierType = reflect.Typeof(ObjectIdentifier{})
enumeratedType = reflect.Typeof(Enumerated(0))
flagType = reflect.Typeof(Flag(false))
timeType = reflect.Typeof(&time.Time{}) timeType = reflect.Typeof(&time.Time{})
rawValueType = reflect.Typeof(RawValue{}) rawValueType = reflect.Typeof(RawValue{})
rawContentsType = reflect.Typeof(RawContent(nil)) rawContentsType = reflect.Typeof(RawContent(nil))
...@@ -499,7 +446,7 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam ...@@ -499,7 +446,7 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
err = SyntaxError{"data truncated"} err = SyntaxError{"data truncated"}
return return
} }
result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length]} result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]}
offset += t.length offset += t.length
v.(*reflect.StructValue).Set(reflect.NewValue(result).(*reflect.StructValue)) v.(*reflect.StructValue).Set(reflect.NewValue(result).(*reflect.StructValue))
return return
...@@ -559,9 +506,20 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam ...@@ -559,9 +506,20 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
return return
} }
if params.explicit { if params.explicit {
if t.class == classContextSpecific && t.tag == *params.tag && t.isCompound { if t.class == classContextSpecific && t.tag == *params.tag && (t.length == 0 || t.isCompound) {
t, offset, err = parseTagAndLength(bytes, offset) if t.length > 0 {
if err != nil { t, offset, err = parseTagAndLength(bytes, offset)
if err != nil {
return
}
} else {
if fieldType != flagType {
err = StructuralError{"Zero length explicit tag was not an asn1.Flag"}
return
}
flagValue := v.(*reflect.BoolValue)
flagValue.Set(true)
return return
} }
} else { } else {
...@@ -584,6 +542,12 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam ...@@ -584,6 +542,12 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
universalTag = tagIA5String universalTag = tagIA5String
} }
// Special case for time: UTCTime and GeneralizedTime both map to the
// Go type time.Time.
if universalTag == tagUTCTime && t.tag == tagGeneralizedTime {
universalTag = tagGeneralizedTime
}
expectedClass := classUniversal expectedClass := classUniversal
expectedTag := universalTag expectedTag := universalTag
...@@ -631,12 +595,30 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam ...@@ -631,12 +595,30 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
return return
case timeType: case timeType:
ptrValue := v.(*reflect.PtrValue) ptrValue := v.(*reflect.PtrValue)
time, err1 := parseUTCTime(innerBytes) var time *time.Time
var err1 os.Error
if universalTag == tagUTCTime {
time, err1 = parseUTCTime(innerBytes)
} else {
time, err1 = parseGeneralizedTime(innerBytes)
}
if err1 == nil { if err1 == nil {
ptrValue.Set(reflect.NewValue(time).(*reflect.PtrValue)) ptrValue.Set(reflect.NewValue(time).(*reflect.PtrValue))
} }
err = err1 err = err1
return return
case enumeratedType:
parsedInt, err1 := parseInt(innerBytes)
enumValue := v.(*reflect.IntValue)
if err1 == nil {
enumValue.Set(int64(parsedInt))
}
err = err1
return
case flagType:
flagValue := v.(*reflect.BoolValue)
flagValue.Set(true)
return
} }
switch val := v.(type) { switch val := v.(type) {
case *reflect.BoolValue: case *reflect.BoolValue:
...@@ -753,6 +735,10 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { ...@@ -753,6 +735,10 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
// An ASN.1 OBJECT IDENTIFIER can be written to an // An ASN.1 OBJECT IDENTIFIER can be written to an
// ObjectIdentifier. // ObjectIdentifier.
// //
// An ASN.1 ENUMERATED can be written to an Enumerated.
//
// An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a *time.Time.
//
// An ASN.1 PrintableString or IA5String can be written to a string. // An ASN.1 PrintableString or IA5String can be written to a string.
// //
// Any of the above ASN.1 values can be written to an interface{}. // Any of the above ASN.1 values can be written to an interface{}.
......
...@@ -147,11 +147,11 @@ type timeTest struct { ...@@ -147,11 +147,11 @@ type timeTest struct {
out *time.Time out *time.Time
} }
var timeTestData = []timeTest{ var utcTestData = []timeTest{
timeTest{"910506164540-0700", true, &time.Time{1991, 05, 06, 16, 45, 40, 0, -7 * 60 * 60, ""}}, timeTest{"910506164540-0700", true, &time.Time{1991, 05, 06, 16, 45, 40, 0, -7 * 60 * 60, ""}},
timeTest{"910506164540+0730", true, &time.Time{1991, 05, 06, 16, 45, 40, 0, 7*60*60 + 30*60, ""}}, timeTest{"910506164540+0730", true, &time.Time{1991, 05, 06, 16, 45, 40, 0, 7*60*60 + 30*60, ""}},
timeTest{"910506234540Z", true, &time.Time{1991, 05, 06, 23, 45, 40, 0, 0, ""}}, timeTest{"910506234540Z", true, &time.Time{1991, 05, 06, 23, 45, 40, 0, 0, "UTC"}},
timeTest{"9105062345Z", true, &time.Time{1991, 05, 06, 23, 45, 0, 0, 0, ""}}, timeTest{"9105062345Z", true, &time.Time{1991, 05, 06, 23, 45, 0, 0, 0, "UTC"}},
timeTest{"a10506234540Z", false, nil}, timeTest{"a10506234540Z", false, nil},
timeTest{"91a506234540Z", false, nil}, timeTest{"91a506234540Z", false, nil},
timeTest{"9105a6234540Z", false, nil}, timeTest{"9105a6234540Z", false, nil},
...@@ -162,8 +162,8 @@ var timeTestData = []timeTest{ ...@@ -162,8 +162,8 @@ var timeTestData = []timeTest{
timeTest{"910506334400Za", false, nil}, timeTest{"910506334400Za", false, nil},
} }
func TestTime(t *testing.T) { func TestUTCTime(t *testing.T) {
for i, test := range timeTestData { for i, test := range utcTestData {
ret, err := parseUTCTime([]byte(test.in)) ret, err := parseUTCTime([]byte(test.in))
if (err == nil) != test.ok { if (err == nil) != test.ok {
t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok)
...@@ -176,6 +176,27 @@ func TestTime(t *testing.T) { ...@@ -176,6 +176,27 @@ func TestTime(t *testing.T) {
} }
} }
var generalizedTimeTestData = []timeTest{
timeTest{"20100102030405Z", true, &time.Time{2010, 01, 02, 03, 04, 05, 0, 0, "UTC"}},
timeTest{"20100102030405", false, nil},
timeTest{"20100102030405+0607", true, &time.Time{2010, 01, 02, 03, 04, 05, 0, 6*60*60 + 7*60, ""}},
timeTest{"20100102030405-0607", true, &time.Time{2010, 01, 02, 03, 04, 05, 0, -6*60*60 - 7*60, ""}},
}
func TestGeneralizedTime(t *testing.T) {
for i, test := range generalizedTimeTestData {
ret, err := parseGeneralizedTime([]byte(test.in))
if (err == nil) != test.ok {
t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok)
}
if err == nil {
if !reflect.DeepEqual(test.out, ret) {
t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out)
}
}
}
}
type tagAndLengthTest struct { type tagAndLengthTest struct {
in []byte in []byte
ok bool ok bool
...@@ -276,8 +297,8 @@ var unmarshalTestData []unmarshalTest = []unmarshalTest{ ...@@ -276,8 +297,8 @@ var unmarshalTestData []unmarshalTest = []unmarshalTest{
unmarshalTest{[]byte{0x02, 0x01, 0x10}, newInt(16)}, unmarshalTest{[]byte{0x02, 0x01, 0x10}, newInt(16)},
unmarshalTest{[]byte{0x13, 0x04, 't', 'e', 's', 't'}, newString("test")}, unmarshalTest{[]byte{0x13, 0x04, 't', 'e', 's', 't'}, newString("test")},
unmarshalTest{[]byte{0x16, 0x04, 't', 'e', 's', 't'}, newString("test")}, unmarshalTest{[]byte{0x16, 0x04, 't', 'e', 's', 't'}, newString("test")},
unmarshalTest{[]byte{0x16, 0x04, 't', 'e', 's', 't'}, &RawValue{0, 22, false, []byte("test")}}, unmarshalTest{[]byte{0x16, 0x04, 't', 'e', 's', 't'}, &RawValue{0, 22, false, []byte("test"), []byte("\x16\x04test")}},
unmarshalTest{[]byte{0x04, 0x04, 1, 2, 3, 4}, &RawValue{0, 4, false, []byte{1, 2, 3, 4}}}, unmarshalTest{[]byte{0x04, 0x04, 1, 2, 3, 4}, &RawValue{0, 4, false, []byte{1, 2, 3, 4}, []byte{4, 4, 1, 2, 3, 4}}},
unmarshalTest{[]byte{0x30, 0x03, 0x81, 0x01, 0x01}, &TestContextSpecificTags{1}}, unmarshalTest{[]byte{0x30, 0x03, 0x81, 0x01, 0x01}, &TestContextSpecificTags{1}},
unmarshalTest{[]byte{0x30, 0x08, 0xa1, 0x03, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02}, &TestContextSpecificTags2{1, 2}}, unmarshalTest{[]byte{0x30, 0x08, 0xa1, 0x03, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02}, &TestContextSpecificTags2{1, 2}},
unmarshalTest{[]byte{0x01, 0x01, 0x00}, newBool(false)}, unmarshalTest{[]byte{0x01, 0x01, 0x00}, newBool(false)},
...@@ -389,7 +410,7 @@ func TestRawStructs(t *testing.T) { ...@@ -389,7 +410,7 @@ func TestRawStructs(t *testing.T) {
var derEncodedSelfSignedCert = Certificate{ var derEncodedSelfSignedCert = Certificate{
TBSCertificate: TBSCertificate{ TBSCertificate: TBSCertificate{
Version: 0, Version: 0,
SerialNumber: RawValue{Class: 0, Tag: 2, IsCompound: false, Bytes: []uint8{0x0, 0x8c, 0xc3, 0x37, 0x92, 0x10, 0xec, 0x2c, 0x98}}, SerialNumber: RawValue{Class: 0, Tag: 2, IsCompound: false, Bytes: []uint8{0x0, 0x8c, 0xc3, 0x37, 0x92, 0x10, 0xec, 0x2c, 0x98}, FullBytes: []byte{2, 9, 0x0, 0x8c, 0xc3, 0x37, 0x92, 0x10, 0xec, 0x2c, 0x98}},
SignatureAlgorithm: AlgorithmIdentifier{Algorithm: ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}}, SignatureAlgorithm: AlgorithmIdentifier{Algorithm: ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}},
Issuer: RDNSequence{ Issuer: RDNSequence{
RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 6}, Value: "XX"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 6}, Value: "XX"}},
...@@ -399,7 +420,7 @@ var derEncodedSelfSignedCert = Certificate{ ...@@ -399,7 +420,7 @@ var derEncodedSelfSignedCert = Certificate{
RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 3}, Value: "false.example.com"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 3}, Value: "false.example.com"}},
RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}, Value: "false@example.com"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}, Value: "false@example.com"}},
}, },
Validity: Validity{NotBefore: &time.Time{Year: 2009, Month: 10, Day: 8, Hour: 0, Minute: 25, Second: 53, Weekday: 0, ZoneOffset: 0, Zone: ""}, NotAfter: &time.Time{Year: 2010, Month: 10, Day: 8, Hour: 0, Minute: 25, Second: 53, Weekday: 0, ZoneOffset: 0, Zone: ""}}, Validity: Validity{NotBefore: &time.Time{Year: 2009, Month: 10, Day: 8, Hour: 0, Minute: 25, Second: 53, Weekday: 0, ZoneOffset: 0, Zone: "UTC"}, NotAfter: &time.Time{Year: 2010, Month: 10, Day: 8, Hour: 0, Minute: 25, Second: 53, Weekday: 0, ZoneOffset: 0, Zone: "UTC"}},
Subject: RDNSequence{ Subject: RDNSequence{
RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 6}, Value: "XX"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 6}, Value: "XX"}},
RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 8}, Value: "Some-State"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 8}, Value: "Some-State"}},
......
...@@ -24,11 +24,13 @@ const ( ...@@ -24,11 +24,13 @@ const (
tagBitString = 3 tagBitString = 3
tagOctetString = 4 tagOctetString = 4
tagOID = 6 tagOID = 6
tagEnum = 10
tagSequence = 16 tagSequence = 16
tagSet = 17 tagSet = 17
tagPrintableString = 19 tagPrintableString = 19
tagIA5String = 22 tagIA5String = 22
tagUTCTime = 23 tagUTCTime = 23
tagGeneralizedTime = 24
) )
const ( const (
...@@ -121,6 +123,8 @@ func getUniversalType(t reflect.Type) (tagNumber int, isCompound, ok bool) { ...@@ -121,6 +123,8 @@ func getUniversalType(t reflect.Type) (tagNumber int, isCompound, ok bool) {
return tagBitString, false, true return tagBitString, false, true
case timeType: case timeType:
return tagUTCTime, false, true return tagUTCTime, false, true
case enumeratedType:
return tagEnum, false, true
} }
switch t := t.(type) { switch t := t.(type) {
case *reflect.BoolType: case *reflect.BoolType:
......
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