Source file src/encoding/asn1/asn1.go

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

View as plain text