github.com/devops-filetransfer/sshego@v7.0.4+incompatible/_vendor/golang.org/x/crypto/cryptobyte/asn1.go (about)

     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"
     9  	"fmt"
    10  	"math/big"
    11  	"reflect"
    12  	"time"
    13  )
    14  
    15  // This file contains ASN.1-related methods for String and Builder.
    16  
    17  // Tag represents an ASN.1 tag number and class (together also referred to as
    18  // identifier octets). Methods in this package only support the low-tag-number
    19  // form, i.e. a single identifier octet with bits 7-8 encoding the class and
    20  // bits 1-6 encoding the tag number.
    21  type Tag uint8
    22  
    23  // Contructed returns t with the context-specific class bit set.
    24  func (t Tag) ContextSpecific() Tag { return t | 0x80 }
    25  
    26  // Contructed returns t with the constructed class bit set.
    27  func (t Tag) Constructed() Tag { return t | 0x20 }
    28  
    29  // Builder
    30  
    31  // AddASN1Int64 appends a DER-encoded ASN.1 INTEGER.
    32  func (b *Builder) AddASN1Int64(v int64) {
    33  	b.addASN1Signed(asn1.TagInteger, v)
    34  }
    35  
    36  // AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION.
    37  func (b *Builder) AddASN1Enum(v int64) {
    38  	b.addASN1Signed(asn1.TagEnum, v)
    39  }
    40  
    41  func (b *Builder) addASN1Signed(tag Tag, v int64) {
    42  	b.AddASN1(tag, func(c *Builder) {
    43  		length := 1
    44  		for i := v; i >= 0x80 || i < -0x80; i >>= 8 {
    45  			length++
    46  		}
    47  
    48  		for ; length > 0; length-- {
    49  			i := v >> uint((length-1)*8) & 0xff
    50  			c.AddUint8(uint8(i))
    51  		}
    52  	})
    53  }
    54  
    55  // AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER.
    56  func (b *Builder) AddASN1Uint64(v uint64) {
    57  	b.AddASN1(asn1.TagInteger, func(c *Builder) {
    58  		length := 1
    59  		for i := v; i >= 0x80; i >>= 8 {
    60  			length++
    61  		}
    62  
    63  		for ; length > 0; length-- {
    64  			i := v >> uint((length-1)*8) & 0xff
    65  			c.AddUint8(uint8(i))
    66  		}
    67  	})
    68  }
    69  
    70  // AddASN1BigInt appends a DER-encoded ASN.1 INTEGER.
    71  func (b *Builder) AddASN1BigInt(n *big.Int) {
    72  	if b.err != nil {
    73  		return
    74  	}
    75  
    76  	b.AddASN1(asn1.TagInteger, func(c *Builder) {
    77  		if n.Sign() < 0 {
    78  			// A negative number has to be converted to two's-complement form. So we
    79  			// invert and subtract 1. If the most-significant-bit isn't set then
    80  			// we'll need to pad the beginning with 0xff in order to keep the number
    81  			// negative.
    82  			nMinus1 := new(big.Int).Neg(n)
    83  			nMinus1.Sub(nMinus1, bigOne)
    84  			bytes := nMinus1.Bytes()
    85  			for i := range bytes {
    86  				bytes[i] ^= 0xff
    87  			}
    88  			if bytes[0]&0x80 == 0 {
    89  				c.add(0xff)
    90  			}
    91  			c.add(bytes...)
    92  		} else if n.Sign() == 0 {
    93  			c.add(0)
    94  		} else {
    95  			bytes := n.Bytes()
    96  			if bytes[0]&0x80 != 0 {
    97  				c.add(0)
    98  			}
    99  			c.add(bytes...)
   100  		}
   101  	})
   102  }
   103  
   104  // AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING.
   105  func (b *Builder) AddASN1OctetString(bytes []byte) {
   106  	b.AddASN1(asn1.TagOctetString, func(c *Builder) {
   107  		c.AddBytes(bytes)
   108  	})
   109  }
   110  
   111  const generalizedTimeFormatStr = "20060102150405Z0700"
   112  
   113  // AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME.
   114  func (b *Builder) AddASN1GeneralizedTime(t time.Time) {
   115  	if t.Year() < 0 || t.Year() > 9999 {
   116  		b.err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", t)
   117  		return
   118  	}
   119  	b.AddASN1(asn1.TagGeneralizedTime, func(c *Builder) {
   120  		c.AddBytes([]byte(t.Format(generalizedTimeFormatStr)))
   121  	})
   122  }
   123  
   124  // AddASN1BitString appends a DER-encoded ASN.1 BIT STRING.
   125  func (b *Builder) AddASN1BitString(s asn1.BitString) {
   126  	// TODO(martinkr): Implement.
   127  	b.MarshalASN1(s)
   128  }
   129  
   130  // MarshalASN1 calls asn1.Marshal on its input and appends the result if
   131  // successful or records an error if one occurred.
   132  func (b *Builder) MarshalASN1(v interface{}) {
   133  	// NOTE(martinkr): This is somewhat of a hack to allow propagation of
   134  	// asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a
   135  	// value embedded into a struct, its tag information is lost.
   136  	if b.err != nil {
   137  		return
   138  	}
   139  	bytes, err := asn1.Marshal(v)
   140  	if err != nil {
   141  		b.err = err
   142  		return
   143  	}
   144  	b.AddBytes(bytes)
   145  }
   146  
   147  // AddASN1 appends an ASN.1 object. The object is prefixed with the given tag.
   148  // Tags greater than 30 are not supported and result in an error (i.e.
   149  // low-tag-number form only). The child builder passed to the
   150  // BuilderContinuation can be used to build the content of the ASN.1 object.
   151  func (b *Builder) AddASN1(tag Tag, f BuilderContinuation) {
   152  	if b.err != nil {
   153  		return
   154  	}
   155  	// Identifiers with the low five bits set indicate high-tag-number format
   156  	// (two or more octets), which we don't support.
   157  	if tag&0x1f == 0x1f {
   158  		b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag)
   159  		return
   160  	}
   161  	b.AddUint8(uint8(tag))
   162  	b.addLengthPrefixed(1, true, f)
   163  }
   164  
   165  // String
   166  
   167  var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem()
   168  
   169  // ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does
   170  // not point to an integer or to a big.Int, it panics. It returns true on
   171  // success and false on error.
   172  func (s *String) ReadASN1Integer(out interface{}) bool {
   173  	if reflect.TypeOf(out).Kind() != reflect.Ptr {
   174  		panic("out is not a pointer")
   175  	}
   176  	switch reflect.ValueOf(out).Elem().Kind() {
   177  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   178  		var i int64
   179  		if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) {
   180  			return false
   181  		}
   182  		reflect.ValueOf(out).Elem().SetInt(i)
   183  		return true
   184  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   185  		var u uint64
   186  		if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) {
   187  			return false
   188  		}
   189  		reflect.ValueOf(out).Elem().SetUint(u)
   190  		return true
   191  	case reflect.Struct:
   192  		if reflect.TypeOf(out).Elem() == bigIntType {
   193  			return s.readASN1BigInt(out.(*big.Int))
   194  		}
   195  	}
   196  	panic("out does not point to an integer type")
   197  }
   198  
   199  func checkASN1Integer(bytes []byte) bool {
   200  	if len(bytes) == 0 {
   201  		// An INTEGER is encoded with at least one octet.
   202  		return false
   203  	}
   204  	if len(bytes) == 1 {
   205  		return true
   206  	}
   207  	if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 {
   208  		// Value is not minimally encoded.
   209  		return false
   210  	}
   211  	return true
   212  }
   213  
   214  var bigOne = big.NewInt(1)
   215  
   216  func (s *String) readASN1BigInt(out *big.Int) bool {
   217  	var bytes String
   218  	if !s.ReadASN1(&bytes, asn1.TagInteger) || !checkASN1Integer(bytes) {
   219  		return false
   220  	}
   221  	if bytes[0]&0x80 == 0x80 {
   222  		// Negative number.
   223  		neg := make([]byte, len(bytes))
   224  		for i, b := range bytes {
   225  			neg[i] = ^b
   226  		}
   227  		out.SetBytes(neg)
   228  		out.Add(out, bigOne)
   229  		out.Neg(out)
   230  	} else {
   231  		out.SetBytes(bytes)
   232  	}
   233  	return true
   234  }
   235  
   236  func (s *String) readASN1Int64(out *int64) bool {
   237  	var bytes String
   238  	if !s.ReadASN1(&bytes, asn1.TagInteger) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) {
   239  		return false
   240  	}
   241  	return true
   242  }
   243  
   244  func asn1Signed(out *int64, n []byte) bool {
   245  	length := len(n)
   246  	if length > 8 {
   247  		return false
   248  	}
   249  	for i := 0; i < length; i++ {
   250  		*out <<= 8
   251  		*out |= int64(n[i])
   252  	}
   253  	// Shift up and down in order to sign extend the result.
   254  	*out <<= 64 - uint8(length)*8
   255  	*out >>= 64 - uint8(length)*8
   256  	return true
   257  }
   258  
   259  func (s *String) readASN1Uint64(out *uint64) bool {
   260  	var bytes String
   261  	if !s.ReadASN1(&bytes, asn1.TagInteger) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) {
   262  		return false
   263  	}
   264  	return true
   265  }
   266  
   267  func asn1Unsigned(out *uint64, n []byte) bool {
   268  	length := len(n)
   269  	if length > 9 || length == 9 && n[0] != 0 {
   270  		// Too large for uint64.
   271  		return false
   272  	}
   273  	if n[0]&0x80 != 0 {
   274  		// Negative number.
   275  		return false
   276  	}
   277  	for i := 0; i < length; i++ {
   278  		*out <<= 8
   279  		*out |= uint64(n[i])
   280  	}
   281  	return true
   282  }
   283  
   284  // ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It returns
   285  // true on success and false on error.
   286  func (s *String) ReadASN1Enum(out *int) bool {
   287  	var bytes String
   288  	var i int64
   289  	if !s.ReadASN1(&bytes, asn1.TagEnum) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) {
   290  		return false
   291  	}
   292  	if int64(int(i)) != i {
   293  		return false
   294  	}
   295  	*out = int(i)
   296  	return true
   297  }
   298  
   299  func (s *String) readBase128Int(out *int) bool {
   300  	ret := 0
   301  	for i := 0; len(*s) > 0; i++ {
   302  		if i == 4 {
   303  			return false
   304  		}
   305  		ret <<= 7
   306  		b := s.read(1)[0]
   307  		ret |= int(b & 0x7f)
   308  		if b&0x80 == 0 {
   309  			*out = ret
   310  			return true
   311  		}
   312  	}
   313  	return false // truncated
   314  }
   315  
   316  // ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and
   317  // advances. It returns true on success and false on error.
   318  func (s *String) ReadASN1ObjectIdentifier(out *asn1.ObjectIdentifier) bool {
   319  	var bytes String
   320  	if !s.ReadASN1(&bytes, asn1.TagOID) || len(bytes) == 0 {
   321  		return false
   322  	}
   323  
   324  	// In the worst case, we get two elements from the first byte (which is
   325  	// encoded differently) and then every varint is a single byte long.
   326  	components := make([]int, len(bytes)+1)
   327  
   328  	// The first varint is 40*value1 + value2:
   329  	// According to this packing, value1 can take the values 0, 1 and 2 only.
   330  	// When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
   331  	// then there are no restrictions on value2.
   332  	var v int
   333  	if !bytes.readBase128Int(&v) {
   334  		return false
   335  	}
   336  	if v < 80 {
   337  		components[0] = v / 40
   338  		components[1] = v % 40
   339  	} else {
   340  		components[0] = 2
   341  		components[1] = v - 80
   342  	}
   343  
   344  	i := 2
   345  	for ; len(bytes) > 0; i++ {
   346  		if !bytes.readBase128Int(&v) {
   347  			return false
   348  		}
   349  		components[i] = v
   350  	}
   351  	*out = components[:i]
   352  	return true
   353  }
   354  
   355  // ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and
   356  // advances. It returns true on success and false on error.
   357  func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool {
   358  	var bytes String
   359  	if !s.ReadASN1(&bytes, asn1.TagGeneralizedTime) {
   360  		return false
   361  	}
   362  	t := string(bytes)
   363  	res, err := time.Parse(generalizedTimeFormatStr, t)
   364  	if err != nil {
   365  		return false
   366  	}
   367  	if serialized := res.Format(generalizedTimeFormatStr); serialized != t {
   368  		return false
   369  	}
   370  	*out = res
   371  	return true
   372  }
   373  
   374  // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It
   375  // returns true on success and false on error.
   376  func (s *String) ReadASN1BitString(out *asn1.BitString) bool {
   377  	var bytes String
   378  	if !s.ReadASN1(&bytes, asn1.TagBitString) || len(bytes) == 0 {
   379  		return false
   380  	}
   381  
   382  	paddingBits := uint8(bytes[0])
   383  	bytes = bytes[1:]
   384  	if paddingBits > 7 ||
   385  		len(bytes) == 0 && paddingBits != 0 ||
   386  		len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 {
   387  		return false
   388  	}
   389  
   390  	out.BitLength = len(bytes)*8 - int(paddingBits)
   391  	out.Bytes = bytes
   392  	return true
   393  }
   394  
   395  // ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including
   396  // tag and length bytes) into out, and advances. The element must match the
   397  // given tag. It returns true on success and false on error.
   398  func (s *String) ReadASN1Bytes(out *[]byte, tag Tag) bool {
   399  	return s.ReadASN1((*String)(out), tag)
   400  }
   401  
   402  // ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including
   403  // tag and length bytes) into out, and advances. The element must match the
   404  // given tag. It returns true on success and false on error.
   405  //
   406  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   407  func (s *String) ReadASN1(out *String, tag Tag) bool {
   408  	var t Tag
   409  	if !s.ReadAnyASN1(out, &t) || t != tag {
   410  		return false
   411  	}
   412  	return true
   413  }
   414  
   415  // ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including
   416  // tag and length bytes) into out, and advances. The element must match the
   417  // given tag. It returns true on success and false on error.
   418  //
   419  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   420  func (s *String) ReadASN1Element(out *String, tag Tag) bool {
   421  	var t Tag
   422  	if !s.ReadAnyASN1Element(out, &t) || t != tag {
   423  		return false
   424  	}
   425  	return true
   426  }
   427  
   428  // ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including
   429  // tag and length bytes) into out, sets outTag to its tag, and advances. It
   430  // returns true on success and false on error.
   431  //
   432  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   433  func (s *String) ReadAnyASN1(out *String, outTag *Tag) bool {
   434  	return s.readASN1(out, outTag, true /* skip header */)
   435  }
   436  
   437  // ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element
   438  // (including tag and length bytes) into out, sets outTag to is tag, and
   439  // advances. It returns true on success and false on error.
   440  //
   441  // Tags greater than 30 are not supported (i.e. low-tag-number format only).
   442  func (s *String) ReadAnyASN1Element(out *String, outTag *Tag) bool {
   443  	return s.readASN1(out, outTag, false /* include header */)
   444  }
   445  
   446  // PeekASN1Tag returns true if the next ASN.1 value on the string starts with
   447  // the given tag.
   448  func (s String) PeekASN1Tag(tag Tag) bool {
   449  	if len(s) == 0 {
   450  		return false
   451  	}
   452  	return Tag(s[0]) == tag
   453  }
   454  
   455  // ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.Element
   456  // (not including tag and length bytes) tagged with the given tag into out. It
   457  // stores whether an element with the tag was found in outPresent, unless
   458  // outPresent is nil. It returns true on success and false on error.
   459  func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag Tag) bool {
   460  	present := s.PeekASN1Tag(tag)
   461  	if outPresent != nil {
   462  		*outPresent = present
   463  	}
   464  	if present && !s.ReadASN1(out, tag) {
   465  		return false
   466  	}
   467  	return true
   468  }
   469  
   470  // ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER
   471  // explicitly tagged with tag into out and advances. If no element with a
   472  // matching tag is present, it writes defaultValue into out instead. If out
   473  // does not point to an integer or to a big.Int, it panics. It returns true on
   474  // success and false on error.
   475  func (s *String) ReadOptionalASN1Integer(out interface{}, tag Tag, defaultValue interface{}) bool {
   476  	if reflect.TypeOf(out).Kind() != reflect.Ptr {
   477  		panic("out is not a pointer")
   478  	}
   479  	var present bool
   480  	var i String
   481  	if !s.ReadOptionalASN1(&i, &present, tag) {
   482  		return false
   483  	}
   484  	if !present {
   485  		switch reflect.ValueOf(out).Elem().Kind() {
   486  		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   487  			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   488  			reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue))
   489  		case reflect.Struct:
   490  			if reflect.TypeOf(out).Elem() != bigIntType {
   491  				panic("invalid integer type")
   492  			}
   493  			if reflect.TypeOf(defaultValue).Kind() != reflect.Ptr ||
   494  				reflect.TypeOf(defaultValue).Elem() != bigIntType {
   495  				panic("out points to big.Int, but defaultValue does not")
   496  			}
   497  			out.(*big.Int).Set(defaultValue.(*big.Int))
   498  		default:
   499  			panic("invalid integer type")
   500  		}
   501  		return true
   502  	}
   503  	if !i.ReadASN1Integer(out) || !i.Empty() {
   504  		return false
   505  	}
   506  	return true
   507  }
   508  
   509  // ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING
   510  // explicitly tagged with tag into out and advances. If no element with a
   511  // matching tag is present, it writes defaultValue into out instead. It returns
   512  // true on success and false on error.
   513  func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag Tag) bool {
   514  	var present bool
   515  	var child String
   516  	if !s.ReadOptionalASN1(&child, &present, tag) {
   517  		return false
   518  	}
   519  	if outPresent != nil {
   520  		*outPresent = present
   521  	}
   522  	if present {
   523  		var oct String
   524  		if !child.ReadASN1(&oct, asn1.TagOctetString) || !child.Empty() {
   525  			return false
   526  		}
   527  		*out = oct
   528  	} else {
   529  		*out = nil
   530  	}
   531  	return true
   532  }
   533  
   534  func (s *String) readASN1(out *String, outTag *Tag, skipHeader bool) bool {
   535  	if len(*s) < 2 {
   536  		return false
   537  	}
   538  	tag, lenByte := (*s)[0], (*s)[1]
   539  
   540  	if tag&0x1f == 0x1f {
   541  		// ITU-T X.690 section 8.1.2
   542  		//
   543  		// An identifier octet with a tag part of 0x1f indicates a high-tag-number
   544  		// form identifier with two or more octets. We only support tags less than
   545  		// 31 (i.e. low-tag-number form, single octet identifier).
   546  		return false
   547  	}
   548  
   549  	if outTag != nil {
   550  		*outTag = Tag(tag)
   551  	}
   552  
   553  	// ITU-T X.690 section 8.1.3
   554  	//
   555  	// Bit 8 of the first length byte indicates whether the length is short- or
   556  	// long-form.
   557  	var length, headerLen uint32 // length includes headerLen
   558  	if lenByte&0x80 == 0 {
   559  		// Short-form length (section 8.1.3.4), encoded in bits 1-7.
   560  		length = uint32(lenByte) + 2
   561  		headerLen = 2
   562  	} else {
   563  		// Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets
   564  		// used to encode the length.
   565  		lenLen := lenByte & 0x7f
   566  		var len32 uint32
   567  
   568  		if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) {
   569  			return false
   570  		}
   571  
   572  		lenBytes := String((*s)[2 : 2+lenLen])
   573  		if !lenBytes.readUnsigned(&len32, int(lenLen)) {
   574  			return false
   575  		}
   576  
   577  		// ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
   578  		// with the minimum number of octets.
   579  		if len32 < 128 {
   580  			// Length should have used short-form encoding.
   581  			return false
   582  		}
   583  		if len32>>((lenLen-1)*8) == 0 {
   584  			// Leading octet is 0. Length should have been at least one byte shorter.
   585  			return false
   586  		}
   587  
   588  		headerLen = 2 + uint32(lenLen)
   589  		if headerLen+len32 < len32 {
   590  			// Overflow.
   591  			return false
   592  		}
   593  		length = headerLen + len32
   594  	}
   595  
   596  	if uint32(int(length)) != length || !s.ReadBytes((*[]byte)(out), int(length)) {
   597  		return false
   598  	}
   599  	if skipHeader && !out.Skip(int(headerLen)) {
   600  		panic("cryptobyte: internal error")
   601  	}
   602  
   603  	return true
   604  }