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