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