github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/src/encoding/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  import (
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  	"reflect"
    27  	"strconv"
    28  	"time"
    29  	"unicode/utf8"
    30  )
    31  
    32  // A StructuralError suggests that the ASN.1 data is valid, but the Go type
    33  // which is receiving it doesn't match.
    34  type StructuralError struct {
    35  	Msg string
    36  }
    37  
    38  func (e StructuralError) Error() string { return "asn1: structure error: " + e.Msg }
    39  
    40  // A SyntaxError suggests that the ASN.1 data is invalid.
    41  type SyntaxError struct {
    42  	Msg string
    43  }
    44  
    45  func (e SyntaxError) Error() string { return "asn1: syntax error: " + e.Msg }
    46  
    47  // We start by dealing with each of the primitive types in turn.
    48  
    49  // BOOLEAN
    50  
    51  func parseBool(bytes []byte) (ret bool, err error) {
    52  	if len(bytes) != 1 {
    53  		err = SyntaxError{"invalid boolean"}
    54  		return
    55  	}
    56  
    57  	// DER demands that "If the encoding represents the boolean value TRUE,
    58  	// its single contents octet shall have all eight bits set to one."
    59  	// Thus only 0 and 255 are valid encoded values.
    60  	switch bytes[0] {
    61  	case 0:
    62  		ret = false
    63  	case 0xff:
    64  		ret = true
    65  	default:
    66  		err = SyntaxError{"invalid boolean"}
    67  	}
    68  
    69  	return
    70  }
    71  
    72  // INTEGER
    73  
    74  // parseInt64 treats the given bytes as a big-endian, signed integer and
    75  // returns the result.
    76  func parseInt64(bytes []byte) (ret int64, err error) {
    77  	if len(bytes) > 8 {
    78  		// We'll overflow an int64 in this case.
    79  		err = StructuralError{"integer too large"}
    80  		return
    81  	}
    82  	for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
    83  		ret <<= 8
    84  		ret |= int64(bytes[bytesRead])
    85  	}
    86  
    87  	// Shift up and down in order to sign extend the result.
    88  	ret <<= 64 - uint8(len(bytes))*8
    89  	ret >>= 64 - uint8(len(bytes))*8
    90  	return
    91  }
    92  
    93  // parseInt treats the given bytes as a big-endian, signed integer and returns
    94  // the result.
    95  func parseInt32(bytes []byte) (int32, error) {
    96  	ret64, err := parseInt64(bytes)
    97  	if err != nil {
    98  		return 0, err
    99  	}
   100  	if ret64 != int64(int32(ret64)) {
   101  		return 0, StructuralError{"integer too large"}
   102  	}
   103  	return int32(ret64), nil
   104  }
   105  
   106  var bigOne = big.NewInt(1)
   107  
   108  // parseBigInt treats the given bytes as a big-endian, signed integer and returns
   109  // the result.
   110  func parseBigInt(bytes []byte) *big.Int {
   111  	ret := new(big.Int)
   112  	if len(bytes) > 0 && bytes[0]&0x80 == 0x80 {
   113  		// This is a negative number.
   114  		notBytes := make([]byte, len(bytes))
   115  		for i := range notBytes {
   116  			notBytes[i] = ^bytes[i]
   117  		}
   118  		ret.SetBytes(notBytes)
   119  		ret.Add(ret, bigOne)
   120  		ret.Neg(ret)
   121  		return ret
   122  	}
   123  	ret.SetBytes(bytes)
   124  	return ret
   125  }
   126  
   127  // BIT STRING
   128  
   129  // BitString is the structure to use when you want an ASN.1 BIT STRING type. A
   130  // bit string is padded up to the nearest byte in memory and the number of
   131  // valid bits is recorded. Padding bits will be zero.
   132  type BitString struct {
   133  	Bytes     []byte // bits packed into bytes.
   134  	BitLength int    // length in bits.
   135  }
   136  
   137  // At returns the bit at the given index. If the index is out of range it
   138  // returns false.
   139  func (b BitString) At(i int) int {
   140  	if i < 0 || i >= b.BitLength {
   141  		return 0
   142  	}
   143  	x := i / 8
   144  	y := 7 - uint(i%8)
   145  	return int(b.Bytes[x]>>y) & 1
   146  }
   147  
   148  // RightAlign returns a slice where the padding bits are at the beginning. The
   149  // slice may share memory with the BitString.
   150  func (b BitString) RightAlign() []byte {
   151  	shift := uint(8 - (b.BitLength % 8))
   152  	if shift == 8 || len(b.Bytes) == 0 {
   153  		return b.Bytes
   154  	}
   155  
   156  	a := make([]byte, len(b.Bytes))
   157  	a[0] = b.Bytes[0] >> shift
   158  	for i := 1; i < len(b.Bytes); i++ {
   159  		a[i] = b.Bytes[i-1] << (8 - shift)
   160  		a[i] |= b.Bytes[i] >> shift
   161  	}
   162  
   163  	return a
   164  }
   165  
   166  // parseBitString parses an ASN.1 bit string from the given byte slice and returns it.
   167  func parseBitString(bytes []byte) (ret BitString, err error) {
   168  	if len(bytes) == 0 {
   169  		err = SyntaxError{"zero length BIT STRING"}
   170  		return
   171  	}
   172  	paddingBits := int(bytes[0])
   173  	if paddingBits > 7 ||
   174  		len(bytes) == 1 && paddingBits > 0 ||
   175  		bytes[len(bytes)-1]&((1<<bytes[0])-1) != 0 {
   176  		err = SyntaxError{"invalid padding bits in BIT STRING"}
   177  		return
   178  	}
   179  	ret.BitLength = (len(bytes)-1)*8 - paddingBits
   180  	ret.Bytes = bytes[1:]
   181  	return
   182  }
   183  
   184  // OBJECT IDENTIFIER
   185  
   186  // An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
   187  type ObjectIdentifier []int
   188  
   189  // Equal reports whether oi and other represent the same identifier.
   190  func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {
   191  	if len(oi) != len(other) {
   192  		return false
   193  	}
   194  	for i := 0; i < len(oi); i++ {
   195  		if oi[i] != other[i] {
   196  			return false
   197  		}
   198  	}
   199  
   200  	return true
   201  }
   202  
   203  func (oi ObjectIdentifier) String() string {
   204  	var s string
   205  
   206  	for i, v := range oi {
   207  		if i > 0 {
   208  			s += "."
   209  		}
   210  		s += strconv.Itoa(v)
   211  	}
   212  
   213  	return s
   214  }
   215  
   216  // parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
   217  // returns it. An object identifier is a sequence of variable length integers
   218  // that are assigned in a hierarchy.
   219  func parseObjectIdentifier(bytes []byte) (s []int, err error) {
   220  	if len(bytes) == 0 {
   221  		err = SyntaxError{"zero length OBJECT IDENTIFIER"}
   222  		return
   223  	}
   224  
   225  	// In the worst case, we get two elements from the first byte (which is
   226  	// encoded differently) and then every varint is a single byte long.
   227  	s = make([]int, len(bytes)+1)
   228  
   229  	// The first varint is 40*value1 + value2:
   230  	// According to this packing, value1 can take the values 0, 1 and 2 only.
   231  	// When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
   232  	// then there are no restrictions on value2.
   233  	v, offset, err := parseBase128Int(bytes, 0)
   234  	if err != nil {
   235  		return
   236  	}
   237  	if v < 80 {
   238  		s[0] = v / 40
   239  		s[1] = v % 40
   240  	} else {
   241  		s[0] = 2
   242  		s[1] = v - 80
   243  	}
   244  
   245  	i := 2
   246  	for ; offset < len(bytes); i++ {
   247  		v, offset, err = parseBase128Int(bytes, offset)
   248  		if err != nil {
   249  			return
   250  		}
   251  		s[i] = v
   252  	}
   253  	s = s[0:i]
   254  	return
   255  }
   256  
   257  // ENUMERATED
   258  
   259  // An Enumerated is represented as a plain int.
   260  type Enumerated int
   261  
   262  // FLAG
   263  
   264  // A Flag accepts any data and is set to true if present.
   265  type Flag bool
   266  
   267  // parseBase128Int parses a base-128 encoded int from the given offset in the
   268  // given byte slice. It returns the value and the new offset.
   269  func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
   270  	offset = initOffset
   271  	for shifted := 0; offset < len(bytes); shifted++ {
   272  		if shifted > 4 {
   273  			err = StructuralError{"base 128 integer too large"}
   274  			return
   275  		}
   276  		ret <<= 7
   277  		b := bytes[offset]
   278  		ret |= int(b & 0x7f)
   279  		offset++
   280  		if b&0x80 == 0 {
   281  			return
   282  		}
   283  	}
   284  	err = SyntaxError{"truncated base 128 integer"}
   285  	return
   286  }
   287  
   288  // UTCTime
   289  
   290  func parseUTCTime(bytes []byte) (ret time.Time, err error) {
   291  	s := string(bytes)
   292  
   293  	formatStr := "0601021504Z0700"
   294  	ret, err = time.Parse(formatStr, s)
   295  	if err != nil {
   296  		formatStr = "060102150405Z0700"
   297  		ret, err = time.Parse(formatStr, s)
   298  	}
   299  	if err != nil {
   300  		return
   301  	}
   302  
   303  	if serialized := ret.Format(formatStr); serialized != s {
   304  		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)
   305  		return
   306  	}
   307  
   308  	if ret.Year() >= 2050 {
   309  		// UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
   310  		ret = ret.AddDate(-100, 0, 0)
   311  	}
   312  
   313  	return
   314  }
   315  
   316  // parseGeneralizedTime parses the GeneralizedTime from the given byte slice
   317  // and returns the resulting time.
   318  func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) {
   319  	const formatStr = "20060102150405Z0700"
   320  	s := string(bytes)
   321  
   322  	if ret, err = time.Parse(formatStr, s); err != nil {
   323  		return
   324  	}
   325  
   326  	if serialized := ret.Format(formatStr); serialized != s {
   327  		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)
   328  	}
   329  
   330  	return
   331  }
   332  
   333  // PrintableString
   334  
   335  // parsePrintableString parses a ASN.1 PrintableString from the given byte
   336  // array and returns it.
   337  func parsePrintableString(bytes []byte) (ret string, err error) {
   338  	for _, b := range bytes {
   339  		if !isPrintable(b) {
   340  			err = SyntaxError{"PrintableString contains invalid character"}
   341  			return
   342  		}
   343  	}
   344  	ret = string(bytes)
   345  	return
   346  }
   347  
   348  // isPrintable reports whether the given b is in the ASN.1 PrintableString set.
   349  func isPrintable(b byte) bool {
   350  	return 'a' <= b && b <= 'z' ||
   351  		'A' <= b && b <= 'Z' ||
   352  		'0' <= b && b <= '9' ||
   353  		'\'' <= b && b <= ')' ||
   354  		'+' <= b && b <= '/' ||
   355  		b == ' ' ||
   356  		b == ':' ||
   357  		b == '=' ||
   358  		b == '?' ||
   359  		// This is technically not allowed in a PrintableString.
   360  		// However, x509 certificates with wildcard strings don't
   361  		// always use the correct string type so we permit it.
   362  		b == '*'
   363  }
   364  
   365  // IA5String
   366  
   367  // parseIA5String parses a ASN.1 IA5String (ASCII string) from the given
   368  // byte slice and returns it.
   369  func parseIA5String(bytes []byte) (ret string, err error) {
   370  	for _, b := range bytes {
   371  		if b >= 0x80 {
   372  			err = SyntaxError{"IA5String contains invalid character"}
   373  			return
   374  		}
   375  	}
   376  	ret = string(bytes)
   377  	return
   378  }
   379  
   380  // T61String
   381  
   382  // parseT61String parses a ASN.1 T61String (8-bit clean string) from the given
   383  // byte slice and returns it.
   384  func parseT61String(bytes []byte) (ret string, err error) {
   385  	return string(bytes), nil
   386  }
   387  
   388  // UTF8String
   389  
   390  // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
   391  // array and returns it.
   392  func parseUTF8String(bytes []byte) (ret string, err error) {
   393  	if !utf8.Valid(bytes) {
   394  		return "", errors.New("asn1: invalid UTF-8 string")
   395  	}
   396  	return string(bytes), nil
   397  }
   398  
   399  // A RawValue represents an undecoded ASN.1 object.
   400  type RawValue struct {
   401  	Class, Tag int
   402  	IsCompound bool
   403  	Bytes      []byte
   404  	FullBytes  []byte // includes the tag and length
   405  }
   406  
   407  // RawContent is used to signal that the undecoded, DER data needs to be
   408  // preserved for a struct. To use it, the first field of the struct must have
   409  // this type. It's an error for any of the other fields to have this type.
   410  type RawContent []byte
   411  
   412  // Tagging
   413  
   414  // parseTagAndLength parses an ASN.1 tag and length pair from the given offset
   415  // into a byte slice. It returns the parsed data and the new offset. SET and
   416  // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
   417  // don't distinguish between ordered and unordered objects in this code.
   418  func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) {
   419  	offset = initOffset
   420  	// parseTagAndLength should not be called without at least a single
   421  	// byte to read. Thus this check is for robustness:
   422  	if offset >= len(bytes) {
   423  		err = errors.New("asn1: internal error in parseTagAndLength")
   424  		return
   425  	}
   426  	b := bytes[offset]
   427  	offset++
   428  	ret.class = int(b >> 6)
   429  	ret.isCompound = b&0x20 == 0x20
   430  	ret.tag = int(b & 0x1f)
   431  
   432  	// If the bottom five bits are set, then the tag number is actually base 128
   433  	// encoded afterwards
   434  	if ret.tag == 0x1f {
   435  		ret.tag, offset, err = parseBase128Int(bytes, offset)
   436  		if err != nil {
   437  			return
   438  		}
   439  	}
   440  	if offset >= len(bytes) {
   441  		err = SyntaxError{"truncated tag or length"}
   442  		return
   443  	}
   444  	b = bytes[offset]
   445  	offset++
   446  	if b&0x80 == 0 {
   447  		// The length is encoded in the bottom 7 bits.
   448  		ret.length = int(b & 0x7f)
   449  	} else {
   450  		// Bottom 7 bits give the number of length bytes to follow.
   451  		numBytes := int(b & 0x7f)
   452  		if numBytes == 0 {
   453  			err = SyntaxError{"indefinite length found (not DER)"}
   454  			return
   455  		}
   456  		ret.length = 0
   457  		for i := 0; i < numBytes; i++ {
   458  			if offset >= len(bytes) {
   459  				err = SyntaxError{"truncated tag or length"}
   460  				return
   461  			}
   462  			b = bytes[offset]
   463  			offset++
   464  			if ret.length >= 1<<23 {
   465  				// We can't shift ret.length up without
   466  				// overflowing.
   467  				err = StructuralError{"length too large"}
   468  				return
   469  			}
   470  			ret.length <<= 8
   471  			ret.length |= int(b)
   472  			if ret.length == 0 {
   473  				// DER requires that lengths be minimal.
   474  				err = StructuralError{"superfluous leading zeros in length"}
   475  				return
   476  			}
   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  }