...
Run Format

Source file src/encoding/asn1/asn1.go

Documentation: encoding/asn1

     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 ObjectIdentifier, 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  // NumericString
   376  
   377  // parseNumericString parses an ASN.1 NumericString from the given byte array
   378  // and returns it.
   379  func parseNumericString(bytes []byte) (ret string, err error) {
   380  	for _, b := range bytes {
   381  		if !isNumeric(b) {
   382  			return "", SyntaxError{"NumericString contains invalid character"}
   383  		}
   384  	}
   385  	return string(bytes), nil
   386  }
   387  
   388  // isNumeric reports whether the given b is in the ASN.1 NumericString set.
   389  func isNumeric(b byte) bool {
   390  	return '0' <= b && b <= '9' ||
   391  		b == ' '
   392  }
   393  
   394  // PrintableString
   395  
   396  // parsePrintableString parses an ASN.1 PrintableString from the given byte
   397  // array and returns it.
   398  func parsePrintableString(bytes []byte) (ret string, err error) {
   399  	for _, b := range bytes {
   400  		if !isPrintable(b, allowAsterisk, allowAmpersand) {
   401  			err = SyntaxError{"PrintableString contains invalid character"}
   402  			return
   403  		}
   404  	}
   405  	ret = string(bytes)
   406  	return
   407  }
   408  
   409  type asteriskFlag bool
   410  type ampersandFlag bool
   411  
   412  const (
   413  	allowAsterisk  asteriskFlag = true
   414  	rejectAsterisk asteriskFlag = false
   415  
   416  	allowAmpersand  ampersandFlag = true
   417  	rejectAmpersand ampersandFlag = false
   418  )
   419  
   420  // isPrintable reports whether the given b is in the ASN.1 PrintableString set.
   421  // If asterisk is allowAsterisk then '*' is also allowed, reflecting existing
   422  // practice. If ampersand is allowAmpersand then '&' is allowed as well.
   423  func isPrintable(b byte, asterisk asteriskFlag, ampersand ampersandFlag) bool {
   424  	return 'a' <= b && b <= 'z' ||
   425  		'A' <= b && b <= 'Z' ||
   426  		'0' <= b && b <= '9' ||
   427  		'\'' <= b && b <= ')' ||
   428  		'+' <= b && b <= '/' ||
   429  		b == ' ' ||
   430  		b == ':' ||
   431  		b == '=' ||
   432  		b == '?' ||
   433  		// This is technically not allowed in a PrintableString.
   434  		// However, x509 certificates with wildcard strings don't
   435  		// always use the correct string type so we permit it.
   436  		(bool(asterisk) && b == '*') ||
   437  		// This is not technically allowed either. However, not
   438  		// only is it relatively common, but there are also a
   439  		// handful of CA certificates that contain it. At least
   440  		// one of which will not expire until 2027.
   441  		(bool(ampersand) && b == '&')
   442  }
   443  
   444  // IA5String
   445  
   446  // parseIA5String parses an ASN.1 IA5String (ASCII string) from the given
   447  // byte slice and returns it.
   448  func parseIA5String(bytes []byte) (ret string, err error) {
   449  	for _, b := range bytes {
   450  		if b >= utf8.RuneSelf {
   451  			err = SyntaxError{"IA5String contains invalid character"}
   452  			return
   453  		}
   454  	}
   455  	ret = string(bytes)
   456  	return
   457  }
   458  
   459  // T61String
   460  
   461  // parseT61String parses an ASN.1 T61String (8-bit clean string) from the given
   462  // byte slice and returns it.
   463  func parseT61String(bytes []byte) (ret string, err error) {
   464  	return string(bytes), nil
   465  }
   466  
   467  // UTF8String
   468  
   469  // parseUTF8String parses an ASN.1 UTF8String (raw UTF-8) from the given byte
   470  // array and returns it.
   471  func parseUTF8String(bytes []byte) (ret string, err error) {
   472  	if !utf8.Valid(bytes) {
   473  		return "", errors.New("asn1: invalid UTF-8 string")
   474  	}
   475  	return string(bytes), nil
   476  }
   477  
   478  // A RawValue represents an undecoded ASN.1 object.
   479  type RawValue struct {
   480  	Class, Tag int
   481  	IsCompound bool
   482  	Bytes      []byte
   483  	FullBytes  []byte // includes the tag and length
   484  }
   485  
   486  // RawContent is used to signal that the undecoded, DER data needs to be
   487  // preserved for a struct. To use it, the first field of the struct must have
   488  // this type. It's an error for any of the other fields to have this type.
   489  type RawContent []byte
   490  
   491  // Tagging
   492  
   493  // parseTagAndLength parses an ASN.1 tag and length pair from the given offset
   494  // into a byte slice. It returns the parsed data and the new offset. SET and
   495  // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
   496  // don't distinguish between ordered and unordered objects in this code.
   497  func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) {
   498  	offset = initOffset
   499  	// parseTagAndLength should not be called without at least a single
   500  	// byte to read. Thus this check is for robustness:
   501  	if offset >= len(bytes) {
   502  		err = errors.New("asn1: internal error in parseTagAndLength")
   503  		return
   504  	}
   505  	b := bytes[offset]
   506  	offset++
   507  	ret.class = int(b >> 6)
   508  	ret.isCompound = b&0x20 == 0x20
   509  	ret.tag = int(b & 0x1f)
   510  
   511  	// If the bottom five bits are set, then the tag number is actually base 128
   512  	// encoded afterwards
   513  	if ret.tag == 0x1f {
   514  		ret.tag, offset, err = parseBase128Int(bytes, offset)
   515  		if err != nil {
   516  			return
   517  		}
   518  		// Tags should be encoded in minimal form.
   519  		if ret.tag < 0x1f {
   520  			err = SyntaxError{"non-minimal tag"}
   521  			return
   522  		}
   523  	}
   524  	if offset >= len(bytes) {
   525  		err = SyntaxError{"truncated tag or length"}
   526  		return
   527  	}
   528  	b = bytes[offset]
   529  	offset++
   530  	if b&0x80 == 0 {
   531  		// The length is encoded in the bottom 7 bits.
   532  		ret.length = int(b & 0x7f)
   533  	} else {
   534  		// Bottom 7 bits give the number of length bytes to follow.
   535  		numBytes := int(b & 0x7f)
   536  		if numBytes == 0 {
   537  			err = SyntaxError{"indefinite length found (not DER)"}
   538  			return
   539  		}
   540  		ret.length = 0
   541  		for i := 0; i < numBytes; i++ {
   542  			if offset >= len(bytes) {
   543  				err = SyntaxError{"truncated tag or length"}
   544  				return
   545  			}
   546  			b = bytes[offset]
   547  			offset++
   548  			if ret.length >= 1<<23 {
   549  				// We can't shift ret.length up without
   550  				// overflowing.
   551  				err = StructuralError{"length too large"}
   552  				return
   553  			}
   554  			ret.length <<= 8
   555  			ret.length |= int(b)
   556  			if ret.length == 0 {
   557  				// DER requires that lengths be minimal.
   558  				err = StructuralError{"superfluous leading zeros in length"}
   559  				return
   560  			}
   561  		}
   562  		// Short lengths must be encoded in short form.
   563  		if ret.length < 0x80 {
   564  			err = StructuralError{"non-minimal length"}
   565  			return
   566  		}
   567  	}
   568  
   569  	return
   570  }
   571  
   572  // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
   573  // a number of ASN.1 values from the given byte slice and returns them as a
   574  // slice of Go values of the given type.
   575  func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) {
   576  	matchAny, expectedTag, compoundType, ok := getUniversalType(elemType)
   577  	if !ok {
   578  		err = StructuralError{"unknown Go type for slice"}
   579  		return
   580  	}
   581  
   582  	// First we iterate over the input and count the number of elements,
   583  	// checking that the types are correct in each case.
   584  	numElements := 0
   585  	for offset := 0; offset < len(bytes); {
   586  		var t tagAndLength
   587  		t, offset, err = parseTagAndLength(bytes, offset)
   588  		if err != nil {
   589  			return
   590  		}
   591  		switch t.tag {
   592  		case TagIA5String, TagGeneralString, TagT61String, TagUTF8String, TagNumericString:
   593  			// We pretend that various other string types are
   594  			// PRINTABLE STRINGs so that a sequence of them can be
   595  			// parsed into a []string.
   596  			t.tag = TagPrintableString
   597  		case TagGeneralizedTime, TagUTCTime:
   598  			// Likewise, both time types are treated the same.
   599  			t.tag = TagUTCTime
   600  		}
   601  
   602  		if !matchAny && (t.class != ClassUniversal || t.isCompound != compoundType || t.tag != expectedTag) {
   603  			err = StructuralError{"sequence tag mismatch"}
   604  			return
   605  		}
   606  		if invalidLength(offset, t.length, len(bytes)) {
   607  			err = SyntaxError{"truncated sequence"}
   608  			return
   609  		}
   610  		offset += t.length
   611  		numElements++
   612  	}
   613  	ret = reflect.MakeSlice(sliceType, numElements, numElements)
   614  	params := fieldParameters{}
   615  	offset := 0
   616  	for i := 0; i < numElements; i++ {
   617  		offset, err = parseField(ret.Index(i), bytes, offset, params)
   618  		if err != nil {
   619  			return
   620  		}
   621  	}
   622  	return
   623  }
   624  
   625  var (
   626  	bitStringType        = reflect.TypeOf(BitString{})
   627  	objectIdentifierType = reflect.TypeOf(ObjectIdentifier{})
   628  	enumeratedType       = reflect.TypeOf(Enumerated(0))
   629  	flagType             = reflect.TypeOf(Flag(false))
   630  	timeType             = reflect.TypeOf(time.Time{})
   631  	rawValueType         = reflect.TypeOf(RawValue{})
   632  	rawContentsType      = reflect.TypeOf(RawContent(nil))
   633  	bigIntType           = reflect.TypeOf(new(big.Int))
   634  )
   635  
   636  // invalidLength returns true iff offset + length > sliceLength, or if the
   637  // addition would overflow.
   638  func invalidLength(offset, length, sliceLength int) bool {
   639  	return offset+length < offset || offset+length > sliceLength
   640  }
   641  
   642  // parseField is the main parsing function. Given a byte slice and an offset
   643  // into the array, it will try to parse a suitable ASN.1 value out and store it
   644  // in the given Value.
   645  func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) {
   646  	offset = initOffset
   647  	fieldType := v.Type()
   648  
   649  	// If we have run out of data, it may be that there are optional elements at the end.
   650  	if offset == len(bytes) {
   651  		if !setDefaultValue(v, params) {
   652  			err = SyntaxError{"sequence truncated"}
   653  		}
   654  		return
   655  	}
   656  
   657  	// Deal with the ANY type.
   658  	if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 {
   659  		var t tagAndLength
   660  		t, offset, err = parseTagAndLength(bytes, offset)
   661  		if err != nil {
   662  			return
   663  		}
   664  		if invalidLength(offset, t.length, len(bytes)) {
   665  			err = SyntaxError{"data truncated"}
   666  			return
   667  		}
   668  		var result interface{}
   669  		if !t.isCompound && t.class == ClassUniversal {
   670  			innerBytes := bytes[offset : offset+t.length]
   671  			switch t.tag {
   672  			case TagPrintableString:
   673  				result, err = parsePrintableString(innerBytes)
   674  			case TagNumericString:
   675  				result, err = parseNumericString(innerBytes)
   676  			case TagIA5String:
   677  				result, err = parseIA5String(innerBytes)
   678  			case TagT61String:
   679  				result, err = parseT61String(innerBytes)
   680  			case TagUTF8String:
   681  				result, err = parseUTF8String(innerBytes)
   682  			case TagInteger:
   683  				result, err = parseInt64(innerBytes)
   684  			case TagBitString:
   685  				result, err = parseBitString(innerBytes)
   686  			case TagOID:
   687  				result, err = parseObjectIdentifier(innerBytes)
   688  			case TagUTCTime:
   689  				result, err = parseUTCTime(innerBytes)
   690  			case TagGeneralizedTime:
   691  				result, err = parseGeneralizedTime(innerBytes)
   692  			case TagOctetString:
   693  				result = innerBytes
   694  			default:
   695  				// If we don't know how to handle the type, we just leave Value as nil.
   696  			}
   697  		}
   698  		offset += t.length
   699  		if err != nil {
   700  			return
   701  		}
   702  		if result != nil {
   703  			v.Set(reflect.ValueOf(result))
   704  		}
   705  		return
   706  	}
   707  
   708  	t, offset, err := parseTagAndLength(bytes, offset)
   709  	if err != nil {
   710  		return
   711  	}
   712  	if params.explicit {
   713  		expectedClass := ClassContextSpecific
   714  		if params.application {
   715  			expectedClass = ClassApplication
   716  		}
   717  		if offset == len(bytes) {
   718  			err = StructuralError{"explicit tag has no child"}
   719  			return
   720  		}
   721  		if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) {
   722  			if fieldType == rawValueType {
   723  				// The inner element should not be parsed for RawValues.
   724  			} else if t.length > 0 {
   725  				t, offset, err = parseTagAndLength(bytes, offset)
   726  				if err != nil {
   727  					return
   728  				}
   729  			} else {
   730  				if fieldType != flagType {
   731  					err = StructuralError{"zero length explicit tag was not an asn1.Flag"}
   732  					return
   733  				}
   734  				v.SetBool(true)
   735  				return
   736  			}
   737  		} else {
   738  			// The tags didn't match, it might be an optional element.
   739  			ok := setDefaultValue(v, params)
   740  			if ok {
   741  				offset = initOffset
   742  			} else {
   743  				err = StructuralError{"explicitly tagged member didn't match"}
   744  			}
   745  			return
   746  		}
   747  	}
   748  
   749  	matchAny, universalTag, compoundType, ok1 := getUniversalType(fieldType)
   750  	if !ok1 {
   751  		err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)}
   752  		return
   753  	}
   754  
   755  	// Special case for strings: all the ASN.1 string types map to the Go
   756  	// type string. getUniversalType returns the tag for PrintableString
   757  	// when it sees a string, so if we see a different string type on the
   758  	// wire, we change the universal type to match.
   759  	if universalTag == TagPrintableString {
   760  		if t.class == ClassUniversal {
   761  			switch t.tag {
   762  			case TagIA5String, TagGeneralString, TagT61String, TagUTF8String, TagNumericString:
   763  				universalTag = t.tag
   764  			}
   765  		} else if params.stringType != 0 {
   766  			universalTag = params.stringType
   767  		}
   768  	}
   769  
   770  	// Special case for time: UTCTime and GeneralizedTime both map to the
   771  	// Go type time.Time.
   772  	if universalTag == TagUTCTime && t.tag == TagGeneralizedTime && t.class == ClassUniversal {
   773  		universalTag = TagGeneralizedTime
   774  	}
   775  
   776  	if params.set {
   777  		universalTag = TagSet
   778  	}
   779  
   780  	matchAnyClassAndTag := matchAny
   781  	expectedClass := ClassUniversal
   782  	expectedTag := universalTag
   783  
   784  	if !params.explicit && params.tag != nil {
   785  		expectedClass = ClassContextSpecific
   786  		expectedTag = *params.tag
   787  		matchAnyClassAndTag = false
   788  	}
   789  
   790  	if !params.explicit && params.application && params.tag != nil {
   791  		expectedClass = ClassApplication
   792  		expectedTag = *params.tag
   793  		matchAnyClassAndTag = false
   794  	}
   795  
   796  	if !params.explicit && params.private && params.tag != nil {
   797  		expectedClass = ClassPrivate
   798  		expectedTag = *params.tag
   799  		matchAnyClassAndTag = false
   800  	}
   801  
   802  	// We have unwrapped any explicit tagging at this point.
   803  	if !matchAnyClassAndTag && (t.class != expectedClass || t.tag != expectedTag) ||
   804  		(!matchAny && t.isCompound != compoundType) {
   805  		// Tags don't match. Again, it could be an optional element.
   806  		ok := setDefaultValue(v, params)
   807  		if ok {
   808  			offset = initOffset
   809  		} else {
   810  			err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)}
   811  		}
   812  		return
   813  	}
   814  	if invalidLength(offset, t.length, len(bytes)) {
   815  		err = SyntaxError{"data truncated"}
   816  		return
   817  	}
   818  	innerBytes := bytes[offset : offset+t.length]
   819  	offset += t.length
   820  
   821  	// We deal with the structures defined in this package first.
   822  	switch fieldType {
   823  	case rawValueType:
   824  		result := RawValue{t.class, t.tag, t.isCompound, innerBytes, bytes[initOffset:offset]}
   825  		v.Set(reflect.ValueOf(result))
   826  		return
   827  	case objectIdentifierType:
   828  		newSlice, err1 := parseObjectIdentifier(innerBytes)
   829  		v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice)))
   830  		if err1 == nil {
   831  			reflect.Copy(v, reflect.ValueOf(newSlice))
   832  		}
   833  		err = err1
   834  		return
   835  	case bitStringType:
   836  		bs, err1 := parseBitString(innerBytes)
   837  		if err1 == nil {
   838  			v.Set(reflect.ValueOf(bs))
   839  		}
   840  		err = err1
   841  		return
   842  	case timeType:
   843  		var time time.Time
   844  		var err1 error
   845  		if universalTag == TagUTCTime {
   846  			time, err1 = parseUTCTime(innerBytes)
   847  		} else {
   848  			time, err1 = parseGeneralizedTime(innerBytes)
   849  		}
   850  		if err1 == nil {
   851  			v.Set(reflect.ValueOf(time))
   852  		}
   853  		err = err1
   854  		return
   855  	case enumeratedType:
   856  		parsedInt, err1 := parseInt32(innerBytes)
   857  		if err1 == nil {
   858  			v.SetInt(int64(parsedInt))
   859  		}
   860  		err = err1
   861  		return
   862  	case flagType:
   863  		v.SetBool(true)
   864  		return
   865  	case bigIntType:
   866  		parsedInt, err1 := parseBigInt(innerBytes)
   867  		if err1 == nil {
   868  			v.Set(reflect.ValueOf(parsedInt))
   869  		}
   870  		err = err1
   871  		return
   872  	}
   873  	switch val := v; val.Kind() {
   874  	case reflect.Bool:
   875  		parsedBool, err1 := parseBool(innerBytes)
   876  		if err1 == nil {
   877  			val.SetBool(parsedBool)
   878  		}
   879  		err = err1
   880  		return
   881  	case reflect.Int, reflect.Int32, reflect.Int64:
   882  		if val.Type().Size() == 4 {
   883  			parsedInt, err1 := parseInt32(innerBytes)
   884  			if err1 == nil {
   885  				val.SetInt(int64(parsedInt))
   886  			}
   887  			err = err1
   888  		} else {
   889  			parsedInt, err1 := parseInt64(innerBytes)
   890  			if err1 == nil {
   891  				val.SetInt(parsedInt)
   892  			}
   893  			err = err1
   894  		}
   895  		return
   896  	// TODO(dfc) Add support for the remaining integer types
   897  	case reflect.Struct:
   898  		structType := fieldType
   899  
   900  		for i := 0; i < structType.NumField(); i++ {
   901  			if structType.Field(i).PkgPath != "" {
   902  				err = StructuralError{"struct contains unexported fields"}
   903  				return
   904  			}
   905  		}
   906  
   907  		if structType.NumField() > 0 &&
   908  			structType.Field(0).Type == rawContentsType {
   909  			bytes := bytes[initOffset:offset]
   910  			val.Field(0).Set(reflect.ValueOf(RawContent(bytes)))
   911  		}
   912  
   913  		innerOffset := 0
   914  		for i := 0; i < structType.NumField(); i++ {
   915  			field := structType.Field(i)
   916  			if i == 0 && field.Type == rawContentsType {
   917  				continue
   918  			}
   919  			innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1")))
   920  			if err != nil {
   921  				return
   922  			}
   923  		}
   924  		// We allow extra bytes at the end of the SEQUENCE because
   925  		// adding elements to the end has been used in X.509 as the
   926  		// version numbers have increased.
   927  		return
   928  	case reflect.Slice:
   929  		sliceType := fieldType
   930  		if sliceType.Elem().Kind() == reflect.Uint8 {
   931  			val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes)))
   932  			reflect.Copy(val, reflect.ValueOf(innerBytes))
   933  			return
   934  		}
   935  		newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem())
   936  		if err1 == nil {
   937  			val.Set(newSlice)
   938  		}
   939  		err = err1
   940  		return
   941  	case reflect.String:
   942  		var v string
   943  		switch universalTag {
   944  		case TagPrintableString:
   945  			v, err = parsePrintableString(innerBytes)
   946  		case TagNumericString:
   947  			v, err = parseNumericString(innerBytes)
   948  		case TagIA5String:
   949  			v, err = parseIA5String(innerBytes)
   950  		case TagT61String:
   951  			v, err = parseT61String(innerBytes)
   952  		case TagUTF8String:
   953  			v, err = parseUTF8String(innerBytes)
   954  		case TagGeneralString:
   955  			// GeneralString is specified in ISO-2022/ECMA-35,
   956  			// A brief review suggests that it includes structures
   957  			// that allow the encoding to change midstring and
   958  			// such. We give up and pass it as an 8-bit string.
   959  			v, err = parseT61String(innerBytes)
   960  		default:
   961  			err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)}
   962  		}
   963  		if err == nil {
   964  			val.SetString(v)
   965  		}
   966  		return
   967  	}
   968  	err = StructuralError{"unsupported: " + v.Type().String()}
   969  	return
   970  }
   971  
   972  // canHaveDefaultValue reports whether k is a Kind that we will set a default
   973  // value for. (A signed integer, essentially.)
   974  func canHaveDefaultValue(k reflect.Kind) bool {
   975  	switch k {
   976  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   977  		return true
   978  	}
   979  
   980  	return false
   981  }
   982  
   983  // setDefaultValue is used to install a default value, from a tag string, into
   984  // a Value. It is successful if the field was optional, even if a default value
   985  // wasn't provided or it failed to install it into the Value.
   986  func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
   987  	if !params.optional {
   988  		return
   989  	}
   990  	ok = true
   991  	if params.defaultValue == nil {
   992  		return
   993  	}
   994  	if canHaveDefaultValue(v.Kind()) {
   995  		v.SetInt(*params.defaultValue)
   996  	}
   997  	return
   998  }
   999  
  1000  // Unmarshal parses the DER-encoded ASN.1 data structure b
  1001  // and uses the reflect package to fill in an arbitrary value pointed at by val.
  1002  // Because Unmarshal uses the reflect package, the structs
  1003  // being written to must use upper case field names.
  1004  //
  1005  // An ASN.1 INTEGER can be written to an int, int32, int64,
  1006  // or *big.Int (from the math/big package).
  1007  // If the encoded value does not fit in the Go type,
  1008  // Unmarshal returns a parse error.
  1009  //
  1010  // An ASN.1 BIT STRING can be written to a BitString.
  1011  //
  1012  // An ASN.1 OCTET STRING can be written to a []byte.
  1013  //
  1014  // An ASN.1 OBJECT IDENTIFIER can be written to an
  1015  // ObjectIdentifier.
  1016  //
  1017  // An ASN.1 ENUMERATED can be written to an Enumerated.
  1018  //
  1019  // An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.
  1020  //
  1021  // An ASN.1 PrintableString, IA5String, or NumericString can be written to a string.
  1022  //
  1023  // Any of the above ASN.1 values can be written to an interface{}.
  1024  // The value stored in the interface has the corresponding Go type.
  1025  // For integers, that type is int64.
  1026  //
  1027  // An ASN.1 SEQUENCE OF x or SET OF x can be written
  1028  // to a slice if an x can be written to the slice's element type.
  1029  //
  1030  // An ASN.1 SEQUENCE or SET can be written to a struct
  1031  // if each of the elements in the sequence can be
  1032  // written to the corresponding element in the struct.
  1033  //
  1034  // The following tags on struct fields have special meaning to Unmarshal:
  1035  //
  1036  //	application specifies that an APPLICATION tag is used
  1037  //	private     specifies that a PRIVATE tag is used
  1038  //	default:x   sets the default value for optional integer fields (only used if optional is also present)
  1039  //	explicit    specifies that an additional, explicit tag wraps the implicit one
  1040  //	optional    marks the field as ASN.1 OPTIONAL
  1041  //	set         causes a SET, rather than a SEQUENCE type to be expected
  1042  //	tag:x       specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
  1043  //
  1044  // If the type of the first field of a structure is RawContent then the raw
  1045  // ASN1 contents of the struct will be stored in it.
  1046  //
  1047  // If the type name of a slice element ends with "SET" then it's treated as if
  1048  // the "set" tag was set on it. This can be used with nested slices where a
  1049  // struct tag cannot be given.
  1050  //
  1051  // Other ASN.1 types are not supported; if it encounters them,
  1052  // Unmarshal returns a parse error.
  1053  func Unmarshal(b []byte, val interface{}) (rest []byte, err error) {
  1054  	return UnmarshalWithParams(b, val, "")
  1055  }
  1056  
  1057  // UnmarshalWithParams allows field parameters to be specified for the
  1058  // top-level element. The form of the params is the same as the field tags.
  1059  func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) {
  1060  	v := reflect.ValueOf(val).Elem()
  1061  	offset, err := parseField(v, b, 0, parseFieldParameters(params))
  1062  	if err != nil {
  1063  		return nil, err
  1064  	}
  1065  	return b[offset:], nil
  1066  }
  1067  

View as plain text