Source file src/vendor/golang.org/x/crypto/cryptobyte/asn1.go

     1  // Copyright 2017 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 cryptobyte
     6  
     7  import (
     8  	encoding_asn1 "encoding/asn1"
     9  	"fmt"
    10  	"math/big"
    11  	"reflect"
    12  	"time"
    13  
    14  	"golang.org/x/crypto/cryptobyte/asn1"
    15  )
    16  
    17  // This file contains ASN.1-related methods for String and Builder.
    18  
    19  // Builder
    20  
    21  // AddASN1Int64 appends a DER-encoded ASN.1 INTEGER.
    22  func (b *Builder) AddASN1Int64(v int64) {
    23  	b.addASN1Signed(asn1.INTEGER, v)
    24  }
    25  
    26  // AddASN1Int64WithTag appends a DER-encoded ASN.1 INTEGER with the
    27  // given tag.
    28  func (b *Builder) AddASN1Int64WithTag(v int64, tag asn1.Tag) {
    29  	b.addASN1Signed(tag, v)
    30  }
    31  
    32  // AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION.
    33  func (b *Builder) AddASN1Enum(v int64) {
    34  	b.addASN1Signed(asn1.ENUM, v)
    35  }
    36  
    37  func (b *Builder) addASN1Signed(tag asn1.Tag, v int64) {
    38  	b.AddASN1(tag, func(c *Builder) {
    39  		length := 1
    40  		for i := v; i >= 0x80 || i < -0x80; i >>= 8 {
    41  			length++
    42  		}
    43  
    44  		for ; length > 0; length-- {
    45  			i := v >> uint((length-1)*8) & 0xff
    46  			c.AddUint8(uint8(i))
    47  		}
    48  	})
    49  }
    50  
    51  // AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER.
    52  func (b *Builder) AddASN1Uint64(v uint64) {
    53  	b.AddASN1(asn1.INTEGER, func(c *Builder) {
    54  		length := 1
    55  		for i := v; i >= 0x80; i >>= 8 {
    56  			length++
    57  		}
    58  
    59  		for ; length > 0; length-- {
    60  			i := v >> uint((length-1)*8) & 0xff
    61  			c.AddUint8(uint8(i))
    62  		}
    63  	})
    64  }
    65  
    66  // AddASN1BigInt appends a DER-encoded ASN.1 INTEGER.
    67  func (b *Builder) AddASN1BigInt(n *big.Int) {
    68  	if b.err != nil {
    69  		return
    70  	}
    71  
    72  	b.AddASN1(asn1.INTEGER, func(c *Builder) {
    73  		if n.Sign() < 0 {
    74  			// A negative number has to be converted to two's-complement form. So we
    75  			// invert and subtract 1. If the most-significant-bit isn't set then
    76  			// we'll need to pad the beginning with 0xff in order to keep the number
    77  			// negative.
    78  			nMinus1 := new(big.Int).Neg(n)
    79  			nMinus1.Sub(nMinus1, bigOne)
    80  			bytes := nMinus1.Bytes()
    81  			for i := range bytes {
    82  				bytes[i] ^= 0xff
    83  			}
    84  			if len(bytes) == 0 || bytes[0]&0x80 == 0 {
    85  				c.add(0xff)
    86  			}
    87  			c.add(bytes...)
    88  		} else if n.Sign() == 0 {
    89  			c.add(0)
    90  		} else {
    91  			bytes := n.Bytes()
    92  			if bytes[0]&0x80 != 0 {
    93  				c.add(0)
    94  			}
    95  			c.add(bytes...)
    96  		}
    97  	})
    98  }
    99  
   100  // AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING.
   101  func (b *Builder) AddASN1OctetString(bytes []byte) {
   102  	b.AddASN1(asn1.OCTET_STRING, func(c *Builder) {
   103  		c.AddBytes(bytes)
   104  	})
   105  }
   106  
   107  const generalizedTimeFormatStr = "20060102150405Z0700"
   108  
   109  // AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME.
   110  func (b *Builder) AddASN1GeneralizedTime(t time.Time) {
   111  	if t.Year() < 0 || t.Year() > 9999 {
   112  		b.err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", t)
   113  		return
   114  	}
   115  	b.AddASN1(asn1.GeneralizedTime, func(c *Builder) {
   116  		c.AddBytes([]byte(t.Format(generalizedTimeFormatStr)))
   117  	})
   118  }
   119  
   120  // AddASN1UTCTime appends a DER-encoded ASN.1 UTCTime.
   121  func (b *Builder) AddASN1UTCTime(t time.Time) {
   122  	b.AddASN1(asn1.UTCTime, func(c *Builder) {
   123  		// As utilized by the X.509 profile, UTCTime can only
   124  		// represent the years 1950 through 2049.
   125  		if t.Year() < 1950 || t.Year() >= 2050 {
   126  			b.err = fmt.Errorf("cryptobyte: cannot represent %v as a UTCTime", t)
   127  			return
   128  		}
   129  		c.AddBytes([]byte(t.Format(defaultUTCTimeFormatStr)))
   130  	})
   131  }
   132  
   133  // AddASN1BitString appends a DER-encoded ASN.1 BIT STRING. This does not
   134  // support BIT STRINGs that are not a whole number of bytes.
   135  func (b *Builder) AddASN1BitString(data []byte) {
   136  	b.AddASN1(asn1.BIT_STRING, func(b *Builder) {
   137  		b.AddUint8(0)
   138  		b.AddBytes(data)
   139  	})
   140  }
   141  
   142  func (b *Builder) addBase128Int(n int64) {
   143  	var length int
   144  	if n == 0 {
   145  		length = 1
   146  	} else {
   147  		for i := n; i > 0; i >>= 7 {
   148  			length++
   149  		}
   150  	}
   151  
   152  	for i := length - 1; i >= 0; i-- {
   153  		o := byte(n >> uint(i*7))
   154  		o &= 0x7f
   155  		if i != 0 {
   156  			o |= 0x80
   157  		}
   158  
   159  		b.add(o)
   160  	}
   161  }
   162  
   163  func isValidOID(oid encoding_asn1.ObjectIdentifier) bool {
   164  	if len(oid) < 2 {
   165  		return false
   166  	}
   167  
   168  	if oid[0] > 2 || (oid[0] <= 1 && oid[1] >= 40) {
   169  		return false
   170  	}
   171  
   172  	for _, v := range oid {
   173  		if v < 0 {
   174  			return false
   175  		}
   176  	}
   177  
   178  	return true
   179  }
   180  
   181  func (b *Builder) AddASN1ObjectIdentifier(oid encoding_asn1.ObjectIdentifier) {
   182  	b.AddASN1(asn1.OBJECT_IDENTIFIER, func(b *Builder) {
   183  		if !isValidOID(oid) {
   184  			b.err = fmt.Errorf("cryptobyte: invalid OID: %v", oid)
   185  			return
   186  		}
   187  
   188  		b.addBase128Int(int64(oid[0])*40 + int64(oid[1]))
   189  		for _, v := range oid[2:] {
   190  			b.addBase128Int(int64(v))
   191  		}
   192  	})
   193  }
   194  
   195  func (b *Builder) AddASN1Boolean(v bool) {
   196  	b.AddASN1(asn1.BOOLEAN, func(b *Builder) {
   197  		if v {
   198  			b.AddUint8(0xff)
   199  		} else {
   200  			b.AddUint8(0)
   201  		}
   202  	})
   203  }
   204  
   205  func (b *Builder) AddASN1NULL() {
   206  	b.add(uint8(asn1.NULL), 0)
   207  }
   208  
   209  // MarshalASN1 calls encoding_asn1.Marshal on its input and appends the result if
   210  // successful or records an error if one occurred.
   211  func (b *Builder) MarshalASN1(v interface{}) {
   212  	// NOTE(martinkr): This is somewhat of a hack to allow propagation of
   213  	// encoding_asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a
   214  	// value embedded into a struct, its tag information is lost.
   215  	if b.err != nil {
   216  		return
   217  	}
   218  	bytes, err := encoding_asn1.Marshal(v)
   219  	if err != nil {
   220  		b.err = err
   221  		return
   222  	}
   223  	b.AddBytes(bytes)
   224  }
   225  
   226  // AddASN1 appends an ASN.1 object. The object is prefixed with the given tag.
   227  // Tags greater than 30 are not supported and result in an error (i.e.
   228  // low-tag-number form only). The child builder passed to the
   229  // BuilderContinuation can be used to build the content of the ASN.1 object.
   230  func (b *Builder) AddASN1(tag asn1.Tag, f BuilderContinuation) {
   231  	if b.err != nil {
   232  		return
   233  	}
   234  	// Identifiers with the low five bits set indicate high-tag-number format
   235  	// (two or more octets), which we don't support.
   236  	if tag&0x1f == 0x1f {
   237  		b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag)
   238  		return
   239  	}
   240  	b.AddUint8(uint8(tag))
   241  	b.addLengthPrefixed(1, true, f)
   242  }
   243  
   244  // String
   245  
   246  // ReadASN1Boolean decodes an ASN.1 BOOLEAN and converts it to a boolean
   247  // representation into out and advances. It reports whether the read
   248  // was successful.
   249  func (s *String) ReadASN1Boolean(out *bool) bool {
   250  	var bytes String
   251  	if !s.ReadASN1(&bytes, asn1.BOOLEAN) || len(bytes) != 1 {
   252  		return false
   253  	}
   254  
   255  	switch bytes[0] {
   256  	case 0:
   257  		*out = false
   258  	case 0xff:
   259  		*out = true
   260  	default:
   261  		return false
   262  	}
   263  
   264  	return true
   265  }
   266  
   267  // ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does
   268  // not point to an integer, to a big.Int, or to a []byte it panics. Only
   269  // positive and zero values can be decoded into []byte, and they are returned as
   270  // big-endian binary values that share memory with s. Positive values will have
   271  // no leading zeroes, and zero will be returned as a single zero byte.
   272  // ReadASN1Integer reports whether the read was successful.
   273  func (s *String) ReadASN1Integer(out interface{}) bool {
   274  	switch out := out.(type) {
   275  	case *int, *int8, *int16, *int32, *int64:
   276  		var i int64
   277  		if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) {
   278  			return false
   279  		}
   280  		reflect.ValueOf(out).Elem().SetInt(i)
   281  		return true
   282  	case *uint, *uint8, *uint16, *uint32, *uint64:
   283  		var u uint64
   284  		if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) {
   285  			return false
   286  		}
   287  		reflect.ValueOf(out).Elem().SetUint(u)
   288  		return true
   289  	case *big.Int:
   290  		return s.readASN1BigInt(out)
   291  	case *[]byte:
   292  		return s.readASN1Bytes(out)
   293  	default:
   294  		panic("out does not point to an integer type")
   295  	}
   296  }
   297  
   298  func checkASN1Integer(bytes []byte) bool {
   299  	if len(bytes) == 0 {
   300  		// An INTEGER is encoded with at least one octet.
   301  		return false
   302  	}
   303  	if len(bytes) == 1 {
   304  		return true
   305  	}
   306  	if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 {
   307  		// Value is not minimally encoded.
   308  		return false
   309  	}
   310  	return true
   311  }
   312  
   313  var bigOne = big.NewInt(1)
   314  
   315  func (s *String) readASN1BigInt(out *big.Int) bool {
   316  	var bytes String
   317  	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) {
   318  		return false
   319  	}
   320  	if bytes[0]&0x80 == 0x80 {
   321  		// Negative number.
   322  		neg := make([]byte, len(bytes))
   323  		for i, b := range bytes {
   324  			neg[i] = ^b
   325  		}
   326  		out.SetBytes(neg)
   327  		out.Add(out, bigOne)
   328  		out.Neg(out)
   329  	} else {
   330  		out.SetBytes(bytes)
   331  	}
   332  	return true
   333  }
   334  
   335  func (s *String) readASN1Bytes(out *[]byte) bool {
   336  	var bytes String
   337  	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) {
   338  		return false
   339  	}
   340  	if bytes[0]&0x80 == 0x80 {
   341  		return false
   342  	}
   343  	for len(bytes) > 1 && bytes[0] == 0 {
   344  		bytes = bytes[1:]
   345  	}
   346  	*out = bytes
   347  	return true
   348  }
   349  
   350  func (s *String) readASN1Int64(out *int64) bool {
   351  	var bytes String
   352  	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) {
   353  		return false
   354  	}
   355  	return true
   356  }
   357  
   358  func asn1Signed(out *int64, n []byte) bool {
   359  	length := len(n)
   360  	if length > 8 {
   361  		return false
   362  	}
   363  	for i := 0; i < length; i++ {
   364  		*out <<= 8
   365  		*out |= int64(n[i])
   366  	}
   367  	// Shift up and down in order to sign extend the result.
   368  	*out <<= 64 - uint8(length)*8
   369  	*out >>= 64 - uint8(length)*8
   370  	return true
   371  }
   372  
   373  func (s *String) readASN1Uint64(out *uint64) bool {
   374  	var bytes String
   375  	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) {
   376  		return false
   377  	}
   378  	return true
   379  }
   380  
   381  func asn1Unsigned(out *uint64, n []byte) bool {
   382  	length := len(n)
   383  	if length > 9 || length == 9 && n[0] != 0 {
   384  		// Too large for uint64.
   385  		return false
   386  	}
   387  	if n[0]&0x80 != 0 {
   388  		// Negative number.
   389  		return false
   390  	}
   391  	for i := 0; i < length; i++ {
   392  		*out <<= 8
   393  		*out |= uint64(n[i])
   394  	}
   395  	return true
   396  }
   397  
   398  // ReadASN1Int64WithTag decodes an ASN.1 INTEGER with the given tag into out
   399  // and advances. It reports whether the read was successful and resulted in a
   400  // value that can be represented in an int64.
   401  func (s *String) ReadASN1Int64WithTag(out *int64, tag asn1.Tag) bool {
   402  	var bytes String
   403  	return s.ReadASN1(&bytes, tag) && checkASN1Integer(bytes) && asn1Signed(out, bytes)
   404  }
   405  
   406  // ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It reports
   407  // whether the read was successful.
   408  func (s *String) ReadASN1Enum(out *int) bool {
   409  	var bytes String
   410  	var i int64
   411  	if !s.ReadASN1(&bytes, asn1.ENUM) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) {
   412  		return false
   413  	}
   414  	if int64(int(i)) != i {
   415  		return false
   416  	}
   417  	*out = int(i)
   418  	return true
   419  }
   420  
   421  func (s *String) readBase128Int(out *int) bool {
   422  	ret := 0
   423  	for i := 0; len(*s) > 0; i++ {
   424  		if i == 5 {
   425  			return false
   426  		}
   427  		// Avoid overflowing int on a 32-bit platform.
   428  		// We don't want different behavior based on the architecture.
   429  		if ret >= 1<<(31-7) {
   430  			return false
   431  		}
   432  		ret <<= 7
   433  		b := s.read(1)[0]
   434  
   435  		// ITU-T X.690, section 8.19.2:
   436  		// The subidentifier shall be encoded in the fewest possible octets,
   437  		// that is, the leading octet of the subidentifier shall not have the value 0x80.
   438  		if i == 0 && b == 0x80 {
   439  			return false
   440  		}
   441  
   442  		ret |= int(b & 0x7f)
   443  		if b&0x80 == 0 {
   444  			*out = ret
   445  			return true
   446  		}
   447  	}
   448  	return false // truncated
   449  }
   450  
   451  // ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and
   452  // advances. It reports whether the read was successful.
   453  func (s *String) ReadASN1ObjectIdentifier(out *encoding_asn1.ObjectIdentifier) bool {
   454  	var bytes String
   455  	if !s.ReadASN1(&bytes, asn1.OBJECT_IDENTIFIER) || len(bytes) == 0 {
   456  		return false
   457  	}
   458  
   459  	// In the worst case, we get two elements from the first byte (which is
   460  	// encoded differently) and then every varint is a single byte long.
   461  	components := make([]int, len(bytes)+1)
   462  
   463  	// The first varint is 40*value1 + value2:
   464  	// According to this packing, value1 can take the values 0, 1 and 2 only.
   465  	// When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
   466  	// then there are no restrictions on value2.
   467  	var v int
   468  	if !bytes.readBase128Int(&v) {
   469  		return false
   470  	}
   471  	if v < 80 {
   472  		components[0] = v / 40
   473  		components[1] = v % 40
   474  	} else {
   475  		components[0] = 2
   476  		components[1] = v - 80
   477  	}
   478  
   479  	i := 2
   480  	for ; len(bytes) > 0; i++ {
   481  		if !bytes.readBase128Int(&v) {
   482  			return false
   483  		}
   484  		components[i] = v
   485  	}
   486  	*out = components[:i]
   487  	return true
   488  }
   489  
   490  // ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and
   491  // advances. It reports whether the read was successful.
   492  func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool {
   493  	var bytes String
   494  	if !s.ReadASN1(&bytes, asn1.GeneralizedTime) {
   495  		return false
   496  	}
   497  	t := string(bytes)
   498  	res, err := time.Parse(generalizedTimeFormatStr, t)
   499  	if err != nil {
   500  		return false
   501  	}
   502  	if serialized := res.Format(generalizedTimeFormatStr); serialized != t {
   503  		return false
   504  	}
   505  	*out = res
   506  	return true
   507  }
   508  
   509  const defaultUTCTimeFormatStr = "060102150405Z0700"
   510  
   511  // ReadASN1UTCTime decodes an ASN.1 UTCTime into out and advances.
   512  // It reports whether the read was successful.
   513  func (s *String) ReadASN1UTCTime(out *time.Time) bool {
   514  	var bytes String
   515  	if !s.ReadASN1(&bytes, asn1.UTCTime) {
   516  		return false
   517  	}
   518  	t := string(bytes)
   519  
   520  	formatStr := defaultUTCTimeFormatStr
   521  	var err error
   522  	res, err := time.Parse(formatStr, t)
   523  	if err != nil {
   524  		// Fallback to minute precision if we can't parse second
   525  		// precision. If we are following X.509 or X.690 we shouldn't
   526  		// support this, but we do.
   527  		formatStr = "0601021504Z0700"
   528  		res, err = time.Parse(formatStr, t)
   529  	}
   530  	if err != nil {
   531  		return false
   532  	}
   533  
   534  	if serialized := res.Format(formatStr); serialized != t {
   535  		return false
   536  	}
   537  
   538  	if res.Year() >= 2050 {
   539  		// UTCTime interprets the low order digits 50-99 as 1950-99.
   540  		// This only applies to its use in the X.509 profile.
   541  		// See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
   542  		res = res.AddDate(-100, 0, 0)
   543  	}
   544  	*out = res
   545  	return true
   546  }
   547  
   548  // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances.
   549  // It reports whether the read was successful.
   550  func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool {
   551  	var bytes String
   552  	if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 ||
   553  		len(bytes)*8/8 != len(bytes) {
   554  		return false
   555  	}
   556  
   557  	paddingBits := bytes[0]
   558  	bytes = bytes[1:]
   559  	if paddingBits > 7 ||
   560  		len(bytes) == 0 && paddingBits != 0 ||
   561  		len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 {
   562  		return false
   563  	}
   564  
   565  	out.BitLength = len(bytes)*8 - int(paddingBits)
   566  	out.Bytes = bytes
   567  	return true
   568  }
   569  
   570  // ReadASN1BitStringAsBytes decodes an ASN.1 BIT STRING into out and advances. It is
   571  // an error if the BIT STRING is not a whole number of bytes. It reports
   572  // whether the read was successful.
   573  func (s *String) ReadASN1BitStringAsBytes(out *[]byte) bool {
   574  	var bytes String
   575  	if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 {
   576  		return false
   577  	}
   578  
   579  	paddingBits := bytes[0]
   580  	if paddingBits != 0 {
   581  		return false
   582  	}
   583  	*out = bytes[1:]
   584  	return true
   585  }
   586  
   587  // ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including
   588  // tag and length bytes) into out, and advances. The element must match the
   589  // given tag. It reports whether the read was successful.
   590  func (s *String) ReadASN1Bytes(out *[]byte, tag asn1.Tag) bool {
   591  	return s.ReadASN1((*String)(out), tag)
   592  }
   593  
   594  // ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including
   595  // tag and length bytes) into out, and advances. The element must match the
   596  // given tag. It reports whether the read was successful.
   597  //
   598  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   599  func (s *String) ReadASN1(out *String, tag asn1.Tag) bool {
   600  	var t asn1.Tag
   601  	if !s.ReadAnyASN1(out, &t) || t != tag {
   602  		return false
   603  	}
   604  	return true
   605  }
   606  
   607  // ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including
   608  // tag and length bytes) into out, and advances. The element must match the
   609  // given tag. It reports whether the read was successful.
   610  //
   611  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   612  func (s *String) ReadASN1Element(out *String, tag asn1.Tag) bool {
   613  	var t asn1.Tag
   614  	if !s.ReadAnyASN1Element(out, &t) || t != tag {
   615  		return false
   616  	}
   617  	return true
   618  }
   619  
   620  // ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including
   621  // tag and length bytes) into out, sets outTag to its tag, and advances.
   622  // It reports whether the read was successful.
   623  //
   624  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   625  func (s *String) ReadAnyASN1(out *String, outTag *asn1.Tag) bool {
   626  	return s.readASN1(out, outTag, true /* skip header */)
   627  }
   628  
   629  // ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element
   630  // (including tag and length bytes) into out, sets outTag to is tag, and
   631  // advances. It reports whether the read was successful.
   632  //
   633  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   634  func (s *String) ReadAnyASN1Element(out *String, outTag *asn1.Tag) bool {
   635  	return s.readASN1(out, outTag, false /* include header */)
   636  }
   637  
   638  // PeekASN1Tag reports whether the next ASN.1 value on the string starts with
   639  // the given tag.
   640  func (s String) PeekASN1Tag(tag asn1.Tag) bool {
   641  	if len(s) == 0 {
   642  		return false
   643  	}
   644  	return asn1.Tag(s[0]) == tag
   645  }
   646  
   647  // SkipASN1 reads and discards an ASN.1 element with the given tag. It
   648  // reports whether the operation was successful.
   649  func (s *String) SkipASN1(tag asn1.Tag) bool {
   650  	var unused String
   651  	return s.ReadASN1(&unused, tag)
   652  }
   653  
   654  // ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.1
   655  // element (not including tag and length bytes) tagged with the given tag into
   656  // out. It stores whether an element with the tag was found in outPresent,
   657  // unless outPresent is nil. It reports whether the read was successful.
   658  func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag asn1.Tag) bool {
   659  	present := s.PeekASN1Tag(tag)
   660  	if outPresent != nil {
   661  		*outPresent = present
   662  	}
   663  	if present && !s.ReadASN1(out, tag) {
   664  		return false
   665  	}
   666  	return true
   667  }
   668  
   669  // SkipOptionalASN1 advances s over an ASN.1 element with the given tag, or
   670  // else leaves s unchanged. It reports whether the operation was successful.
   671  func (s *String) SkipOptionalASN1(tag asn1.Tag) bool {
   672  	if !s.PeekASN1Tag(tag) {
   673  		return true
   674  	}
   675  	var unused String
   676  	return s.ReadASN1(&unused, tag)
   677  }
   678  
   679  // ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER explicitly
   680  // tagged with tag into out and advances. If no element with a matching tag is
   681  // present, it writes defaultValue into out instead. Otherwise, it behaves like
   682  // ReadASN1Integer.
   683  func (s *String) ReadOptionalASN1Integer(out interface{}, tag asn1.Tag, defaultValue interface{}) bool {
   684  	var present bool
   685  	var i String
   686  	if !s.ReadOptionalASN1(&i, &present, tag) {
   687  		return false
   688  	}
   689  	if !present {
   690  		switch out.(type) {
   691  		case *int, *int8, *int16, *int32, *int64,
   692  			*uint, *uint8, *uint16, *uint32, *uint64, *[]byte:
   693  			reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue))
   694  		case *big.Int:
   695  			if defaultValue, ok := defaultValue.(*big.Int); ok {
   696  				out.(*big.Int).Set(defaultValue)
   697  			} else {
   698  				panic("out points to big.Int, but defaultValue does not")
   699  			}
   700  		default:
   701  			panic("invalid integer type")
   702  		}
   703  		return true
   704  	}
   705  	if !i.ReadASN1Integer(out) || !i.Empty() {
   706  		return false
   707  	}
   708  	return true
   709  }
   710  
   711  // ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING
   712  // explicitly tagged with tag into out and advances. If no element with a
   713  // matching tag is present, it sets "out" to nil instead. It reports
   714  // whether the read was successful.
   715  func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag asn1.Tag) bool {
   716  	var present bool
   717  	var child String
   718  	if !s.ReadOptionalASN1(&child, &present, tag) {
   719  		return false
   720  	}
   721  	if outPresent != nil {
   722  		*outPresent = present
   723  	}
   724  	if present {
   725  		var oct String
   726  		if !child.ReadASN1(&oct, asn1.OCTET_STRING) || !child.Empty() {
   727  			return false
   728  		}
   729  		*out = oct
   730  	} else {
   731  		*out = nil
   732  	}
   733  	return true
   734  }
   735  
   736  // ReadOptionalASN1Boolean attempts to read an optional ASN.1 BOOLEAN
   737  // explicitly tagged with tag into out and advances. If no element with a
   738  // matching tag is present, it sets "out" to defaultValue instead. It reports
   739  // whether the read was successful.
   740  func (s *String) ReadOptionalASN1Boolean(out *bool, tag asn1.Tag, defaultValue bool) bool {
   741  	var present bool
   742  	var child String
   743  	if !s.ReadOptionalASN1(&child, &present, tag) {
   744  		return false
   745  	}
   746  
   747  	if !present {
   748  		*out = defaultValue
   749  		return true
   750  	}
   751  
   752  	return child.ReadASN1Boolean(out)
   753  }
   754  
   755  func (s *String) readASN1(out *String, outTag *asn1.Tag, skipHeader bool) bool {
   756  	if len(*s) < 2 {
   757  		return false
   758  	}
   759  	tag, lenByte := (*s)[0], (*s)[1]
   760  
   761  	if tag&0x1f == 0x1f {
   762  		// ITU-T X.690 section 8.1.2
   763  		//
   764  		// An identifier octet with a tag part of 0x1f indicates a high-tag-number
   765  		// form identifier with two or more octets. We only support tags less than
   766  		// 31 (i.e. low-tag-number form, single octet identifier).
   767  		return false
   768  	}
   769  
   770  	if outTag != nil {
   771  		*outTag = asn1.Tag(tag)
   772  	}
   773  
   774  	// ITU-T X.690 section 8.1.3
   775  	//
   776  	// Bit 8 of the first length byte indicates whether the length is short- or
   777  	// long-form.
   778  	var length, headerLen uint32 // length includes headerLen
   779  	if lenByte&0x80 == 0 {
   780  		// Short-form length (section 8.1.3.4), encoded in bits 1-7.
   781  		length = uint32(lenByte) + 2
   782  		headerLen = 2
   783  	} else {
   784  		// Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets
   785  		// used to encode the length.
   786  		lenLen := lenByte & 0x7f
   787  		var len32 uint32
   788  
   789  		if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) {
   790  			return false
   791  		}
   792  
   793  		lenBytes := String((*s)[2 : 2+lenLen])
   794  		if !lenBytes.readUnsigned(&len32, int(lenLen)) {
   795  			return false
   796  		}
   797  
   798  		// ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
   799  		// with the minimum number of octets.
   800  		if len32 < 128 {
   801  			// Length should have used short-form encoding.
   802  			return false
   803  		}
   804  		if len32>>((lenLen-1)*8) == 0 {
   805  			// Leading octet is 0. Length should have been at least one byte shorter.
   806  			return false
   807  		}
   808  
   809  		headerLen = 2 + uint32(lenLen)
   810  		if headerLen+len32 < len32 {
   811  			// Overflow.
   812  			return false
   813  		}
   814  		length = headerLen + len32
   815  	}
   816  
   817  	if int(length) < 0 || !s.ReadBytes((*[]byte)(out), int(length)) {
   818  		return false
   819  	}
   820  	if skipHeader && !out.Skip(int(headerLen)) {
   821  		panic("cryptobyte: internal error")
   822  	}
   823  
   824  	return true
   825  }
   826  

View as plain text