pax_global_header00006660000000000000000000000064136476603250014526gustar00rootroot0000000000000052 comment=e8e9323b07b7a9d9222b7fd36000d7409f383f63 ber-1.1.0/000077500000000000000000000000001364766032500122755ustar00rootroot00000000000000ber-1.1.0/.travis.yml000066400000000000000000000003061364766032500144050ustar00rootroot00000000000000language: go go: - "1.8" - "1.9" - "1.10" - "1.11" - "1.12" - "1.13" - "1.14" install: - go get -d -t -v ./... script: - GOOS=linux GOARCH=amd64 go test -v . - GOOS=linux GOARCH=386 go test -v . ber-1.1.0/LICENSE000066400000000000000000000027071364766032500133100ustar00rootroot00000000000000Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ber-1.1.0/README.md000066400000000000000000000006731364766032500135620ustar00rootroot00000000000000BER Package ============ [![Build Status](https://travis-ci.org/geoffgarside/ber.svg?branch=master)](https://travis-ci.org/geoffgarside/ber) [![GoDoc](https://godoc.org/github.com/geoffgarside/ber?status.svg)](http://godoc.org/github.com/geoffgarside/ber) This package is a fork of the standard library `encoding/asn1` package, adding Basic Encoding Rules support for use with [`github.com/k-sone/snmpgo`](https://github.com/k-sone/snmpgo). ber-1.1.0/ber.go000066400000000000000000000702621364766032500134030ustar00rootroot00000000000000// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package asn1 implements parsing of DER-encoded ASN.1 data structures, // as defined in ITU-T Rec X.690. // // See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,'' // http://luca.ntop.org/Teaching/Appunti/asn1.html. package ber // ASN.1 is a syntax for specifying abstract objects and BER, DER, PER, XER etc // are different encoding formats for those objects. Here, we'll be dealing // with DER, the Distinguished Encoding Rules. DER is used in X.509 because // it's fast to parse and, unlike BER, has a unique encoding for every object. // When calculating hashes over objects, it's important that the resulting // bytes be the same at both ends and DER removes this margin of error. // // ASN.1 is very complex and this package doesn't attempt to implement // everything by any means. import ( "encoding/asn1" "errors" "fmt" "math" "math/big" "reflect" "time" "unicode/utf16" "unicode/utf8" ) // We start by dealing with each of the primitive types in turn. // BOOLEAN func parseBool(bytes []byte) (ret bool, err error) { if len(bytes) != 1 { err = asn1.SyntaxError{Msg: "invalid boolean"} return } // DER demands that "If the encoding represents the boolean value TRUE, // its single contents octet shall have all eight bits set to one." // Thus only 0 and 255 are valid encoded values. switch bytes[0] { case 0: ret = false case 0xff: ret = true default: err = asn1.SyntaxError{Msg: "invalid boolean"} } return } // INTEGER // checkInteger returns nil if the given bytes are a valid DER-encoded // INTEGER and an error otherwise. func checkInteger(bytes []byte) error { if len(bytes) == 0 { return asn1.StructuralError{Msg: "empty integer"} } if len(bytes) == 1 { return nil } if (bytes[0] == 0 && bytes[1]&0x80 == 0) || (bytes[0] == 0xff && bytes[1]&0x80 == 0x80) { return asn1.StructuralError{Msg: "integer not minimally-encoded"} } return nil } // parseInt64 treats the given bytes as a big-endian, signed integer and // returns the result. func parseInt64(bytes []byte) (ret int64, err error) { err = checkInteger(bytes) if err != nil { return } if len(bytes) > 8 { // We'll overflow an int64 in this case. err = asn1.StructuralError{Msg: "integer too large"} return } for bytesRead := 0; bytesRead < len(bytes); bytesRead++ { ret <<= 8 ret |= int64(bytes[bytesRead]) } // Shift up and down in order to sign extend the result. ret <<= 64 - uint8(len(bytes))*8 ret >>= 64 - uint8(len(bytes))*8 return } // parseInt treats the given bytes as a big-endian, signed integer and returns // the result. func parseInt32(bytes []byte) (int32, error) { if err := checkInteger(bytes); err != nil { return 0, err } ret64, err := parseInt64(bytes) if err != nil { return 0, err } if ret64 != int64(int32(ret64)) { return 0, asn1.StructuralError{Msg: "integer too large"} } return int32(ret64), nil } var bigOne = big.NewInt(1) // parseBigInt treats the given bytes as a big-endian, signed integer and returns // the result. func parseBigInt(bytes []byte) (*big.Int, error) { if err := checkInteger(bytes); err != nil { return nil, err } ret := new(big.Int) if len(bytes) > 0 && bytes[0]&0x80 == 0x80 { // This is a negative number. notBytes := make([]byte, len(bytes)) for i := range notBytes { notBytes[i] = ^bytes[i] } ret.SetBytes(notBytes) ret.Add(ret, bigOne) ret.Neg(ret) return ret, nil } ret.SetBytes(bytes) return ret, nil } // BIT STRING // parseBitString parses an ASN.1 bit string from the given byte slice and returns it. func parseBitString(bytes []byte) (ret asn1.BitString, err error) { if len(bytes) == 0 { err = asn1.SyntaxError{Msg: "zero length BIT STRING"} return } paddingBits := int(bytes[0]) if paddingBits > 7 || len(bytes) == 1 && paddingBits > 0 || bytes[len(bytes)-1]&((1< math.MaxInt32 { err = asn1.StructuralError{Msg: "base 128 integer too large"} } return } } err = asn1.SyntaxError{Msg: "truncated base 128 integer"} return } func _parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) { offset = initOffset for shifted := 0; offset < len(bytes); shifted++ { ret <<= 7 b := bytes[offset] ret |= int(b & 0x7f) offset++ if b&0x80 == 0 { return } } err = asn1.SyntaxError{Msg: "truncated base 128 integer"} return } // UTCTime func parseUTCTime(bytes []byte) (ret time.Time, err error) { s := string(bytes) formatStr := "0601021504Z0700" ret, err = time.Parse(formatStr, s) if err != nil { formatStr = "060102150405Z0700" ret, err = time.Parse(formatStr, s) } if err != nil { return } if serialized := ret.Format(formatStr); serialized != s { err = fmt.Errorf("asn1: time did not serialize back to the original value and may be invalid: given %q, but serialized as %q", s, serialized) return } if ret.Year() >= 2050 { // UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 ret = ret.AddDate(-100, 0, 0) } return } // parseGeneralizedTime parses the GeneralizedTime from the given byte slice // and returns the resulting time. func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) { const formatStr = "20060102150405Z0700" s := string(bytes) if ret, err = time.Parse(formatStr, s); err != nil { return } if serialized := ret.Format(formatStr); serialized != s { err = fmt.Errorf("asn1: time did not serialize back to the original value and may be invalid: given %q, but serialized as %q", s, serialized) } return } // NumericString // parseNumericString parses an ASN.1 NumericString from the given byte array // and returns it. func parseNumericString(bytes []byte) (ret string, err error) { for _, b := range bytes { if !isNumeric(b) { return "", asn1.SyntaxError{Msg: "NumericString contains invalid character"} } } return string(bytes), nil } // isNumeric reports whether the given b is in the ASN.1 NumericString set. func isNumeric(b byte) bool { return '0' <= b && b <= '9' || b == ' ' } // PrintableString // parsePrintableString parses an ASN.1 PrintableString from the given byte // array and returns it. func parsePrintableString(bytes []byte) (ret string, err error) { for _, b := range bytes { if !isPrintable(b, allowAsterisk, allowAmpersand) { err = asn1.SyntaxError{Msg: "PrintableString contains invalid character"} return } } ret = string(bytes) return } type asteriskFlag bool type ampersandFlag bool const ( allowAsterisk asteriskFlag = true rejectAsterisk asteriskFlag = false allowAmpersand ampersandFlag = true rejectAmpersand ampersandFlag = false ) // isPrintable reports whether the given b is in the ASN.1 PrintableString set. // If asterisk is allowAsterisk then '*' is also allowed, reflecting existing // practice. If ampersand is allowAmpersand then '&' is allowed as well. func isPrintable(b byte, asterisk asteriskFlag, ampersand ampersandFlag) bool { return 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z' || '0' <= b && b <= '9' || '\'' <= b && b <= ')' || '+' <= b && b <= '/' || b == ' ' || b == ':' || b == '=' || b == '?' || // This is technically not allowed in a PrintableString. // However, x509 certificates with wildcard strings don't // always use the correct string type so we permit it. (bool(asterisk) && b == '*') || // This is not technically allowed either. However, not // only is it relatively common, but there are also a // handful of CA certificates that contain it. At least // one of which will not expire until 2027. (bool(ampersand) && b == '&') } // IA5String // parseIA5String parses an ASN.1 IA5String (ASCII string) from the given // byte slice and returns it. func parseIA5String(bytes []byte) (ret string, err error) { for _, b := range bytes { if b >= utf8.RuneSelf { err = asn1.SyntaxError{Msg: "IA5String contains invalid character"} return } } ret = string(bytes) return } // T61String // parseT61String parses an ASN.1 T61String (8-bit clean string) from the given // byte slice and returns it. func parseT61String(bytes []byte) (ret string, err error) { return string(bytes), nil } // UTF8String // parseUTF8String parses an ASN.1 UTF8String (raw UTF-8) from the given byte // array and returns it. func parseUTF8String(bytes []byte) (ret string, err error) { if !utf8.Valid(bytes) { return "", errors.New("asn1: invalid UTF-8 string") } return string(bytes), nil } // BMPString // parseBMPString parses an ASN.1 BMPString (Basic Multilingual Plane of // ISO/IEC/ITU 10646-1) from the given byte slice and returns it. func parseBMPString(bmpString []byte) (string, error) { if len(bmpString)%2 != 0 { return "", errors.New("pkcs12: odd-length BMP string") } // Strip terminator if present. if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 { bmpString = bmpString[:l-2] } s := make([]uint16, 0, len(bmpString)/2) for len(bmpString) > 0 { s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1])) bmpString = bmpString[2:] } return string(utf16.Decode(s)), nil } // Tagging // parseTagAndLength parses an ASN.1 tag and length pair from the given offset // into a byte slice. It returns the parsed data and the new offset. SET and // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we // don't distinguish between ordered and unordered objects in this code. func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) { offset = initOffset // parseTagAndLength should not be called without at least a single // byte to read. Thus this check is for robustness: if offset >= len(bytes) { err = errors.New("asn1: internal error in parseTagAndLength") return } b := bytes[offset] offset++ ret.class = int(b >> 6) ret.isCompound = b&0x20 == 0x20 ret.tag = int(b & 0x1f) // If the bottom five bits are set, then the tag number is actually base 128 // encoded afterwards if ret.tag == 0x1f { ret.tag, offset, err = parseBase128Int(bytes, offset) if err != nil { return } // Tags should be encoded in minimal form. if ret.tag < 0x1f { err = asn1.SyntaxError{Msg: "non-minimal tag"} return } } if offset >= len(bytes) { err = asn1.SyntaxError{Msg: "truncated tag or length"} return } b = bytes[offset] offset++ if b&0x80 == 0 { // The length is encoded in the bottom 7 bits. ret.length = int(b & 0x7f) } else { // Bottom 7 bits give the number of length bytes to follow. numBytes := int(b & 0x7f) if numBytes == 0 { // TODO: Fix this for BER as it should be allowed. Not seen this in // the wild with SNMP devices though. err = asn1.SyntaxError{Msg: "indefinite length found (not DER)"} return } ret.length = 0 for i := 0; i < numBytes; i++ { if offset >= len(bytes) { err = asn1.SyntaxError{Msg: "truncated tag or length"} return } b = bytes[offset] offset++ if ret.length >= 1<<23 { // We can't shift ret.length up without // overflowing. err = asn1.StructuralError{Msg: "length too large"} return } ret.length <<= 8 ret.length |= int(b) } } return } // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse // a number of ASN.1 values from the given byte slice and returns them as a // slice of Go values of the given type. func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) { matchAny, expectedTag, compoundType, ok := getUniversalType(elemType) if !ok { err = asn1.StructuralError{Msg: "unknown Go type for slice"} return } // First we iterate over the input and count the number of elements, // checking that the types are correct in each case. numElements := 0 for offset := 0; offset < len(bytes); { var t tagAndLength t, offset, err = parseTagAndLength(bytes, offset) if err != nil { return } switch t.tag { case tagIA5String, tagGeneralString, tagT61String, tagUTF8String, tagNumericString, tagBMPString: // We pretend that various other string types are // PRINTABLE STRINGs so that a sequence of them can be // parsed into a []string. t.tag = tagPrintableString case tagGeneralizedTime, tagUTCTime: // Likewise, both time types are treated the same. t.tag = tagUTCTime } if !matchAny && (t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag) { err = asn1.StructuralError{Msg: "sequence tag mismatch"} return } if invalidLength(offset, t.length, len(bytes)) { err = asn1.SyntaxError{Msg: "truncated sequence"} return } offset += t.length numElements++ } ret = reflect.MakeSlice(sliceType, numElements, numElements) params := fieldParameters{} offset := 0 for i := 0; i < numElements; i++ { offset, err = parseField(ret.Index(i), bytes, offset, params) if err != nil { return } } return } var ( bitStringType = reflect.TypeOf(asn1.BitString{}) objectIdentifierType = reflect.TypeOf(asn1.ObjectIdentifier{}) enumeratedType = reflect.TypeOf(asn1.Enumerated(0)) flagType = reflect.TypeOf(asn1.Flag(false)) timeType = reflect.TypeOf(time.Time{}) rawValueType = reflect.TypeOf(asn1.RawValue{}) rawContentsType = reflect.TypeOf(asn1.RawContent(nil)) bigIntType = reflect.TypeOf(new(big.Int)) ) // invalidLength reports whether offset + length > sliceLength, or if the // addition would overflow. func invalidLength(offset, length, sliceLength int) bool { return offset+length < offset || offset+length > sliceLength } // parseField is the main parsing function. Given a byte slice and an offset // into the array, it will try to parse a suitable ASN.1 value out and store it // in the given Value. func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) { offset = initOffset fieldType := v.Type() // If we have run out of data, it may be that there are optional elements at the end. if offset == len(bytes) { if !setDefaultValue(v, params) { err = asn1.SyntaxError{Msg: "sequence truncated"} } return } // Deal with the ANY type. if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 { var t tagAndLength t, offset, err = parseTagAndLength(bytes, offset) if err != nil { return } if invalidLength(offset, t.length, len(bytes)) { err = asn1.SyntaxError{Msg: "data truncated"} return } var result interface{} if !t.isCompound && t.class == classUniversal { innerBytes := bytes[offset : offset+t.length] switch t.tag { case tagPrintableString: result, err = parsePrintableString(innerBytes) case tagNumericString: result, err = parseNumericString(innerBytes) case tagIA5String: result, err = parseIA5String(innerBytes) case tagT61String: result, err = parseT61String(innerBytes) case tagUTF8String: result, err = parseUTF8String(innerBytes) case tagInteger: result, err = parseInt64(innerBytes) case tagBitString: result, err = parseBitString(innerBytes) case tagOID: result, err = parseObjectIdentifier(innerBytes) case tagUTCTime: result, err = parseUTCTime(innerBytes) case tagGeneralizedTime: result, err = parseGeneralizedTime(innerBytes) case tagOctetString: result = innerBytes case tagBMPString: result, err = parseBMPString(innerBytes) default: // If we don't know how to handle the type, we just leave Value as nil. } } offset += t.length if err != nil { return } if result != nil { v.Set(reflect.ValueOf(result)) } return } t, offset, err := parseTagAndLength(bytes, offset) if err != nil { return } if params.explicit { expectedClass := classContextSpecific if params.application { expectedClass = classApplication } if offset == len(bytes) { err = asn1.StructuralError{Msg: "explicit tag has no child"} return } if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) { if fieldType == rawValueType { // The inner element should not be parsed for RawValues. } else if t.length > 0 { t, offset, err = parseTagAndLength(bytes, offset) if err != nil { return } } else { if fieldType != flagType { err = asn1.StructuralError{Msg: "zero length explicit tag was not an asn1.Flag"} return } v.SetBool(true) return } } else { // The tags didn't match, it might be an optional element. ok := setDefaultValue(v, params) if ok { offset = initOffset } else { err = asn1.StructuralError{Msg: "explicitly tagged member didn't match"} } return } } matchAny, universalTag, compoundType, ok1 := getUniversalType(fieldType) if !ok1 { err = asn1.StructuralError{Msg: fmt.Sprintf("unknown Go type: %v", fieldType)} return } // Special case for strings: all the ASN.1 string types map to the Go // type string. getUniversalType returns the tag for PrintableString // when it sees a string, so if we see a different string type on the // wire, we change the universal type to match. if universalTag == tagPrintableString { if t.class == classUniversal { switch t.tag { case tagIA5String, tagGeneralString, tagT61String, tagUTF8String, tagNumericString, tagBMPString: universalTag = t.tag } } else if params.stringType != 0 { universalTag = params.stringType } } // Special case for time: UTCTime and GeneralizedTime both map to the // Go type time.Time. if universalTag == tagUTCTime && t.tag == tagGeneralizedTime && t.class == classUniversal { universalTag = tagGeneralizedTime } if params.set { universalTag = tagSet } matchAnyClassAndTag := matchAny expectedClass := classUniversal expectedTag := universalTag if !params.explicit && params.tag != nil { expectedClass = classContextSpecific expectedTag = *params.tag matchAnyClassAndTag = false } if !params.explicit && params.application && params.tag != nil { expectedClass = classApplication expectedTag = *params.tag matchAnyClassAndTag = false } if !params.explicit && params.private && params.tag != nil { expectedClass = classPrivate expectedTag = *params.tag matchAnyClassAndTag = false } // We have unwrapped any explicit tagging at this point. if !matchAnyClassAndTag && (t.class != expectedClass || t.tag != expectedTag) || (!matchAny && t.isCompound != compoundType) { // Tags don't match. Again, it could be an optional element. ok := setDefaultValue(v, params) if ok { offset = initOffset } else { err = asn1.StructuralError{Msg: fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)} } return } if invalidLength(offset, t.length, len(bytes)) { err = asn1.SyntaxError{Msg: "data truncated"} return } innerBytes := bytes[offset : offset+t.length] offset += t.length // We deal with the structures defined in this package first. switch fieldType { case rawValueType: result := asn1.RawValue{t.class, t.tag, t.isCompound, innerBytes, bytes[initOffset:offset]} v.Set(reflect.ValueOf(result)) return case objectIdentifierType: newSlice, err1 := parseObjectIdentifier(innerBytes) v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice))) if err1 == nil { reflect.Copy(v, reflect.ValueOf(newSlice)) } err = err1 return case bitStringType: bs, err1 := parseBitString(innerBytes) if err1 == nil { v.Set(reflect.ValueOf(bs)) } err = err1 return case timeType: var time time.Time var err1 error if universalTag == tagUTCTime { time, err1 = parseUTCTime(innerBytes) } else { time, err1 = parseGeneralizedTime(innerBytes) } if err1 == nil { v.Set(reflect.ValueOf(time)) } err = err1 return case enumeratedType: parsedInt, err1 := parseInt32(innerBytes) if err1 == nil { v.SetInt(int64(parsedInt)) } err = err1 return case flagType: v.SetBool(true) return case bigIntType: parsedInt, err1 := parseBigInt(innerBytes) if err1 == nil { v.Set(reflect.ValueOf(parsedInt)) } err = err1 return } switch val := v; val.Kind() { case reflect.Bool: parsedBool, err1 := parseBool(innerBytes) if err1 == nil { val.SetBool(parsedBool) } err = err1 return case reflect.Int, reflect.Int32, reflect.Int64: if val.Type().Size() == 4 { parsedInt, err1 := parseInt32(innerBytes) if err1 == nil { val.SetInt(int64(parsedInt)) } err = err1 } else { parsedInt, err1 := parseInt64(innerBytes) if err1 == nil { val.SetInt(parsedInt) } err = err1 } return // TODO(dfc) Add support for the remaining integer types case reflect.Struct: structType := fieldType for i := 0; i < structType.NumField(); i++ { if structType.Field(i).PkgPath != "" { err = asn1.StructuralError{Msg: "struct contains unexported fields"} return } } if structType.NumField() > 0 && structType.Field(0).Type == rawContentsType { bytes := bytes[initOffset:offset] val.Field(0).Set(reflect.ValueOf(asn1.RawContent(bytes))) } innerOffset := 0 for i := 0; i < structType.NumField(); i++ { field := structType.Field(i) if i == 0 && field.Type == rawContentsType { continue } innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1"))) if err != nil { return } } // We allow extra bytes at the end of the SEQUENCE because // adding elements to the end has been used in X.509 as the // version numbers have increased. return case reflect.Slice: sliceType := fieldType if sliceType.Elem().Kind() == reflect.Uint8 { val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes))) reflect.Copy(val, reflect.ValueOf(innerBytes)) return } newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem()) if err1 == nil { val.Set(newSlice) } err = err1 return case reflect.String: var v string switch universalTag { case tagPrintableString: v, err = parsePrintableString(innerBytes) case tagNumericString: v, err = parseNumericString(innerBytes) case tagIA5String: v, err = parseIA5String(innerBytes) case tagT61String: v, err = parseT61String(innerBytes) case tagUTF8String: v, err = parseUTF8String(innerBytes) case tagGeneralString: // GeneralString is specified in ISO-2022/ECMA-35, // A brief review suggests that it includes structures // that allow the encoding to change midstring and // such. We give up and pass it as an 8-bit string. v, err = parseT61String(innerBytes) case tagBMPString: v, err = parseBMPString(innerBytes) default: err = asn1.SyntaxError{Msg: fmt.Sprintf("internal error: unknown string type %d", universalTag)} } if err == nil { val.SetString(v) } return } err = asn1.StructuralError{Msg: "unsupported: " + v.Type().String()} return } // canHaveDefaultValue reports whether k is a Kind that we will set a default // value for. (A signed integer, essentially.) func canHaveDefaultValue(k reflect.Kind) bool { switch k { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return true } return false } // setDefaultValue is used to install a default value, from a tag string, into // a Value. It is successful if the field was optional, even if a default value // wasn't provided or it failed to install it into the Value. func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { if !params.optional { return } ok = true if params.defaultValue == nil { return } if canHaveDefaultValue(v.Kind()) { v.SetInt(*params.defaultValue) } return } // Unmarshal parses the BER-encoded ASN.1 data structure b // and uses the reflect package to fill in an arbitrary value pointed at by val. // Because Unmarshal uses the reflect package, the structs // being written to must use upper case field names. // // An ASN.1 INTEGER can be written to an int, int32, int64, // or *big.Int (from the math/big package). // If the encoded value does not fit in the Go type, // Unmarshal returns a parse error. // // An ASN.1 BIT STRING can be written to a BitString. // // An ASN.1 OCTET STRING can be written to a []byte. // // An ASN.1 OBJECT IDENTIFIER can be written to an // 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, IA5String, or NumericString can be written to a string. // // Any of the above ASN.1 values can be written to an interface{}. // The value stored in the interface has the corresponding Go type. // For integers, that type is int64. // // An ASN.1 SEQUENCE OF x or SET OF x can be written // to a slice if an x can be written to the slice's element type. // // An ASN.1 SEQUENCE or SET can be written to a struct // if each of the elements in the sequence can be // written to the corresponding element in the struct. // // The following tags on struct fields have special meaning to Unmarshal: // // application specifies that an APPLICATION tag is used // private specifies that a PRIVATE tag is used // default:x sets the default value for optional integer fields (only used if optional is also present) // explicit specifies that an additional, explicit tag wraps the implicit one // optional marks the field as ASN.1 OPTIONAL // set causes a SET, rather than a SEQUENCE type to be expected // tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC // // If the type of the first field of a structure is RawContent then the raw // ASN1 contents of the struct will be stored in it. // // If the type name of a slice element ends with "SET" then it's treated as if // the "set" tag was set on it. This can be used with nested slices where a // struct tag cannot be given. // // Other ASN.1 types are not supported; if it encounters them, // Unmarshal returns a parse error. func Unmarshal(b []byte, val interface{}) (rest []byte, err error) { return UnmarshalWithParams(b, val, "") } // UnmarshalWithParams allows field parameters to be specified for the // top-level element. The form of the params is the same as the field tags. func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) { v := reflect.ValueOf(val).Elem() offset, err := parseField(v, b, 0, parseFieldParameters(params)) if err != nil { return nil, err } return b[offset:], nil } ber-1.1.0/ber_64bit_test.go000066400000000000000000000010551364766032500154440ustar00rootroot00000000000000// +build amd64 package ber import "encoding/asn1" func init() { objectIdentifierTestData = append(objectIdentifierTestData, objectIdentifierTest{ []byte{ 0x2b, 0x06, 0x01, 0x04, 0x01, 0x09, 0x0a, 0x81, 0x0a, 0x01, 0x04, 0x01, 0x02, 0x01, 0x8c, 0x80, 0x80, 0x80, 0x01}, true, []int{1, 3, 6, 1, 4, 1, 9, 10, 138, 1, 4, 1, 2, 1, 3221225473}, }) marshalTests = append(marshalTests, marshalTest{ asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 9, 10, 138, 1, 4, 1, 2, 1, 3221225473}), "06132b06010401090a810a01040102018c80808001", }) } ber-1.1.0/ber_asn1_test.go000066400000000000000000001247731364766032500153730ustar00rootroot00000000000000// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ber import ( "bytes" "encoding/asn1" "encoding/hex" "fmt" "math" "math/big" "reflect" "strings" "testing" "time" ) type boolTest struct { in []byte ok bool out bool } var boolTestData = []boolTest{ {[]byte{0x00}, true, false}, {[]byte{0xff}, true, true}, {[]byte{0x00, 0x00}, false, false}, {[]byte{0xff, 0xff}, false, false}, {[]byte{0x01}, false, false}, } func TestParseBool(t *testing.T) { for i, test := range boolTestData { ret, err := parseBool(test.in) if (err == nil) != test.ok { t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) } if test.ok && ret != test.out { t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out) } } } type int64Test struct { in []byte ok bool out int64 } var int64TestData = []int64Test{ {[]byte{0x00}, true, 0}, {[]byte{0x7f}, true, 127}, {[]byte{0x00, 0x80}, true, 128}, {[]byte{0x01, 0x00}, true, 256}, {[]byte{0x80}, true, -128}, {[]byte{0xff, 0x7f}, true, -129}, {[]byte{0xff}, true, -1}, {[]byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, true, -9223372036854775808}, {[]byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, false, 0}, {[]byte{}, false, 0}, {[]byte{0x00, 0x7f}, false, 0}, {[]byte{0xff, 0xf0}, false, 0}, } func TestParseInt64(t *testing.T) { for i, test := range int64TestData { ret, err := parseInt64(test.in) if (err == nil) != test.ok { t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) } if test.ok && ret != test.out { t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out) } } } type int32Test struct { in []byte ok bool out int32 } var int32TestData = []int32Test{ {[]byte{0x00}, true, 0}, {[]byte{0x7f}, true, 127}, {[]byte{0x00, 0x80}, true, 128}, {[]byte{0x01, 0x00}, true, 256}, {[]byte{0x80}, true, -128}, {[]byte{0xff, 0x7f}, true, -129}, {[]byte{0xff}, true, -1}, {[]byte{0x80, 0x00, 0x00, 0x00}, true, -2147483648}, {[]byte{0x80, 0x00, 0x00, 0x00, 0x00}, false, 0}, {[]byte{}, false, 0}, {[]byte{0x00, 0x7f}, false, 0}, {[]byte{0xff, 0xf0}, false, 0}, } func TestParseInt32(t *testing.T) { for i, test := range int32TestData { ret, err := parseInt32(test.in) if (err == nil) != test.ok { t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) } if test.ok && int32(ret) != test.out { t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out) } } } var bigIntTests = []struct { in []byte ok bool base10 string }{ {[]byte{0xff}, true, "-1"}, {[]byte{0x00}, true, "0"}, {[]byte{0x01}, true, "1"}, {[]byte{0x00, 0xff}, true, "255"}, {[]byte{0xff, 0x00}, true, "-256"}, {[]byte{0x01, 0x00}, true, "256"}, {[]byte{}, false, ""}, {[]byte{0x00, 0x7f}, false, ""}, {[]byte{0xff, 0xf0}, false, ""}, } func TestParseBigInt(t *testing.T) { for i, test := range bigIntTests { ret, err := parseBigInt(test.in) if (err == nil) != test.ok { t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) } if test.ok { if ret.String() != test.base10 { t.Errorf("#%d: bad result from %x, got %s want %s", i, test.in, ret.String(), test.base10) } //e, err := makeBigInt(ret) //if err != nil { // t.Errorf("%d: err=%q", i, err) // continue //} //result := make([]byte, e.Len()) //e.Encode(result) //if !bytes.Equal(result, test.in) { // t.Errorf("#%d: got %x from marshaling %s, want %x", i, result, ret, test.in) //} } } } type bitStringTest struct { in []byte ok bool out []byte bitLength int } var bitStringTestData = []bitStringTest{ {[]byte{}, false, []byte{}, 0}, {[]byte{0x00}, true, []byte{}, 0}, {[]byte{0x07, 0x00}, true, []byte{0x00}, 1}, {[]byte{0x07, 0x01}, false, []byte{}, 0}, {[]byte{0x07, 0x40}, false, []byte{}, 0}, {[]byte{0x08, 0x00}, false, []byte{}, 0}, } func TestBitString(t *testing.T) { for i, test := range bitStringTestData { ret, err := parseBitString(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 test.bitLength != ret.BitLength || !bytes.Equal(ret.Bytes, test.out) { t.Errorf("#%d: Bad result: %v (expected %v %v)", i, ret, test.out, test.bitLength) } } } } func TestBitStringAt(t *testing.T) { bs := asn1.BitString{[]byte{0x82, 0x40}, 16} if bs.At(0) != 1 { t.Error("#1: Failed") } if bs.At(1) != 0 { t.Error("#2: Failed") } if bs.At(6) != 1 { t.Error("#3: Failed") } if bs.At(9) != 1 { t.Error("#4: Failed") } if bs.At(-1) != 0 { t.Error("#5: Failed") } if bs.At(17) != 0 { t.Error("#6: Failed") } } type bitStringRightAlignTest struct { in []byte inlen int out []byte } var bitStringRightAlignTests = []bitStringRightAlignTest{ {[]byte{0x80}, 1, []byte{0x01}}, {[]byte{0x80, 0x80}, 9, []byte{0x01, 0x01}}, {[]byte{}, 0, []byte{}}, {[]byte{0xce}, 8, []byte{0xce}}, {[]byte{0xce, 0x47}, 16, []byte{0xce, 0x47}}, {[]byte{0x34, 0x50}, 12, []byte{0x03, 0x45}}, } func TestBitStringRightAlign(t *testing.T) { for i, test := range bitStringRightAlignTests { bs := asn1.BitString{test.in, test.inlen} out := bs.RightAlign() if !bytes.Equal(out, test.out) { t.Errorf("#%d got: %x want: %x", i, out, test.out) } } } type objectIdentifierTest struct { in []byte ok bool out asn1.ObjectIdentifier // has base type[]int } var objectIdentifierTestData = []objectIdentifierTest{ {[]byte{}, false, []int{}}, {[]byte{85}, true, []int{2, 5}}, {[]byte{85, 0x02}, true, []int{2, 5, 2}}, {[]byte{85, 0x02, 0xc0, 0x00}, true, []int{2, 5, 2, 0x2000}}, {[]byte{0x81, 0x34, 0x03}, true, []int{2, 100, 3}}, {[]byte{85, 0x02, 0xc0, 0x80, 0x80, 0x80, 0x80}, false, []int{}}, } func TestObjectIdentifier(t *testing.T) { for i, test := range objectIdentifierTestData { ret, err := parseObjectIdentifier(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) } } } if s := asn1.ObjectIdentifier([]int{1, 2, 3, 4}).String(); s != "1.2.3.4" { t.Errorf("bad ObjectIdentifier.String(). Got %s, want 1.2.3.4", s) } } type timeTest struct { in string ok bool out time.Time } var utcTestData = []timeTest{ {"910506164540-0700", true, time.Date(1991, 05, 06, 16, 45, 40, 0, time.FixedZone("", -7*60*60))}, {"910506164540+0730", true, time.Date(1991, 05, 06, 16, 45, 40, 0, time.FixedZone("", 7*60*60+30*60))}, {"910506234540Z", true, time.Date(1991, 05, 06, 23, 45, 40, 0, time.UTC)}, {"9105062345Z", true, time.Date(1991, 05, 06, 23, 45, 0, 0, time.UTC)}, {"5105062345Z", true, time.Date(1951, 05, 06, 23, 45, 0, 0, time.UTC)}, {"a10506234540Z", false, time.Time{}}, {"91a506234540Z", false, time.Time{}}, {"9105a6234540Z", false, time.Time{}}, {"910506a34540Z", false, time.Time{}}, {"910506334a40Z", false, time.Time{}}, {"91050633444aZ", false, time.Time{}}, {"910506334461Z", false, time.Time{}}, {"910506334400Za", false, time.Time{}}, /* These are invalid times. However, the time package normalises times * and they were accepted in some versions. See #11134. */ {"000100000000Z", false, time.Time{}}, {"101302030405Z", false, time.Time{}}, {"100002030405Z", false, time.Time{}}, {"100100030405Z", false, time.Time{}}, {"100132030405Z", false, time.Time{}}, {"100231030405Z", false, time.Time{}}, {"100102240405Z", false, time.Time{}}, {"100102036005Z", false, time.Time{}}, {"100102030460Z", false, time.Time{}}, {"-100102030410Z", false, time.Time{}}, {"10-0102030410Z", false, time.Time{}}, {"10-0002030410Z", false, time.Time{}}, {"1001-02030410Z", false, time.Time{}}, {"100102-030410Z", false, time.Time{}}, {"10010203-0410Z", false, time.Time{}}, {"1001020304-10Z", false, time.Time{}}, } func TestUTCTime(t *testing.T) { for i, test := range utcTestData { ret, err := parseUTCTime([]byte(test.in)) if err != nil { if test.ok { t.Errorf("#%d: parseUTCTime(%q) = error %v", i, test.in, err) } continue } if !test.ok { t.Errorf("#%d: parseUTCTime(%q) succeeded, should have failed", i, test.in) continue } const format = "Jan _2 15:04:05 -0700 2006" // ignore zone name, just offset have := ret.Format(format) want := test.out.Format(format) if have != want { t.Errorf("#%d: parseUTCTime(%q) = %s, want %s", i, test.in, have, want) } } } var generalizedTimeTestData = []timeTest{ {"20100102030405Z", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.UTC)}, {"20100102030405", false, time.Time{}}, {"20100102030405+0607", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.FixedZone("", 6*60*60+7*60))}, {"20100102030405-0607", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.FixedZone("", -6*60*60-7*60))}, /* These are invalid times. However, the time package normalises times * and they were accepted in some versions. See #11134. */ {"00000100000000Z", false, time.Time{}}, {"20101302030405Z", false, time.Time{}}, {"20100002030405Z", false, time.Time{}}, {"20100100030405Z", false, time.Time{}}, {"20100132030405Z", false, time.Time{}}, {"20100231030405Z", false, time.Time{}}, {"20100102240405Z", false, time.Time{}}, {"20100102036005Z", false, time.Time{}}, {"20100102030460Z", false, time.Time{}}, {"-20100102030410Z", false, time.Time{}}, {"2010-0102030410Z", false, time.Time{}}, {"2010-0002030410Z", false, time.Time{}}, {"201001-02030410Z", false, time.Time{}}, {"20100102-030410Z", false, time.Time{}}, {"2010010203-0410Z", false, time.Time{}}, {"201001020304-10Z", false, time.Time{}}, } 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: %q → %v (expected %v)", i, test.in, ret, test.out) } } } } type tagAndLengthTest struct { in []byte ok bool out tagAndLength } var tagAndLengthData = []tagAndLengthTest{ {[]byte{0x80, 0x01}, true, tagAndLength{2, 0, 1, false}}, {[]byte{0xa0, 0x01}, true, tagAndLength{2, 0, 1, true}}, {[]byte{0x02, 0x00}, true, tagAndLength{0, 2, 0, false}}, {[]byte{0xfe, 0x00}, true, tagAndLength{3, 30, 0, true}}, {[]byte{0x1f, 0x1f, 0x00}, true, tagAndLength{0, 31, 0, false}}, {[]byte{0x1f, 0x81, 0x00, 0x00}, true, tagAndLength{0, 128, 0, false}}, {[]byte{0x1f, 0x81, 0x80, 0x01, 0x00}, true, tagAndLength{0, 0x4001, 0, false}}, {[]byte{0x00, 0x81, 0x80}, true, tagAndLength{0, 0, 128, false}}, {[]byte{0x00, 0x82, 0x01, 0x00}, true, tagAndLength{0, 0, 256, false}}, {[]byte{0x00, 0x83, 0x01, 0x00}, false, tagAndLength{}}, {[]byte{0x1f, 0x85}, false, tagAndLength{}}, {[]byte{0x30, 0x80}, false, tagAndLength{}}, // Superfluous zeros in the length should be an error. {[]byte{0xa0, 0x82, 0x00, 0xff}, false, tagAndLength{}}, // Lengths up to the maximum size of an int should work. {[]byte{0xa0, 0x84, 0x7f, 0xff, 0xff, 0xff}, true, tagAndLength{2, 0, 0x7fffffff, true}}, // Lengths that would overflow an int should be rejected. {[]byte{0xa0, 0x84, 0x80, 0x00, 0x00, 0x00}, false, tagAndLength{}}, // Long length form may not be used for lengths that fit in short form. {[]byte{0xa0, 0x81, 0x7f}, false, tagAndLength{}}, // Tag numbers which would overflow int32 are rejected. (The value below is 2^31.) {[]byte{0x1f, 0x88, 0x80, 0x80, 0x80, 0x00, 0x00}, false, tagAndLength{}}, // Tag numbers that fit in an int32 are valid. (The value below is 2^31 - 1.) {[]byte{0x1f, 0x87, 0xFF, 0xFF, 0xFF, 0x7F, 0x00}, true, tagAndLength{tag: math.MaxInt32}}, // Long tag number form may not be used for tags that fit in short form. {[]byte{0x1f, 0x1e, 0x00}, false, tagAndLength{}}, } func TestParseTagAndLength(t *testing.T) { for i, test := range tagAndLengthData { tagAndLength, _, err := parseTagAndLength(test.in, 0) if (err == nil) != test.ok { t.Errorf("#%d: Incorrect error result (did pass? %v, expected: %v)", i, err == nil, test.ok) } if err == nil && !reflect.DeepEqual(test.out, tagAndLength) { t.Errorf("#%d: Bad result: %v (expected %v)", i, tagAndLength, test.out) } } } type parseFieldParametersTest struct { in string out fieldParameters } func newInt(n int) *int { return &n } func newInt64(n int64) *int64 { return &n } func newString(s string) *string { return &s } func newBool(b bool) *bool { return &b } var parseFieldParametersTestData []parseFieldParametersTest = []parseFieldParametersTest{ {"", fieldParameters{}}, {"ia5", fieldParameters{stringType: tagIA5String}}, {"generalized", fieldParameters{timeType: tagGeneralizedTime}}, {"utc", fieldParameters{timeType: tagUTCTime}}, {"printable", fieldParameters{stringType: tagPrintableString}}, {"numeric", fieldParameters{stringType: tagNumericString}}, {"optional", fieldParameters{optional: true}}, {"explicit", fieldParameters{explicit: true, tag: new(int)}}, {"application", fieldParameters{application: true, tag: new(int)}}, {"private", fieldParameters{private: true, tag: new(int)}}, {"optional,explicit", fieldParameters{optional: true, explicit: true, tag: new(int)}}, {"default:42", fieldParameters{defaultValue: newInt64(42)}}, {"tag:17", fieldParameters{tag: newInt(17)}}, {"optional,explicit,default:42,tag:17", fieldParameters{optional: true, explicit: true, defaultValue: newInt64(42), tag: newInt(17)}}, {"optional,explicit,default:42,tag:17,rubbish1", fieldParameters{optional: true, explicit: true, application: false, defaultValue: newInt64(42), tag: newInt(17), stringType: 0, timeType: 0, set: false, omitEmpty: false}}, {"set", fieldParameters{set: true}}, } func TestParseFieldParameters(t *testing.T) { for i, test := range parseFieldParametersTestData { f := parseFieldParameters(test.in) if !reflect.DeepEqual(f, test.out) { t.Errorf("#%d: Bad result: %v (expected %v)", i, f, test.out) } } } type TestObjectIdentifierStruct struct { OID asn1.ObjectIdentifier } type TestContextSpecificTags struct { A int `asn1:"tag:1"` } type TestContextSpecificTags2 struct { A int `asn1:"explicit,tag:1"` B int } type TestContextSpecificTags3 struct { S string `asn1:"tag:1,utf8"` } type TestElementsAfterString struct { S string A, B int } type TestBigInt struct { X *big.Int } type TestSet struct { Ints []int `asn1:"set"` } var unmarshalTestData = []struct { in []byte out interface{} }{ {[]byte{0x02, 0x01, 0x42}, newInt(0x42)}, {[]byte{0x05, 0x00}, &asn1.RawValue{0, 5, false, []byte{}, []byte{0x05, 0x00}}}, {[]byte{0x30, 0x08, 0x06, 0x06, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d}, &TestObjectIdentifierStruct{[]int{1, 2, 840, 113549}}}, {[]byte{0x03, 0x04, 0x06, 0x6e, 0x5d, 0xc0}, &asn1.BitString{[]byte{110, 93, 192}, 18}}, {[]byte{0x30, 0x09, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x01, 0x03}, &[]int{1, 2, 3}}, {[]byte{0x02, 0x01, 0x10}, newInt(16)}, {[]byte{0x13, 0x04, 't', 'e', 's', 't'}, newString("test")}, {[]byte{0x16, 0x04, 't', 'e', 's', 't'}, newString("test")}, // Ampersand is allowed in PrintableString due to mistakes by major CAs. {[]byte{0x13, 0x05, 't', 'e', 's', 't', '&'}, newString("test&")}, {[]byte{0x16, 0x04, 't', 'e', 's', 't'}, &asn1.RawValue{0, 22, false, []byte("test"), []byte("\x16\x04test")}}, {[]byte{0x04, 0x04, 1, 2, 3, 4}, &asn1.RawValue{0, 4, false, []byte{1, 2, 3, 4}, []byte{4, 4, 1, 2, 3, 4}}}, {[]byte{0x30, 0x03, 0x81, 0x01, 0x01}, &TestContextSpecificTags{1}}, {[]byte{0x30, 0x08, 0xa1, 0x03, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02}, &TestContextSpecificTags2{1, 2}}, {[]byte{0x30, 0x03, 0x81, 0x01, '@'}, &TestContextSpecificTags3{"@"}}, {[]byte{0x01, 0x01, 0x00}, newBool(false)}, {[]byte{0x01, 0x01, 0xff}, newBool(true)}, {[]byte{0x30, 0x0b, 0x13, 0x03, 0x66, 0x6f, 0x6f, 0x02, 0x01, 0x22, 0x02, 0x01, 0x33}, &TestElementsAfterString{"foo", 0x22, 0x33}}, {[]byte{0x30, 0x05, 0x02, 0x03, 0x12, 0x34, 0x56}, &TestBigInt{big.NewInt(0x123456)}}, {[]byte{0x30, 0x0b, 0x31, 0x09, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x01, 0x03}, &TestSet{Ints: []int{1, 2, 3}}}, {[]byte{0x12, 0x0b, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' '}, newString("0123456789 ")}, } func TestUnmarshal(t *testing.T) { for i, test := range unmarshalTestData { pv := reflect.New(reflect.TypeOf(test.out).Elem()) val := pv.Interface() _, err := Unmarshal(test.in, val) if err != nil { t.Errorf("Unmarshal failed at index %d %v", i, err) } if !reflect.DeepEqual(val, test.out) { t.Errorf("#%d:\nhave %#v\nwant %#v", i, val, test.out) } } } type Certificate struct { TBSCertificate TBSCertificate SignatureAlgorithm AlgorithmIdentifier SignatureValue asn1.BitString } type TBSCertificate struct { Version int `asn1:"optional,explicit,default:0,tag:0"` SerialNumber asn1.RawValue SignatureAlgorithm AlgorithmIdentifier Issuer RDNSequence Validity Validity Subject RDNSequence PublicKey PublicKeyInfo } type AlgorithmIdentifier struct { Algorithm asn1.ObjectIdentifier } type RDNSequence []RelativeDistinguishedNameSET type RelativeDistinguishedNameSET []AttributeTypeAndValue type AttributeTypeAndValue struct { Type asn1.ObjectIdentifier Value interface{} } type Validity struct { NotBefore, NotAfter time.Time } type PublicKeyInfo struct { Algorithm AlgorithmIdentifier PublicKey asn1.BitString } func TestCertificate(t *testing.T) { // This is a minimal, self-signed certificate that should parse correctly. var cert Certificate if _, err := Unmarshal(derEncodedSelfSignedCertBytes, &cert); err != nil { t.Errorf("Unmarshal failed: %v", err) } if !reflect.DeepEqual(cert, derEncodedSelfSignedCert) { t.Errorf("Bad result:\ngot: %+v\nwant: %+v", cert, derEncodedSelfSignedCert) } } func TestCertificateWithNUL(t *testing.T) { // This is the paypal NUL-hack certificate. It should fail to parse because // NUL isn't a permitted character in a PrintableString. var cert Certificate if _, err := Unmarshal(derEncodedPaypalNULCertBytes, &cert); err == nil { t.Error("Unmarshal succeeded, should not have") } } type rawStructTest struct { Raw asn1.RawContent A int } func TestRawStructs(t *testing.T) { var s rawStructTest input := []byte{0x30, 0x03, 0x02, 0x01, 0x50} rest, err := Unmarshal(input, &s) if len(rest) != 0 { t.Errorf("incomplete parse: %x", rest) return } if err != nil { t.Error(err) return } if s.A != 0x50 { t.Errorf("bad value for A: got %d want %d", s.A, 0x50) } if !bytes.Equal([]byte(s.Raw), input) { t.Errorf("bad value for Raw: got %x want %x", s.Raw, input) } } type oiEqualTest struct { first asn1.ObjectIdentifier second asn1.ObjectIdentifier same bool } var oiEqualTests = []oiEqualTest{ { asn1.ObjectIdentifier{1, 2, 3}, asn1.ObjectIdentifier{1, 2, 3}, true, }, { asn1.ObjectIdentifier{1}, asn1.ObjectIdentifier{1, 2, 3}, false, }, { asn1.ObjectIdentifier{1, 2, 3}, asn1.ObjectIdentifier{10, 11, 12}, false, }, } func TestObjectIdentifierEqual(t *testing.T) { for _, o := range oiEqualTests { if s := o.first.Equal(o.second); s != o.same { t.Errorf("ObjectIdentifier.Equal: got: %t want: %t", s, o.same) } } } var derEncodedSelfSignedCert = Certificate{ TBSCertificate: TBSCertificate{ Version: 0, SerialNumber: asn1.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: asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}}, Issuer: RDNSequence{ RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 6}, Value: "XX"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 8}, Value: "Some-State"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 7}, Value: "City"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 10}, Value: "Internet Widgits Pty Ltd"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 3}, Value: "false.example.com"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}, Value: "false@example.com"}}, }, Validity: Validity{ NotBefore: time.Date(2009, 10, 8, 00, 25, 53, 0, time.UTC), NotAfter: time.Date(2010, 10, 8, 00, 25, 53, 0, time.UTC), }, Subject: RDNSequence{ RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 6}, Value: "XX"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 8}, Value: "Some-State"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 7}, Value: "City"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 10}, Value: "Internet Widgits Pty Ltd"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{2, 5, 4, 3}, Value: "false.example.com"}}, RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}, Value: "false@example.com"}}, }, PublicKey: PublicKeyInfo{ Algorithm: AlgorithmIdentifier{Algorithm: asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}}, PublicKey: asn1.BitString{ Bytes: []uint8{ 0x30, 0x48, 0x2, 0x41, 0x0, 0xcd, 0xb7, 0x63, 0x9c, 0x32, 0x78, 0xf0, 0x6, 0xaa, 0x27, 0x7f, 0x6e, 0xaf, 0x42, 0x90, 0x2b, 0x59, 0x2d, 0x8c, 0xbc, 0xbe, 0x38, 0xa1, 0xc9, 0x2b, 0xa4, 0x69, 0x5a, 0x33, 0x1b, 0x1d, 0xea, 0xde, 0xad, 0xd8, 0xe9, 0xa5, 0xc2, 0x7e, 0x8c, 0x4c, 0x2f, 0xd0, 0xa8, 0x88, 0x96, 0x57, 0x72, 0x2a, 0x4f, 0x2a, 0xf7, 0x58, 0x9c, 0xf2, 0xc7, 0x70, 0x45, 0xdc, 0x8f, 0xde, 0xec, 0x35, 0x7d, 0x2, 0x3, 0x1, 0x0, 0x1, }, BitLength: 592, }, }, }, SignatureAlgorithm: AlgorithmIdentifier{Algorithm: asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}}, SignatureValue: asn1.BitString{ Bytes: []uint8{ 0xa6, 0x7b, 0x6, 0xec, 0x5e, 0xce, 0x92, 0x77, 0x2c, 0xa4, 0x13, 0xcb, 0xa3, 0xca, 0x12, 0x56, 0x8f, 0xdc, 0x6c, 0x7b, 0x45, 0x11, 0xcd, 0x40, 0xa7, 0xf6, 0x59, 0x98, 0x4, 0x2, 0xdf, 0x2b, 0x99, 0x8b, 0xb9, 0xa4, 0xa8, 0xcb, 0xeb, 0x34, 0xc0, 0xf0, 0xa7, 0x8c, 0xf8, 0xd9, 0x1e, 0xde, 0x14, 0xa5, 0xed, 0x76, 0xbf, 0x11, 0x6f, 0xe3, 0x60, 0xaa, 0xfa, 0x88, 0x21, 0x49, 0x4, 0x35, }, BitLength: 512, }, } var derEncodedSelfSignedCertBytes = []byte{ 0x30, 0x82, 0x02, 0x18, 0x30, 0x82, 0x01, 0xc2, 0x02, 0x09, 0x00, 0x8c, 0xc3, 0x37, 0x92, 0x10, 0xec, 0x2c, 0x98, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x81, 0x92, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x58, 0x58, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x04, 0x43, 0x69, 0x74, 0x79, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x40, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x1e, 0x17, 0x0d, 0x30, 0x39, 0x31, 0x30, 0x30, 0x38, 0x30, 0x30, 0x32, 0x35, 0x35, 0x33, 0x5a, 0x17, 0x0d, 0x31, 0x30, 0x31, 0x30, 0x30, 0x38, 0x30, 0x30, 0x32, 0x35, 0x35, 0x33, 0x5a, 0x30, 0x81, 0x92, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x58, 0x58, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x04, 0x43, 0x69, 0x74, 0x79, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x40, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x5c, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x4b, 0x00, 0x30, 0x48, 0x02, 0x41, 0x00, 0xcd, 0xb7, 0x63, 0x9c, 0x32, 0x78, 0xf0, 0x06, 0xaa, 0x27, 0x7f, 0x6e, 0xaf, 0x42, 0x90, 0x2b, 0x59, 0x2d, 0x8c, 0xbc, 0xbe, 0x38, 0xa1, 0xc9, 0x2b, 0xa4, 0x69, 0x5a, 0x33, 0x1b, 0x1d, 0xea, 0xde, 0xad, 0xd8, 0xe9, 0xa5, 0xc2, 0x7e, 0x8c, 0x4c, 0x2f, 0xd0, 0xa8, 0x88, 0x96, 0x57, 0x72, 0x2a, 0x4f, 0x2a, 0xf7, 0x58, 0x9c, 0xf2, 0xc7, 0x70, 0x45, 0xdc, 0x8f, 0xde, 0xec, 0x35, 0x7d, 0x02, 0x03, 0x01, 0x00, 0x01, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x41, 0x00, 0xa6, 0x7b, 0x06, 0xec, 0x5e, 0xce, 0x92, 0x77, 0x2c, 0xa4, 0x13, 0xcb, 0xa3, 0xca, 0x12, 0x56, 0x8f, 0xdc, 0x6c, 0x7b, 0x45, 0x11, 0xcd, 0x40, 0xa7, 0xf6, 0x59, 0x98, 0x04, 0x02, 0xdf, 0x2b, 0x99, 0x8b, 0xb9, 0xa4, 0xa8, 0xcb, 0xeb, 0x34, 0xc0, 0xf0, 0xa7, 0x8c, 0xf8, 0xd9, 0x1e, 0xde, 0x14, 0xa5, 0xed, 0x76, 0xbf, 0x11, 0x6f, 0xe3, 0x60, 0xaa, 0xfa, 0x88, 0x21, 0x49, 0x04, 0x35, } var derEncodedPaypalNULCertBytes = []byte{ 0x30, 0x82, 0x06, 0x44, 0x30, 0x82, 0x05, 0xad, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x03, 0x00, 0xf0, 0x9b, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x82, 0x01, 0x12, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x45, 0x53, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x09, 0x42, 0x61, 0x72, 0x63, 0x65, 0x6c, 0x6f, 0x6e, 0x61, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x09, 0x42, 0x61, 0x72, 0x63, 0x65, 0x6c, 0x6f, 0x6e, 0x61, 0x31, 0x29, 0x30, 0x27, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x20, 0x49, 0x50, 0x53, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x20, 0x73, 0x2e, 0x6c, 0x2e, 0x31, 0x2e, 0x30, 0x2c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x14, 0x25, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x40, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x43, 0x2e, 0x49, 0x2e, 0x46, 0x2e, 0x20, 0x20, 0x42, 0x2d, 0x42, 0x36, 0x32, 0x32, 0x31, 0x30, 0x36, 0x39, 0x35, 0x31, 0x2e, 0x30, 0x2c, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x25, 0x69, 0x70, 0x73, 0x43, 0x41, 0x20, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x31, 0x2e, 0x30, 0x2c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x25, 0x69, 0x70, 0x73, 0x43, 0x41, 0x20, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x40, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x1e, 0x17, 0x0d, 0x30, 0x39, 0x30, 0x32, 0x32, 0x34, 0x32, 0x33, 0x30, 0x34, 0x31, 0x37, 0x5a, 0x17, 0x0d, 0x31, 0x31, 0x30, 0x32, 0x32, 0x34, 0x32, 0x33, 0x30, 0x34, 0x31, 0x37, 0x5a, 0x30, 0x81, 0x94, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, 0x43, 0x61, 0x6c, 0x69, 0x66, 0x6f, 0x72, 0x6e, 0x69, 0x61, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0d, 0x53, 0x61, 0x6e, 0x20, 0x46, 0x72, 0x61, 0x6e, 0x63, 0x69, 0x73, 0x63, 0x6f, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x0b, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x55, 0x6e, 0x69, 0x74, 0x31, 0x2f, 0x30, 0x2d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x26, 0x77, 0x77, 0x77, 0x2e, 0x70, 0x61, 0x79, 0x70, 0x61, 0x6c, 0x2e, 0x63, 0x6f, 0x6d, 0x00, 0x73, 0x73, 0x6c, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x63, 0x63, 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xd2, 0x69, 0xfa, 0x6f, 0x3a, 0x00, 0xb4, 0x21, 0x1b, 0xc8, 0xb1, 0x02, 0xd7, 0x3f, 0x19, 0xb2, 0xc4, 0x6d, 0xb4, 0x54, 0xf8, 0x8b, 0x8a, 0xcc, 0xdb, 0x72, 0xc2, 0x9e, 0x3c, 0x60, 0xb9, 0xc6, 0x91, 0x3d, 0x82, 0xb7, 0x7d, 0x99, 0xff, 0xd1, 0x29, 0x84, 0xc1, 0x73, 0x53, 0x9c, 0x82, 0xdd, 0xfc, 0x24, 0x8c, 0x77, 0xd5, 0x41, 0xf3, 0xe8, 0x1e, 0x42, 0xa1, 0xad, 0x2d, 0x9e, 0xff, 0x5b, 0x10, 0x26, 0xce, 0x9d, 0x57, 0x17, 0x73, 0x16, 0x23, 0x38, 0xc8, 0xd6, 0xf1, 0xba, 0xa3, 0x96, 0x5b, 0x16, 0x67, 0x4a, 0x4f, 0x73, 0x97, 0x3a, 0x4d, 0x14, 0xa4, 0xf4, 0xe2, 0x3f, 0x8b, 0x05, 0x83, 0x42, 0xd1, 0xd0, 0xdc, 0x2f, 0x7a, 0xe5, 0xb6, 0x10, 0xb2, 0x11, 0xc0, 0xdc, 0x21, 0x2a, 0x90, 0xff, 0xae, 0x97, 0x71, 0x5a, 0x49, 0x81, 0xac, 0x40, 0xf3, 0x3b, 0xb8, 0x59, 0xb2, 0x4f, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x82, 0x03, 0x21, 0x30, 0x82, 0x03, 0x1d, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x11, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x01, 0x04, 0x04, 0x03, 0x02, 0x06, 0x40, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x03, 0xf8, 0x30, 0x13, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x0c, 0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x61, 0x8f, 0x61, 0x34, 0x43, 0x55, 0x14, 0x7f, 0x27, 0x09, 0xce, 0x4c, 0x8b, 0xea, 0x9b, 0x7b, 0x19, 0x25, 0xbc, 0x6e, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x0e, 0x07, 0x60, 0xd4, 0x39, 0xc9, 0x1b, 0x5b, 0x5d, 0x90, 0x7b, 0x23, 0xc8, 0xd2, 0x34, 0x9d, 0x4a, 0x9a, 0x46, 0x39, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x11, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1c, 0x06, 0x03, 0x55, 0x1d, 0x12, 0x04, 0x15, 0x30, 0x13, 0x81, 0x11, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x40, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x72, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x0d, 0x04, 0x65, 0x16, 0x63, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x4e, 0x4f, 0x54, 0x20, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x41, 0x54, 0x45, 0x44, 0x2e, 0x20, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x20, 0x69, 0x73, 0x73, 0x75, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x30, 0x2f, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x02, 0x04, 0x22, 0x16, 0x20, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x30, 0x43, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x04, 0x04, 0x36, 0x16, 0x34, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x63, 0x72, 0x6c, 0x30, 0x46, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x03, 0x04, 0x39, 0x16, 0x37, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x72, 0x65, 0x76, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x3f, 0x30, 0x43, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x07, 0x04, 0x36, 0x16, 0x34, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x72, 0x65, 0x6e, 0x65, 0x77, 0x61, 0x6c, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x3f, 0x30, 0x41, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x08, 0x04, 0x34, 0x16, 0x32, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x30, 0x81, 0x83, 0x06, 0x03, 0x55, 0x1d, 0x1f, 0x04, 0x7c, 0x30, 0x7a, 0x30, 0x39, 0xa0, 0x37, 0xa0, 0x35, 0x86, 0x33, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x63, 0x72, 0x6c, 0x30, 0x3d, 0xa0, 0x3b, 0xa0, 0x39, 0x86, 0x37, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x62, 0x61, 0x63, 0x6b, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x63, 0x72, 0x6c, 0x30, 0x32, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01, 0x04, 0x26, 0x30, 0x24, 0x30, 0x22, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x86, 0x16, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6f, 0x63, 0x73, 0x70, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x68, 0xee, 0x79, 0x97, 0x97, 0xdd, 0x3b, 0xef, 0x16, 0x6a, 0x06, 0xf2, 0x14, 0x9a, 0x6e, 0xcd, 0x9e, 0x12, 0xf7, 0xaa, 0x83, 0x10, 0xbd, 0xd1, 0x7c, 0x98, 0xfa, 0xc7, 0xae, 0xd4, 0x0e, 0x2c, 0x9e, 0x38, 0x05, 0x9d, 0x52, 0x60, 0xa9, 0x99, 0x0a, 0x81, 0xb4, 0x98, 0x90, 0x1d, 0xae, 0xbb, 0x4a, 0xd7, 0xb9, 0xdc, 0x88, 0x9e, 0x37, 0x78, 0x41, 0x5b, 0xf7, 0x82, 0xa5, 0xf2, 0xba, 0x41, 0x25, 0x5a, 0x90, 0x1a, 0x1e, 0x45, 0x38, 0xa1, 0x52, 0x58, 0x75, 0x94, 0x26, 0x44, 0xfb, 0x20, 0x07, 0xba, 0x44, 0xcc, 0xe5, 0x4a, 0x2d, 0x72, 0x3f, 0x98, 0x47, 0xf6, 0x26, 0xdc, 0x05, 0x46, 0x05, 0x07, 0x63, 0x21, 0xab, 0x46, 0x9b, 0x9c, 0x78, 0xd5, 0x54, 0x5b, 0x3d, 0x0c, 0x1e, 0xc8, 0x64, 0x8c, 0xb5, 0x50, 0x23, 0x82, 0x6f, 0xdb, 0xb8, 0x22, 0x1c, 0x43, 0x96, 0x07, 0xa8, 0xbb, } var stringSliceTestData = [][]string{ {"foo", "bar"}, {"foo", "\\bar"}, {"foo", "\"bar\""}, {"foo", "åäö"}, } func TestStringSlice(t *testing.T) { for _, test := range stringSliceTestData { bs, err := Marshal(test) if err != nil { t.Error(err) } var res []string _, err = Unmarshal(bs, &res) if err != nil { t.Error(err) } if fmt.Sprintf("%v", res) != fmt.Sprintf("%v", test) { t.Errorf("incorrect marshal/unmarshal; %v != %v", res, test) } } } type explicitTaggedTimeTest struct { Time time.Time `asn1:"explicit,tag:0"` } var explicitTaggedTimeTestData = []struct { in []byte out explicitTaggedTimeTest }{ {[]byte{0x30, 0x11, 0xa0, 0xf, 0x17, 0xd, '9', '1', '0', '5', '0', '6', '1', '6', '4', '5', '4', '0', 'Z'}, explicitTaggedTimeTest{time.Date(1991, 05, 06, 16, 45, 40, 0, time.UTC)}}, {[]byte{0x30, 0x17, 0xa0, 0xf, 0x18, 0x13, '2', '0', '1', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '+', '0', '6', '0', '7'}, explicitTaggedTimeTest{time.Date(2010, 01, 02, 03, 04, 05, 0, time.FixedZone("", 6*60*60+7*60))}}, } func TestExplicitTaggedTime(t *testing.T) { // Test that a time.Time will match either tagUTCTime or // tagGeneralizedTime. for i, test := range explicitTaggedTimeTestData { var got explicitTaggedTimeTest _, err := Unmarshal(test.in, &got) if err != nil { t.Errorf("Unmarshal failed at index %d %v", i, err) } if !got.Time.Equal(test.out.Time) { t.Errorf("#%d: got %v, want %v", i, got.Time, test.out.Time) } } } type implicitTaggedTimeTest struct { Time time.Time `asn1:"tag:24"` } func TestImplicitTaggedTime(t *testing.T) { // An implicitly tagged time value, that happens to have an implicit // tag equal to a GENERALIZEDTIME, should still be parsed as a UTCTime. // (There's no "timeType" in fieldParameters to determine what type of // time should be expected when implicitly tagged.) der := []byte{0x30, 0x0f, 0x80 | 24, 0xd, '9', '1', '0', '5', '0', '6', '1', '6', '4', '5', '4', '0', 'Z'} var result implicitTaggedTimeTest if _, err := Unmarshal(der, &result); err != nil { t.Fatalf("Error while parsing: %s", err) } if expected := time.Date(1991, 05, 06, 16, 45, 40, 0, time.UTC); !result.Time.Equal(expected) { t.Errorf("Wrong result. Got %v, want %v", result.Time, expected) } } type truncatedExplicitTagTest struct { Test int `asn1:"explicit,tag:0"` } func TestTruncatedExplicitTag(t *testing.T) { // This crashed Unmarshal in the past. See #11154. der := []byte{ 0x30, // SEQUENCE 0x02, // two bytes long 0xa0, // context-specific, tag 0 0x30, // 48 bytes long } var result truncatedExplicitTagTest if _, err := Unmarshal(der, &result); err == nil { 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()) } } func TestMarshalNilValue(t *testing.T) { nilValueTestData := []interface{}{ nil, struct{ V interface{} }{}, } for i, test := range nilValueTestData { if _, err := Marshal(test); err == nil { t.Fatalf("#%d: successfully marshaled nil value", i) } } } type unexported struct { X int y int } type exported struct { X int Y int } func TestUnexportedStructField(t *testing.T) { want := asn1.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) } } func TestNull(t *testing.T) { marshaled, err := Marshal(NullRawValue) if err != nil { t.Fatal(err) } if !bytes.Equal(NullBytes, marshaled) { t.Errorf("Expected Marshal of NullRawValue to yield %x, got %x", NullBytes, marshaled) } unmarshaled := asn1.RawValue{} if _, err := Unmarshal(NullBytes, &unmarshaled); err != nil { t.Fatal(err) } unmarshaled.FullBytes = NullRawValue.FullBytes if len(unmarshaled.Bytes) == 0 { // DeepEqual considers a nil slice and an empty slice to be different. unmarshaled.Bytes = NullRawValue.Bytes } if !reflect.DeepEqual(NullRawValue, unmarshaled) { t.Errorf("Expected Unmarshal of NullBytes to yield %v, got %v", NullRawValue, unmarshaled) } } func TestExplicitTagRawValueStruct(t *testing.T) { type foo struct { A asn1.RawValue `asn1:"optional,explicit,tag:5"` B []byte `asn1:"optional,explicit,tag:6"` } before := foo{B: []byte{1, 2, 3}} derBytes, err := Marshal(before) if err != nil { t.Fatal(err) } var after foo if rest, err := Unmarshal(derBytes, &after); err != nil || len(rest) != 0 { t.Fatal(err) } got := fmt.Sprintf("%#v", after) want := fmt.Sprintf("%#v", before) if got != want { t.Errorf("got %s, want %s (DER: %x)", got, want, derBytes) } } func TestTaggedRawValue(t *testing.T) { type taggedRawValue struct { A asn1.RawValue `asn1:"tag:5"` } type untaggedRawValue struct { A asn1.RawValue } const isCompound = 0x20 const tag = 5 tests := []struct { shouldMatch bool derBytes []byte }{ {false, []byte{0x30, 3, asn1.TagInteger, 1, 1}}, {true, []byte{0x30, 3, (asn1.ClassContextSpecific << 6) | tag, 1, 1}}, {true, []byte{0x30, 3, (asn1.ClassContextSpecific << 6) | tag | isCompound, 1, 1}}, {false, []byte{0x30, 3, (asn1.ClassApplication << 6) | tag | isCompound, 1, 1}}, {false, []byte{0x30, 3, (asn1.ClassPrivate << 6) | tag | isCompound, 1, 1}}, } for i, test := range tests { var tagged taggedRawValue if _, err := Unmarshal(test.derBytes, &tagged); (err == nil) != test.shouldMatch { t.Errorf("#%d: unexpected result parsing %x: %s", i, test.derBytes, err) } // An untagged RawValue should accept anything. var untagged untaggedRawValue if _, err := Unmarshal(test.derBytes, &untagged); err != nil { t.Errorf("#%d: unexpected failure parsing %x with untagged RawValue: %s", i, test.derBytes, err) } } } var bmpStringTests = []struct { decoded string encodedHex string }{ {"", "0000"}, // Example from https://tools.ietf.org/html/rfc7292#appendix-B. {"Beavis", "0042006500610076006900730000"}, // Some characters from the "Letterlike Symbols Unicode block". {"\u2115 - Double-struck N", "21150020002d00200044006f00750062006c0065002d00730074007200750063006b0020004e0000"}, } func TestBMPString(t *testing.T) { for i, test := range bmpStringTests { encoded, err := hex.DecodeString(test.encodedHex) if err != nil { t.Fatalf("#%d: failed to decode from hex string", i) } decoded, err := parseBMPString(encoded) if err != nil { t.Errorf("#%d: decoding output gave an error: %s", i, err) continue } if decoded != test.decoded { t.Errorf("#%d: decoding output resulted in %q, but it should have been %q", i, decoded, test.decoded) continue } } } ber-1.1.0/ber_go1.8_test.go000066400000000000000000000002711364766032500153470ustar00rootroot00000000000000// +build !go1.9 package ber import "encoding/asn1" // Compatibility vars for ber_asn1_test.go var ( NullRawValue = asn1.RawValue{Tag: tagNull} NullBytes = []byte{tagNull, 0} ) ber-1.1.0/ber_go1.9_test.go000066400000000000000000000002521364766032500153470ustar00rootroot00000000000000// +build go1.9 package ber import "encoding/asn1" // Compatibility vars for ber_asn1_test.go var ( NullRawValue = asn1.NullRawValue NullBytes = asn1.NullBytes ) ber-1.1.0/ber_test.go000066400000000000000000000051431364766032500144360ustar00rootroot00000000000000package ber import ( "math" ) func init() { objectIdentifierTestData = append(objectIdentifierTestData, berObjectIdentifierTestData...) tagAndLengthData = berTagAndLengthData } // @init var berObjectIdentifierTestData = []objectIdentifierTest{ // large object identifier value, seen on some SNMP devices // See ber_64bit_test.go for none 32-bit compatible examples. { []byte{ 0x2b, 0x06, 0x01, 0x02, 0x01, 0x1f, 0x01, 0x01, 0x01, 0x01, 0x84, 0x88, 0x90, 0x80, 0x23}, true, []int{1, 3, 6, 1, 2, 1, 31, 1, 1, 1, 1, 1090781219}, }, } // berTagAndLengthData replaces the tagAndLengthData contents, this makes it easier to see which test has failed // as they are numbered var berTagAndLengthData = []tagAndLengthTest{ {[]byte{0x80, 0x01}, true, tagAndLength{2, 0, 1, false}}, {[]byte{0xa0, 0x01}, true, tagAndLength{2, 0, 1, true}}, {[]byte{0x02, 0x00}, true, tagAndLength{0, 2, 0, false}}, {[]byte{0xfe, 0x00}, true, tagAndLength{3, 30, 0, true}}, {[]byte{0x1f, 0x1f, 0x00}, true, tagAndLength{0, 31, 0, false}}, {[]byte{0x1f, 0x81, 0x00, 0x00}, true, tagAndLength{0, 128, 0, false}}, {[]byte{0x1f, 0x81, 0x80, 0x01, 0x00}, true, tagAndLength{0, 0x4001, 0, false}}, {[]byte{0x00, 0x81, 0x80}, true, tagAndLength{0, 0, 128, false}}, {[]byte{0x00, 0x82, 0x01, 0x00}, true, tagAndLength{0, 0, 256, false}}, {[]byte{0x00, 0x83, 0x01, 0x00}, false, tagAndLength{}}, {[]byte{0x1f, 0x85}, false, tagAndLength{}}, {[]byte{0x30, 0x80}, false, tagAndLength{}}, // Lengths up to the maximum size of an int should work. {[]byte{0xa0, 0x84, 0x7f, 0xff, 0xff, 0xff}, true, tagAndLength{2, 0, 0x7fffffff, true}}, // Lengths that would overflow an int should be rejected. {[]byte{0xa0, 0x84, 0x80, 0x00, 0x00, 0x00}, false, tagAndLength{}}, // Tag numbers which would overflow int32 are rejected. (The value below is 2^31.) {[]byte{0x1f, 0x88, 0x80, 0x80, 0x80, 0x00, 0x00}, false, tagAndLength{}}, // Tag numbers that fit in an int32 are valid. (The value below is 2^31 - 1.) {[]byte{0x1f, 0x87, 0xFF, 0xFF, 0xFF, 0x7F, 0x00}, true, tagAndLength{tag: math.MaxInt32}}, // Long tag number form may not be used for tags that fit in short form. {[]byte{0x1f, 0x1e, 0x00}, false, tagAndLength{}}, // Superfluous zeros in the length should be a accepted (different from DER). {[]byte{0xa0, 0x82, 0x00, 0xff}, true, tagAndLength{2, 0, 0xff, true}}, // Lengths that would overflow an int should be rejected. {[]byte{0xa0, 0x84, 0x88, 0x90, 0x80, 0x23}, false, tagAndLength{}}, // Long length form may be used for lengths that fit in short form (different from DER). {[]byte{0xa0, 0x81, 0x7f}, true, tagAndLength{2, 0, 0x7f, true}}, } ber-1.1.0/common.go000066400000000000000000000121231364766032500141130ustar00rootroot00000000000000// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ber import ( "reflect" "strconv" "strings" ) const ( tagBoolean = 1 tagInteger = 2 tagBitString = 3 tagOctetString = 4 tagNull = 5 tagOID = 6 tagEnum = 10 tagUTF8String = 12 tagSequence = 16 tagSet = 17 tagNumericString = 18 tagPrintableString = 19 tagT61String = 20 tagIA5String = 22 tagUTCTime = 23 tagGeneralizedTime = 24 tagGeneralString = 27 tagBMPString = 30 ) const ( classUniversal = 0 classApplication = 1 classContextSpecific = 2 classPrivate = 3 ) type tagAndLength struct { class, tag, length int isCompound bool } // ASN.1 has IMPLICIT and EXPLICIT tags, which can be translated as "instead // of" and "in addition to". When not specified, every primitive type has a // default tag in the UNIVERSAL class. // // For example: a BIT STRING is tagged [UNIVERSAL 3] by default (although ASN.1 // doesn't actually have a UNIVERSAL keyword). However, by saying [IMPLICIT // CONTEXT-SPECIFIC 42], that means that the tag is replaced by another. // // On the other hand, if it said [EXPLICIT CONTEXT-SPECIFIC 10], then an // /additional/ tag would wrap the default tag. This explicit tag will have the // compound flag set. // // (This is used in order to remove ambiguity with optional elements.) // // You can layer EXPLICIT and IMPLICIT tags to an arbitrary depth, however we // don't support that here. We support a single layer of EXPLICIT or IMPLICIT // tagging with tag strings on the fields of a structure. // fieldParameters is the parsed representation of tag string from a structure field. type fieldParameters struct { optional bool // true iff the field is OPTIONAL explicit bool // true iff an EXPLICIT tag is in use. application bool // true iff an APPLICATION tag is in use. private bool // true iff a PRIVATE tag is in use. defaultValue *int64 // a default value for INTEGER typed fields (maybe nil). tag *int // the EXPLICIT or IMPLICIT tag (maybe nil). stringType int // the string tag to use when marshaling. timeType int // the time tag to use when marshaling. set bool // true iff this should be encoded as a SET omitEmpty bool // true iff this should be omitted if empty when marshaling. // Invariants: // if explicit is set, tag is non-nil. } // Given a tag string with the format specified in the package comment, // parseFieldParameters will parse it into a fieldParameters structure, // ignoring unknown parts of the string. func parseFieldParameters(str string) (ret fieldParameters) { for _, part := range strings.Split(str, ",") { switch { case part == "optional": ret.optional = true case part == "explicit": ret.explicit = true if ret.tag == nil { ret.tag = new(int) } case part == "generalized": ret.timeType = tagGeneralizedTime case part == "utc": ret.timeType = tagUTCTime case part == "ia5": ret.stringType = tagIA5String case part == "printable": ret.stringType = tagPrintableString case part == "numeric": ret.stringType = tagNumericString case part == "utf8": ret.stringType = tagUTF8String case strings.HasPrefix(part, "default:"): i, err := strconv.ParseInt(part[8:], 10, 64) if err == nil { ret.defaultValue = new(int64) *ret.defaultValue = i } case strings.HasPrefix(part, "tag:"): i, err := strconv.Atoi(part[4:]) if err == nil { ret.tag = new(int) *ret.tag = i } case part == "set": ret.set = true case part == "application": ret.application = true if ret.tag == nil { ret.tag = new(int) } case part == "private": ret.private = true if ret.tag == nil { ret.tag = new(int) } case part == "omitempty": ret.omitEmpty = true } } return } // Given a reflected Go type, getUniversalType returns the default tag number // and expected compound flag. func getUniversalType(t reflect.Type) (matchAny bool, tagNumber int, isCompound, ok bool) { switch t { case rawValueType: return true, -1, false, true case objectIdentifierType: return false, tagOID, false, true case bitStringType: return false, tagBitString, false, true case timeType: return false, tagUTCTime, false, true case enumeratedType: return false, tagEnum, false, true case bigIntType: return false, tagInteger, false, true } switch t.Kind() { case reflect.Bool: return false, tagBoolean, false, true case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return false, tagInteger, false, true case reflect.Struct: return false, tagSequence, true, true case reflect.Slice: if t.Elem().Kind() == reflect.Uint8 { return false, tagOctetString, false, true } if strings.HasSuffix(t.Name(), "SET") { return false, tagSet, true, true } return false, tagSequence, true, true case reflect.String: return false, tagPrintableString, false, true } return false, 0, false, false } ber-1.1.0/go.mod000066400000000000000000000000541364766032500134020ustar00rootroot00000000000000module github.com/geoffgarside/ber go 1.13 ber-1.1.0/marshal.go000066400000000000000000000002341364766032500142520ustar00rootroot00000000000000package ber import "encoding/asn1" // Marshal wraps the asn1.Marshal function func Marshal(val interface{}) ([]byte, error) { return asn1.Marshal(val) } ber-1.1.0/marshal_test.go000066400000000000000000000016651364766032500153220ustar00rootroot00000000000000package ber import ( "bytes" "encoding/asn1" "encoding/hex" "testing" ) type marshalTest struct { in interface{} out string // hex encoded } var marshalTests = []marshalTest{ {asn1.ObjectIdentifier([]int{1, 2, 3, 4}), "06032a0304"}, {asn1.ObjectIdentifier([]int{1, 2, 840, 133549, 1, 1, 5}), "06092a864888932d010105"}, {asn1.ObjectIdentifier([]int{2, 100, 3}), "0603813403"}, // Ensure large OID suboids are marshalled correctly // See ber_64bit_test.go for none 32-bit compatible examples. { asn1.ObjectIdentifier([]int{1, 3, 6, 1, 2, 1, 31, 1, 1, 1, 1, 1090781219}), "060f2b060102011f010101018488908023", }, } func TestMarshal(t *testing.T) { for i, test := range marshalTests { data, err := Marshal(test.in) if err != nil { t.Errorf("#%d failed: %s", i, err) } out, _ := hex.DecodeString(test.out) if !bytes.Equal(out, data) { t.Errorf("#%d got: %x want %x\n\t%q\n\t%q", i, data, out, data, out) } } }