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