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