bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/snmp/asn1/asn1.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package asn1 implements parsing of DER-encoded ASN.1 data structures,
     6  // as defined in ITU-T Rec X.690.
     7  //
     8  // See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,''
     9  // http://luca.ntop.org/Teaching/Appunti/asn1.html.
    10  package asn1
    11  
    12  // ASN.1 is a syntax for specifying abstract objects and BER, DER, PER, XER etc
    13  // are different encoding formats for those objects. Here, we'll be dealing
    14  // with DER, the Distinguished Encoding Rules. DER is used in X.509 because
    15  // it's fast to parse and, unlike BER, has a unique encoding for every object.
    16  // When calculating hashes over objects, it's important that the resulting
    17  // bytes be the same at both ends and DER removes this margin of error.
    18  //
    19  // ASN.1 is very complex and this package doesn't attempt to implement
    20  // everything by any means.
    21  //
    22  // This package relaxes some of the restrictions of DER in order to facilitate interacting with BER systems.
    23  import (
    24  	"errors"
    25  	"fmt"
    26  	"math/big"
    27  	"reflect"
    28  	"strconv"
    29  	"time"
    30  	"unicode/utf8"
    31  )
    32  
    33  // A StructuralError suggests that the ASN.1 data is valid, but the Go type
    34  // which is receiving it doesn't match.
    35  type StructuralError struct {
    36  	Msg string
    37  }
    38  
    39  func (e StructuralError) Error() string { return "asn1: structure error: " + e.Msg }
    40  
    41  // A SyntaxError suggests that the ASN.1 data is invalid.
    42  type SyntaxError struct {
    43  	Msg string
    44  }
    45  
    46  func (e SyntaxError) Error() string { return "asn1: syntax error: " + e.Msg }
    47  
    48  // We start by dealing with each of the primitive types in turn.
    49  
    50  // BOOLEAN
    51  
    52  func parseBool(bytes []byte) (ret bool, err error) {
    53  	if len(bytes) != 1 {
    54  		err = SyntaxError{"invalid boolean"}
    55  		return
    56  	}
    57  
    58  	// DER demands that "If the encoding represents the boolean value TRUE,
    59  	// its single contents octet shall have all eight bits set to one."
    60  	// Thus only 0 and 255 are valid encoded values.
    61  	switch bytes[0] {
    62  	case 0:
    63  		ret = false
    64  	case 0xff:
    65  		ret = true
    66  	default:
    67  		err = SyntaxError{"invalid boolean"}
    68  	}
    69  
    70  	return
    71  }
    72  
    73  // INTEGER
    74  
    75  // parseInt64 treats the given bytes as a big-endian, signed integer and
    76  // returns the result.
    77  func parseInt64(bytes []byte) (ret int64, err error) {
    78  	if len(bytes) > 8 {
    79  		// We'll overflow an int64 in this case.
    80  		err = StructuralError{"integer too large"}
    81  		return
    82  	}
    83  	for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
    84  		ret <<= 8
    85  		ret |= int64(bytes[bytesRead])
    86  	}
    87  
    88  	// Shift up and down in order to sign extend the result.
    89  	ret <<= 64 - uint8(len(bytes))*8
    90  	ret >>= 64 - uint8(len(bytes))*8
    91  	return
    92  }
    93  
    94  // parseInt treats the given bytes as a big-endian, signed integer and returns
    95  // the result.
    96  func parseInt32(bytes []byte) (int32, error) {
    97  	ret64, err := parseInt64(bytes)
    98  	if err != nil {
    99  		return 0, err
   100  	}
   101  	if ret64 != int64(int32(ret64)) {
   102  		return 0, StructuralError{"integer too large"}
   103  	}
   104  	return int32(ret64), nil
   105  }
   106  
   107  var bigOne = big.NewInt(1)
   108  
   109  // parseBigInt treats the given bytes as a big-endian, signed integer and returns
   110  // the result.
   111  func parseBigInt(bytes []byte) *big.Int {
   112  	ret := new(big.Int)
   113  	if len(bytes) > 0 && bytes[0]&0x80 == 0x80 {
   114  		// This is a negative number.
   115  		notBytes := make([]byte, len(bytes))
   116  		for i := range notBytes {
   117  			notBytes[i] = ^bytes[i]
   118  		}
   119  		ret.SetBytes(notBytes)
   120  		ret.Add(ret, bigOne)
   121  		ret.Neg(ret)
   122  		return ret
   123  	}
   124  	ret.SetBytes(bytes)
   125  	return ret
   126  }
   127  
   128  // BIT STRING
   129  
   130  // BitString is the structure to use when you want an ASN.1 BIT STRING type. A
   131  // bit string is padded up to the nearest byte in memory and the number of
   132  // valid bits is recorded. Padding bits will be zero.
   133  type BitString struct {
   134  	Bytes     []byte // bits packed into bytes.
   135  	BitLength int    // length in bits.
   136  }
   137  
   138  // At returns the bit at the given index. If the index is out of range it
   139  // returns false.
   140  func (b BitString) At(i int) int {
   141  	if i < 0 || i >= b.BitLength {
   142  		return 0
   143  	}
   144  	x := i / 8
   145  	y := 7 - uint(i%8)
   146  	return int(b.Bytes[x]>>y) & 1
   147  }
   148  
   149  // RightAlign returns a slice where the padding bits are at the beginning. The
   150  // slice may share memory with the BitString.
   151  func (b BitString) RightAlign() []byte {
   152  	shift := uint(8 - (b.BitLength % 8))
   153  	if shift == 8 || len(b.Bytes) == 0 {
   154  		return b.Bytes
   155  	}
   156  
   157  	a := make([]byte, len(b.Bytes))
   158  	a[0] = b.Bytes[0] >> shift
   159  	for i := 1; i < len(b.Bytes); i++ {
   160  		a[i] = b.Bytes[i-1] << (8 - shift)
   161  		a[i] |= b.Bytes[i] >> shift
   162  	}
   163  
   164  	return a
   165  }
   166  
   167  // parseBitString parses an ASN.1 bit string from the given byte slice and returns it.
   168  func parseBitString(bytes []byte) (ret BitString, err error) {
   169  	if len(bytes) == 0 {
   170  		err = SyntaxError{"zero length BIT STRING"}
   171  		return
   172  	}
   173  	paddingBits := int(bytes[0])
   174  	if paddingBits > 7 ||
   175  		len(bytes) == 1 && paddingBits > 0 ||
   176  		bytes[len(bytes)-1]&((1<<bytes[0])-1) != 0 {
   177  		err = SyntaxError{"invalid padding bits in BIT STRING"}
   178  		return
   179  	}
   180  	ret.BitLength = (len(bytes)-1)*8 - paddingBits
   181  	ret.Bytes = bytes[1:]
   182  	return
   183  }
   184  
   185  // OBJECT IDENTIFIER
   186  
   187  // An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
   188  type ObjectIdentifier []int
   189  
   190  // Equal reports whether oi and other represent the same identifier.
   191  func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {
   192  	if len(oi) != len(other) {
   193  		return false
   194  	}
   195  	for i := 0; i < len(oi); i++ {
   196  		if oi[i] != other[i] {
   197  			return false
   198  		}
   199  	}
   200  
   201  	return true
   202  }
   203  
   204  func (oi ObjectIdentifier) String() string {
   205  	var s string
   206  
   207  	for i, v := range oi {
   208  		if i > 0 {
   209  			s += "."
   210  		}
   211  		s += strconv.Itoa(v)
   212  	}
   213  
   214  	return s
   215  }
   216  
   217  // parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
   218  // returns it. An object identifier is a sequence of variable length integers
   219  // that are assigned in a hierarchy.
   220  func parseObjectIdentifier(bytes []byte) (s []int, err error) {
   221  	if len(bytes) == 0 {
   222  		err = SyntaxError{"zero length OBJECT IDENTIFIER"}
   223  		return
   224  	}
   225  
   226  	// In the worst case, we get two elements from the first byte (which is
   227  	// encoded differently) and then every varint is a single byte long.
   228  	s = make([]int, len(bytes)+1)
   229  
   230  	// The first varint is 40*value1 + value2:
   231  	// According to this packing, value1 can take the values 0, 1 and 2 only.
   232  	// When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
   233  	// then there are no restrictions on value2.
   234  	v, offset, err := parseBase128Int(bytes, 0)
   235  	if err != nil {
   236  		return
   237  	}
   238  	if v < 80 {
   239  		s[0] = v / 40
   240  		s[1] = v % 40
   241  	} else {
   242  		s[0] = 2
   243  		s[1] = v - 80
   244  	}
   245  
   246  	i := 2
   247  	for ; offset < len(bytes); i++ {
   248  		v, offset, err = parseBase128Int(bytes, offset)
   249  		if err != nil {
   250  			return
   251  		}
   252  		s[i] = v
   253  	}
   254  	s = s[0:i]
   255  	return
   256  }
   257  
   258  // ENUMERATED
   259  
   260  // An Enumerated is represented as a plain int.
   261  type Enumerated int
   262  
   263  // FLAG
   264  
   265  // A Flag accepts any data and is set to true if present.
   266  type Flag bool
   267  
   268  // parseBase128Int parses a base-128 encoded int from the given offset in the
   269  // given byte slice. It returns the value and the new offset.
   270  func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
   271  	offset = initOffset
   272  	for shifted := 0; offset < len(bytes); shifted++ {
   273  		if shifted > 4 {
   274  			err = StructuralError{"base 128 integer too large"}
   275  			return
   276  		}
   277  		ret <<= 7
   278  		b := bytes[offset]
   279  		ret |= int(b & 0x7f)
   280  		offset++
   281  		if b&0x80 == 0 {
   282  			return
   283  		}
   284  	}
   285  	err = SyntaxError{"truncated base 128 integer"}
   286  	return
   287  }
   288  
   289  // UTCTime
   290  
   291  func parseUTCTime(bytes []byte) (ret time.Time, err error) {
   292  	s := string(bytes)
   293  
   294  	formatStr := "0601021504Z0700"
   295  	ret, err = time.Parse(formatStr, s)
   296  	if err != nil {
   297  		formatStr = "060102150405Z0700"
   298  		ret, err = time.Parse(formatStr, s)
   299  	}
   300  	if err != nil {
   301  		return
   302  	}
   303  
   304  	if serialized := ret.Format(formatStr); serialized != s {
   305  		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)
   306  		return
   307  	}
   308  
   309  	if ret.Year() >= 2050 {
   310  		// UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
   311  		ret = ret.AddDate(-100, 0, 0)
   312  	}
   313  
   314  	return
   315  }
   316  
   317  // parseGeneralizedTime parses the GeneralizedTime from the given byte slice
   318  // and returns the resulting time.
   319  func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) {
   320  	const formatStr = "20060102150405Z0700"
   321  	s := string(bytes)
   322  
   323  	if ret, err = time.Parse(formatStr, s); err != nil {
   324  		return
   325  	}
   326  
   327  	if serialized := ret.Format(formatStr); serialized != s {
   328  		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)
   329  	}
   330  
   331  	return
   332  }
   333  
   334  // PrintableString
   335  
   336  // parsePrintableString parses a ASN.1 PrintableString from the given byte
   337  // array and returns it.
   338  func parsePrintableString(bytes []byte) (ret string, err error) {
   339  	for _, b := range bytes {
   340  		if !isPrintable(b) {
   341  			err = SyntaxError{"PrintableString contains invalid character"}
   342  			return
   343  		}
   344  	}
   345  	ret = string(bytes)
   346  	return
   347  }
   348  
   349  // isPrintable reports whether the given b is in the ASN.1 PrintableString set.
   350  func isPrintable(b byte) bool {
   351  	return 'a' <= b && b <= 'z' ||
   352  		'A' <= b && b <= 'Z' ||
   353  		'0' <= b && b <= '9' ||
   354  		'\'' <= b && b <= ')' ||
   355  		'+' <= b && b <= '/' ||
   356  		b == ' ' ||
   357  		b == ':' ||
   358  		b == '=' ||
   359  		b == '?' ||
   360  		// This is technically not allowed in a PrintableString.
   361  		// However, x509 certificates with wildcard strings don't
   362  		// always use the correct string type so we permit it.
   363  		b == '*'
   364  }
   365  
   366  // IA5String
   367  
   368  // parseIA5String parses a ASN.1 IA5String (ASCII string) from the given
   369  // byte slice and returns it.
   370  func parseIA5String(bytes []byte) (ret string, err error) {
   371  	for _, b := range bytes {
   372  		if b >= 0x80 {
   373  			err = SyntaxError{"IA5String contains invalid character"}
   374  			return
   375  		}
   376  	}
   377  	ret = string(bytes)
   378  	return
   379  }
   380  
   381  // T61String
   382  
   383  // parseT61String parses a ASN.1 T61String (8-bit clean string) from the given
   384  // byte slice and returns it.
   385  func parseT61String(bytes []byte) (ret string, err error) {
   386  	return string(bytes), nil
   387  }
   388  
   389  // UTF8String
   390  
   391  // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
   392  // array and returns it.
   393  func parseUTF8String(bytes []byte) (ret string, err error) {
   394  	if !utf8.Valid(bytes) {
   395  		return "", errors.New("asn1: invalid UTF-8 string")
   396  	}
   397  	return string(bytes), nil
   398  }
   399  
   400  // A RawValue represents an undecoded ASN.1 object.
   401  type RawValue struct {
   402  	Class, Tag int
   403  	IsCompound bool
   404  	Bytes      []byte
   405  	FullBytes  []byte // includes the tag and length
   406  }
   407  
   408  // RawContent is used to signal that the undecoded, DER data needs to be
   409  // preserved for a struct. To use it, the first field of the struct must have
   410  // this type. It's an error for any of the other fields to have this type.
   411  type RawContent []byte
   412  
   413  // Tagging
   414  
   415  // parseTagAndLength parses an ASN.1 tag and length pair from the given offset
   416  // into a byte slice. It returns the parsed data and the new offset. SET and
   417  // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
   418  // don't distinguish between ordered and unordered objects in this code.
   419  func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) {
   420  	offset = initOffset
   421  	// parseTagAndLength should not be called without at least a single
   422  	// byte to read. Thus this check is for robustness:
   423  	if offset >= len(bytes) {
   424  		err = errors.New("asn1: internal error in parseTagAndLength")
   425  		return
   426  	}
   427  	b := bytes[offset]
   428  	offset++
   429  	ret.class = int(b >> 6)
   430  	ret.isCompound = b&0x20 == 0x20
   431  	ret.tag = int(b & 0x1f)
   432  
   433  	// If the bottom five bits are set, then the tag number is actually base 128
   434  	// encoded afterwards
   435  	if ret.tag == 0x1f {
   436  		ret.tag, offset, err = parseBase128Int(bytes, offset)
   437  		if err != nil {
   438  			return
   439  		}
   440  	}
   441  	if offset >= len(bytes) {
   442  		err = SyntaxError{"truncated tag or length"}
   443  		return
   444  	}
   445  	b = bytes[offset]
   446  	offset++
   447  	if b&0x80 == 0 {
   448  		// The length is encoded in the bottom 7 bits.
   449  		ret.length = int(b & 0x7f)
   450  	} else {
   451  		// Bottom 7 bits give the number of length bytes to follow.
   452  		numBytes := int(b & 0x7f)
   453  		if numBytes == 0 {
   454  			err = SyntaxError{"indefinite length found (not DER)"}
   455  			return
   456  		}
   457  		ret.length = 0
   458  		for i := 0; i < numBytes; i++ {
   459  			if offset >= len(bytes) {
   460  				err = SyntaxError{"truncated tag or length"}
   461  				return
   462  			}
   463  			b = bytes[offset]
   464  			offset++
   465  			if ret.length >= 1<<23 {
   466  				// We can't shift ret.length up without
   467  				// overflowing.
   468  				err = StructuralError{"length too large"}
   469  				return
   470  			}
   471  			ret.length <<= 8
   472  			ret.length |= int(b)
   473  		}
   474  		if ret.length == 0 {
   475  			err = StructuralError{"zero length"}
   476  			return
   477  		}
   478  	}
   479  
   480  	return
   481  }
   482  
   483  // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
   484  // a number of ASN.1 values from the given byte slice and returns them as a
   485  // slice of Go values of the given type.
   486  func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) {
   487  	expectedTag, compoundType, ok := getUniversalType(elemType)
   488  	if !ok {
   489  		err = StructuralError{"unknown Go type for slice"}
   490  		return
   491  	}
   492  
   493  	// First we iterate over the input and count the number of elements,
   494  	// checking that the types are correct in each case.
   495  	numElements := 0
   496  	for offset := 0; offset < len(bytes); {
   497  		var t tagAndLength
   498  		t, offset, err = parseTagAndLength(bytes, offset)
   499  		if err != nil {
   500  			return
   501  		}
   502  		switch t.tag {
   503  		case tagIA5String, tagGeneralString, tagT61String, tagUTF8String:
   504  			// We pretend that various other string types are
   505  			// PRINTABLE STRINGs so that a sequence of them can be
   506  			// parsed into a []string.
   507  			t.tag = tagPrintableString
   508  		case tagGeneralizedTime, tagUTCTime:
   509  			// Likewise, both time types are treated the same.
   510  			t.tag = tagUTCTime
   511  		}
   512  
   513  		if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag {
   514  			err = StructuralError{"sequence tag mismatch"}
   515  			return
   516  		}
   517  		if invalidLength(offset, t.length, len(bytes)) {
   518  			err = SyntaxError{"truncated sequence"}
   519  			return
   520  		}
   521  		offset += t.length
   522  		numElements++
   523  	}
   524  	ret = reflect.MakeSlice(sliceType, numElements, numElements)
   525  	params := fieldParameters{}
   526  	offset := 0
   527  	for i := 0; i < numElements; i++ {
   528  		offset, err = parseField(ret.Index(i), bytes, offset, params)
   529  		if err != nil {
   530  			return
   531  		}
   532  	}
   533  	return
   534  }
   535  
   536  var (
   537  	bitStringType        = reflect.TypeOf(BitString{})
   538  	objectIdentifierType = reflect.TypeOf(ObjectIdentifier{})
   539  	enumeratedType       = reflect.TypeOf(Enumerated(0))
   540  	flagType             = reflect.TypeOf(Flag(false))
   541  	timeType             = reflect.TypeOf(time.Time{})
   542  	rawValueType         = reflect.TypeOf(RawValue{})
   543  	rawContentsType      = reflect.TypeOf(RawContent(nil))
   544  	bigIntType           = reflect.TypeOf(new(big.Int))
   545  )
   546  
   547  // invalidLength returns true iff offset + length > sliceLength, or if the
   548  // addition would overflow.
   549  func invalidLength(offset, length, sliceLength int) bool {
   550  	return offset+length < offset || offset+length > sliceLength
   551  }
   552  
   553  // parseField is the main parsing function. Given a byte slice and an offset
   554  // into the array, it will try to parse a suitable ASN.1 value out and store it
   555  // in the given Value.
   556  func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) {
   557  	offset = initOffset
   558  	fieldType := v.Type()
   559  
   560  	// If we have run out of data, it may be that there are optional elements at the end.
   561  	if offset == len(bytes) {
   562  		if !setDefaultValue(v, params) {
   563  			err = SyntaxError{"sequence truncated"}
   564  		}
   565  		return
   566  	}
   567  
   568  	// Deal with raw values.
   569  	if fieldType == rawValueType {
   570  		var t tagAndLength
   571  		t, offset, err = parseTagAndLength(bytes, offset)
   572  		if err != nil {
   573  			return
   574  		}
   575  		if invalidLength(offset, t.length, len(bytes)) {
   576  			err = SyntaxError{"data truncated"}
   577  			return
   578  		}
   579  		result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]}
   580  		offset += t.length
   581  		v.Set(reflect.ValueOf(result))
   582  		return
   583  	}
   584  
   585  	// Deal with the ANY type.
   586  	if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 {
   587  		var t tagAndLength
   588  		t, offset, err = parseTagAndLength(bytes, offset)
   589  		if err != nil {
   590  			return
   591  		}
   592  		if invalidLength(offset, t.length, len(bytes)) {
   593  			err = SyntaxError{"data truncated"}
   594  			return
   595  		}
   596  		var result interface{}
   597  		if !t.isCompound && t.class == classUniversal {
   598  			innerBytes := bytes[offset : offset+t.length]
   599  			switch t.tag {
   600  			case tagPrintableString:
   601  				result, err = parsePrintableString(innerBytes)
   602  			case tagIA5String:
   603  				result, err = parseIA5String(innerBytes)
   604  			case tagT61String:
   605  				result, err = parseT61String(innerBytes)
   606  			case tagUTF8String:
   607  				result, err = parseUTF8String(innerBytes)
   608  			case tagInteger:
   609  				result, err = parseInt64(innerBytes)
   610  			case tagBitString:
   611  				result, err = parseBitString(innerBytes)
   612  			case tagOID:
   613  				result, err = parseObjectIdentifier(innerBytes)
   614  			case tagUTCTime:
   615  				result, err = parseUTCTime(innerBytes)
   616  			case tagGeneralizedTime:
   617  				result, err = parseGeneralizedTime(innerBytes)
   618  			case tagOctetString:
   619  				result = innerBytes
   620  			default:
   621  				// If we don't know how to handle the type, we just leave Value as nil.
   622  			}
   623  		}
   624  		offset += t.length
   625  		if err != nil {
   626  			return
   627  		}
   628  		if result != nil {
   629  			v.Set(reflect.ValueOf(result))
   630  		}
   631  		return
   632  	}
   633  	universalTag, compoundType, ok1 := getUniversalType(fieldType)
   634  	if !ok1 {
   635  		err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)}
   636  		return
   637  	}
   638  
   639  	t, offset, err := parseTagAndLength(bytes, offset)
   640  	if err != nil {
   641  		return
   642  	}
   643  	if params.explicit {
   644  		expectedClass := classContextSpecific
   645  		if params.application {
   646  			expectedClass = classApplication
   647  		}
   648  		if offset == len(bytes) {
   649  			err = StructuralError{"explicit tag has no child"}
   650  			return
   651  		}
   652  		if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) {
   653  			if t.length > 0 {
   654  				t, offset, err = parseTagAndLength(bytes, offset)
   655  				if err != nil {
   656  					return
   657  				}
   658  			} else {
   659  				if fieldType != flagType {
   660  					err = StructuralError{"zero length explicit tag was not an asn1.Flag"}
   661  					return
   662  				}
   663  				v.SetBool(true)
   664  				return
   665  			}
   666  		} else {
   667  			// The tags didn't match, it might be an optional element.
   668  			ok := setDefaultValue(v, params)
   669  			if ok {
   670  				offset = initOffset
   671  			} else {
   672  				err = StructuralError{"explicitly tagged member didn't match"}
   673  			}
   674  			return
   675  		}
   676  	}
   677  
   678  	// Special case for strings: all the ASN.1 string types map to the Go
   679  	// type string. getUniversalType returns the tag for PrintableString
   680  	// when it sees a string, so if we see a different string type on the
   681  	// wire, we change the universal type to match.
   682  	if universalTag == tagPrintableString {
   683  		if t.class == classUniversal {
   684  			switch t.tag {
   685  			case tagIA5String, tagGeneralString, tagT61String, tagUTF8String:
   686  				universalTag = t.tag
   687  			}
   688  		} else if params.stringType != 0 {
   689  			universalTag = params.stringType
   690  		}
   691  	}
   692  
   693  	// Special case for time: UTCTime and GeneralizedTime both map to the
   694  	// Go type time.Time.
   695  	if universalTag == tagUTCTime && t.tag == tagGeneralizedTime && t.class == classUniversal {
   696  		universalTag = tagGeneralizedTime
   697  	}
   698  
   699  	if params.set {
   700  		universalTag = tagSet
   701  	}
   702  
   703  	expectedClass := classUniversal
   704  	expectedTag := universalTag
   705  
   706  	if !params.explicit && params.tag != nil {
   707  		expectedClass = classContextSpecific
   708  		expectedTag = *params.tag
   709  	}
   710  
   711  	if !params.explicit && params.application && params.tag != nil {
   712  		expectedClass = classApplication
   713  		expectedTag = *params.tag
   714  	}
   715  
   716  	// We have unwrapped any explicit tagging at this point.
   717  	if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType {
   718  		// Tags don't match. Again, it could be an optional element.
   719  		ok := setDefaultValue(v, params)
   720  		if ok {
   721  			offset = initOffset
   722  		} else {
   723  			err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)}
   724  		}
   725  		return
   726  	}
   727  	if invalidLength(offset, t.length, len(bytes)) {
   728  		err = SyntaxError{"data truncated"}
   729  		return
   730  	}
   731  	innerBytes := bytes[offset : offset+t.length]
   732  	offset += t.length
   733  
   734  	// We deal with the structures defined in this package first.
   735  	switch fieldType {
   736  	case objectIdentifierType:
   737  		newSlice, err1 := parseObjectIdentifier(innerBytes)
   738  		v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice)))
   739  		if err1 == nil {
   740  			reflect.Copy(v, reflect.ValueOf(newSlice))
   741  		}
   742  		err = err1
   743  		return
   744  	case bitStringType:
   745  		bs, err1 := parseBitString(innerBytes)
   746  		if err1 == nil {
   747  			v.Set(reflect.ValueOf(bs))
   748  		}
   749  		err = err1
   750  		return
   751  	case timeType:
   752  		var time time.Time
   753  		var err1 error
   754  		if universalTag == tagUTCTime {
   755  			time, err1 = parseUTCTime(innerBytes)
   756  		} else {
   757  			time, err1 = parseGeneralizedTime(innerBytes)
   758  		}
   759  		if err1 == nil {
   760  			v.Set(reflect.ValueOf(time))
   761  		}
   762  		err = err1
   763  		return
   764  	case enumeratedType:
   765  		parsedInt, err1 := parseInt32(innerBytes)
   766  		if err1 == nil {
   767  			v.SetInt(int64(parsedInt))
   768  		}
   769  		err = err1
   770  		return
   771  	case flagType:
   772  		v.SetBool(true)
   773  		return
   774  	case bigIntType:
   775  		parsedInt := parseBigInt(innerBytes)
   776  		v.Set(reflect.ValueOf(parsedInt))
   777  		return
   778  	}
   779  	switch val := v; val.Kind() {
   780  	case reflect.Bool:
   781  		parsedBool, err1 := parseBool(innerBytes)
   782  		if err1 == nil {
   783  			val.SetBool(parsedBool)
   784  		}
   785  		err = err1
   786  		return
   787  	case reflect.Int, reflect.Int32, reflect.Int64:
   788  		if val.Type().Size() == 4 {
   789  			parsedInt, err1 := parseInt32(innerBytes)
   790  			if err1 == nil {
   791  				val.SetInt(int64(parsedInt))
   792  			}
   793  			err = err1
   794  		} else {
   795  			parsedInt, err1 := parseInt64(innerBytes)
   796  			if err1 == nil {
   797  				val.SetInt(parsedInt)
   798  			}
   799  			err = err1
   800  		}
   801  		return
   802  	// TODO(dfc) Add support for the remaining integer types
   803  	case reflect.Struct:
   804  		structType := fieldType
   805  
   806  		if structType.NumField() > 0 &&
   807  			structType.Field(0).Type == rawContentsType {
   808  			bytes := bytes[initOffset:offset]
   809  			val.Field(0).Set(reflect.ValueOf(RawContent(bytes)))
   810  		}
   811  
   812  		innerOffset := 0
   813  		for i := 0; i < structType.NumField(); i++ {
   814  			field := structType.Field(i)
   815  			if i == 0 && field.Type == rawContentsType {
   816  				continue
   817  			}
   818  			innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1")))
   819  			if err != nil {
   820  				return
   821  			}
   822  		}
   823  		// We allow extra bytes at the end of the SEQUENCE because
   824  		// adding elements to the end has been used in X.509 as the
   825  		// version numbers have increased.
   826  		return
   827  	case reflect.Slice:
   828  		sliceType := fieldType
   829  		if sliceType.Elem().Kind() == reflect.Uint8 {
   830  			val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes)))
   831  			reflect.Copy(val, reflect.ValueOf(innerBytes))
   832  			return
   833  		}
   834  		newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem())
   835  		if err1 == nil {
   836  			val.Set(newSlice)
   837  		}
   838  		err = err1
   839  		return
   840  	case reflect.String:
   841  		var v string
   842  		switch universalTag {
   843  		case tagPrintableString:
   844  			v, err = parsePrintableString(innerBytes)
   845  		case tagIA5String:
   846  			v, err = parseIA5String(innerBytes)
   847  		case tagT61String:
   848  			v, err = parseT61String(innerBytes)
   849  		case tagUTF8String:
   850  			v, err = parseUTF8String(innerBytes)
   851  		case tagGeneralString:
   852  			// GeneralString is specified in ISO-2022/ECMA-35,
   853  			// A brief review suggests that it includes structures
   854  			// that allow the encoding to change midstring and
   855  			// such. We give up and pass it as an 8-bit string.
   856  			v, err = parseT61String(innerBytes)
   857  		default:
   858  			err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)}
   859  		}
   860  		if err == nil {
   861  			val.SetString(v)
   862  		}
   863  		return
   864  	}
   865  	err = StructuralError{"unsupported: " + v.Type().String()}
   866  	return
   867  }
   868  
   869  // canHaveDefaultValue reports whether k is a Kind that we will set a default
   870  // value for. (A signed integer, essentially.)
   871  func canHaveDefaultValue(k reflect.Kind) bool {
   872  	switch k {
   873  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   874  		return true
   875  	}
   876  
   877  	return false
   878  }
   879  
   880  // setDefaultValue is used to install a default value, from a tag string, into
   881  // a Value. It is successful if the field was optional, even if a default value
   882  // wasn't provided or it failed to install it into the Value.
   883  func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
   884  	if !params.optional {
   885  		return
   886  	}
   887  	ok = true
   888  	if params.defaultValue == nil {
   889  		return
   890  	}
   891  	if canHaveDefaultValue(v.Kind()) {
   892  		v.SetInt(*params.defaultValue)
   893  	}
   894  	return
   895  }
   896  
   897  // Unmarshal parses the DER-encoded ASN.1 data structure b
   898  // and uses the reflect package to fill in an arbitrary value pointed at by val.
   899  // Because Unmarshal uses the reflect package, the structs
   900  // being written to must use upper case field names.
   901  //
   902  // An ASN.1 INTEGER can be written to an int, int32, int64,
   903  // or *big.Int (from the math/big package).
   904  // If the encoded value does not fit in the Go type,
   905  // Unmarshal returns a parse error.
   906  //
   907  // An ASN.1 BIT STRING can be written to a BitString.
   908  //
   909  // An ASN.1 OCTET STRING can be written to a []byte.
   910  //
   911  // An ASN.1 OBJECT IDENTIFIER can be written to an
   912  // ObjectIdentifier.
   913  //
   914  // An ASN.1 ENUMERATED can be written to an Enumerated.
   915  //
   916  // An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.
   917  //
   918  // An ASN.1 PrintableString or IA5String can be written to a string.
   919  //
   920  // Any of the above ASN.1 values can be written to an interface{}.
   921  // The value stored in the interface has the corresponding Go type.
   922  // For integers, that type is int64.
   923  //
   924  // An ASN.1 SEQUENCE OF x or SET OF x can be written
   925  // to a slice if an x can be written to the slice's element type.
   926  //
   927  // An ASN.1 SEQUENCE or SET can be written to a struct
   928  // if each of the elements in the sequence can be
   929  // written to the corresponding element in the struct.
   930  //
   931  // The following tags on struct fields have special meaning to Unmarshal:
   932  //
   933  //	application	specifies that a APPLICATION tag is used
   934  //	default:x	sets the default value for optional integer fields
   935  //	explicit	specifies that an additional, explicit tag wraps the implicit one
   936  //	optional	marks the field as ASN.1 OPTIONAL
   937  //	set		causes a SET, rather than a SEQUENCE type to be expected
   938  //	tag:x		specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
   939  //
   940  // If the type of the first field of a structure is RawContent then the raw
   941  // ASN1 contents of the struct will be stored in it.
   942  //
   943  // If the type name of a slice element ends with "SET" then it's treated as if
   944  // the "set" tag was set on it. This can be used with nested slices where a
   945  // struct tag cannot be given.
   946  //
   947  // Other ASN.1 types are not supported; if it encounters them,
   948  // Unmarshal returns a parse error.
   949  func Unmarshal(b []byte, val interface{}) (rest []byte, err error) {
   950  	return UnmarshalWithParams(b, val, "")
   951  }
   952  
   953  // UnmarshalWithParams allows field parameters to be specified for the
   954  // top-level element. The form of the params is the same as the field tags.
   955  func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) {
   956  	v := reflect.ValueOf(val).Elem()
   957  	offset, err := parseField(v, b, 0, parseFieldParameters(params))
   958  	if err != nil {
   959  		return nil, err
   960  	}
   961  	return b[offset:], nil
   962  }