github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/crypto/openpgp/packet/packet.go (about)

     1  // Copyright 2011 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 packet implements parsing and serialization of OpenPGP packets, as
     6  // specified in RFC 4880.
     7  package packet // import "golang.org/x/crypto/openpgp/packet"
     8  
     9  import (
    10  	"bufio"
    11  	"crypto/aes"
    12  	"crypto/cipher"
    13  	"crypto/des"
    14  	"golang.org/x/crypto/cast5"
    15  	"golang.org/x/crypto/openpgp/errors"
    16  	"io"
    17  	"math/big"
    18  )
    19  
    20  // readFull is the same as io.ReadFull except that reading zero bytes returns
    21  // ErrUnexpectedEOF rather than EOF.
    22  func readFull(r io.Reader, buf []byte) (n int, err error) {
    23  	n, err = io.ReadFull(r, buf)
    24  	if err == io.EOF {
    25  		err = io.ErrUnexpectedEOF
    26  	}
    27  	return
    28  }
    29  
    30  // readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2.
    31  func readLength(r io.Reader) (length int64, isPartial bool, err error) {
    32  	var buf [4]byte
    33  	_, err = readFull(r, buf[:1])
    34  	if err != nil {
    35  		return
    36  	}
    37  	switch {
    38  	case buf[0] < 192:
    39  		length = int64(buf[0])
    40  	case buf[0] < 224:
    41  		length = int64(buf[0]-192) << 8
    42  		_, err = readFull(r, buf[0:1])
    43  		if err != nil {
    44  			return
    45  		}
    46  		length += int64(buf[0]) + 192
    47  	case buf[0] < 255:
    48  		length = int64(1) << (buf[0] & 0x1f)
    49  		isPartial = true
    50  	default:
    51  		_, err = readFull(r, buf[0:4])
    52  		if err != nil {
    53  			return
    54  		}
    55  		length = int64(buf[0])<<24 |
    56  			int64(buf[1])<<16 |
    57  			int64(buf[2])<<8 |
    58  			int64(buf[3])
    59  	}
    60  	return
    61  }
    62  
    63  // partialLengthReader wraps an io.Reader and handles OpenPGP partial lengths.
    64  // The continuation lengths are parsed and removed from the stream and EOF is
    65  // returned at the end of the packet. See RFC 4880, section 4.2.2.4.
    66  type partialLengthReader struct {
    67  	r         io.Reader
    68  	remaining int64
    69  	isPartial bool
    70  }
    71  
    72  func (r *partialLengthReader) Read(p []byte) (n int, err error) {
    73  	for r.remaining == 0 {
    74  		if !r.isPartial {
    75  			return 0, io.EOF
    76  		}
    77  		r.remaining, r.isPartial, err = readLength(r.r)
    78  		if err != nil {
    79  			return 0, err
    80  		}
    81  	}
    82  
    83  	toRead := int64(len(p))
    84  	if toRead > r.remaining {
    85  		toRead = r.remaining
    86  	}
    87  
    88  	n, err = r.r.Read(p[:int(toRead)])
    89  	r.remaining -= int64(n)
    90  	if n < int(toRead) && err == io.EOF {
    91  		err = io.ErrUnexpectedEOF
    92  	}
    93  	return
    94  }
    95  
    96  // partialLengthWriter writes a stream of data using OpenPGP partial lengths.
    97  // See RFC 4880, section 4.2.2.4.
    98  type partialLengthWriter struct {
    99  	w          io.WriteCloser
   100  	lengthByte [1]byte
   101  }
   102  
   103  func (w *partialLengthWriter) Write(p []byte) (n int, err error) {
   104  	for len(p) > 0 {
   105  		for power := uint(14); power < 32; power-- {
   106  			l := 1 << power
   107  			if len(p) >= l {
   108  				w.lengthByte[0] = 224 + uint8(power)
   109  				_, err = w.w.Write(w.lengthByte[:])
   110  				if err != nil {
   111  					return
   112  				}
   113  				var m int
   114  				m, err = w.w.Write(p[:l])
   115  				n += m
   116  				if err != nil {
   117  					return
   118  				}
   119  				p = p[l:]
   120  				break
   121  			}
   122  		}
   123  	}
   124  	return
   125  }
   126  
   127  func (w *partialLengthWriter) Close() error {
   128  	w.lengthByte[0] = 0
   129  	_, err := w.w.Write(w.lengthByte[:])
   130  	if err != nil {
   131  		return err
   132  	}
   133  	return w.w.Close()
   134  }
   135  
   136  // A spanReader is an io.LimitReader, but it returns ErrUnexpectedEOF if the
   137  // underlying Reader returns EOF before the limit has been reached.
   138  type spanReader struct {
   139  	r io.Reader
   140  	n int64
   141  }
   142  
   143  func (l *spanReader) Read(p []byte) (n int, err error) {
   144  	if l.n <= 0 {
   145  		return 0, io.EOF
   146  	}
   147  	if int64(len(p)) > l.n {
   148  		p = p[0:l.n]
   149  	}
   150  	n, err = l.r.Read(p)
   151  	l.n -= int64(n)
   152  	if l.n > 0 && err == io.EOF {
   153  		err = io.ErrUnexpectedEOF
   154  	}
   155  	return
   156  }
   157  
   158  // readHeader parses a packet header and returns an io.Reader which will return
   159  // the contents of the packet. See RFC 4880, section 4.2.
   160  func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) {
   161  	var buf [4]byte
   162  	_, err = io.ReadFull(r, buf[:1])
   163  	if err != nil {
   164  		return
   165  	}
   166  	if buf[0]&0x80 == 0 {
   167  		err = errors.StructuralError("tag byte does not have MSB set")
   168  		return
   169  	}
   170  	if buf[0]&0x40 == 0 {
   171  		// Old format packet
   172  		tag = packetType((buf[0] & 0x3f) >> 2)
   173  		lengthType := buf[0] & 3
   174  		if lengthType == 3 {
   175  			length = -1
   176  			contents = r
   177  			return
   178  		}
   179  		lengthBytes := 1 << lengthType
   180  		_, err = readFull(r, buf[0:lengthBytes])
   181  		if err != nil {
   182  			return
   183  		}
   184  		for i := 0; i < lengthBytes; i++ {
   185  			length <<= 8
   186  			length |= int64(buf[i])
   187  		}
   188  		contents = &spanReader{r, length}
   189  		return
   190  	}
   191  
   192  	// New format packet
   193  	tag = packetType(buf[0] & 0x3f)
   194  	length, isPartial, err := readLength(r)
   195  	if err != nil {
   196  		return
   197  	}
   198  	if isPartial {
   199  		contents = &partialLengthReader{
   200  			remaining: length,
   201  			isPartial: true,
   202  			r:         r,
   203  		}
   204  		length = -1
   205  	} else {
   206  		contents = &spanReader{r, length}
   207  	}
   208  	return
   209  }
   210  
   211  // serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section
   212  // 4.2.
   213  func serializeHeader(w io.Writer, ptype packetType, length int) (err error) {
   214  	var buf [6]byte
   215  	var n int
   216  
   217  	buf[0] = 0x80 | 0x40 | byte(ptype)
   218  	if length < 192 {
   219  		buf[1] = byte(length)
   220  		n = 2
   221  	} else if length < 8384 {
   222  		length -= 192
   223  		buf[1] = 192 + byte(length>>8)
   224  		buf[2] = byte(length)
   225  		n = 3
   226  	} else {
   227  		buf[1] = 255
   228  		buf[2] = byte(length >> 24)
   229  		buf[3] = byte(length >> 16)
   230  		buf[4] = byte(length >> 8)
   231  		buf[5] = byte(length)
   232  		n = 6
   233  	}
   234  
   235  	_, err = w.Write(buf[:n])
   236  	return
   237  }
   238  
   239  // serializeStreamHeader writes an OpenPGP packet header to w where the
   240  // length of the packet is unknown. It returns a io.WriteCloser which can be
   241  // used to write the contents of the packet. See RFC 4880, section 4.2.
   242  func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) {
   243  	var buf [1]byte
   244  	buf[0] = 0x80 | 0x40 | byte(ptype)
   245  	_, err = w.Write(buf[:])
   246  	if err != nil {
   247  		return
   248  	}
   249  	out = &partialLengthWriter{w: w}
   250  	return
   251  }
   252  
   253  // Packet represents an OpenPGP packet. Users are expected to try casting
   254  // instances of this interface to specific packet types.
   255  type Packet interface {
   256  	parse(io.Reader) error
   257  }
   258  
   259  // consumeAll reads from the given Reader until error, returning the number of
   260  // bytes read.
   261  func consumeAll(r io.Reader) (n int64, err error) {
   262  	var m int
   263  	var buf [1024]byte
   264  
   265  	for {
   266  		m, err = r.Read(buf[:])
   267  		n += int64(m)
   268  		if err == io.EOF {
   269  			err = nil
   270  			return
   271  		}
   272  		if err != nil {
   273  			return
   274  		}
   275  	}
   276  
   277  	panic("unreachable")
   278  }
   279  
   280  // packetType represents the numeric ids of the different OpenPGP packet types. See
   281  // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-2
   282  type packetType uint8
   283  
   284  const (
   285  	packetTypeEncryptedKey              packetType = 1
   286  	packetTypeSignature                 packetType = 2
   287  	packetTypeSymmetricKeyEncrypted     packetType = 3
   288  	packetTypeOnePassSignature          packetType = 4
   289  	packetTypePrivateKey                packetType = 5
   290  	packetTypePublicKey                 packetType = 6
   291  	packetTypePrivateSubkey             packetType = 7
   292  	packetTypeCompressed                packetType = 8
   293  	packetTypeSymmetricallyEncrypted    packetType = 9
   294  	packetTypeLiteralData               packetType = 11
   295  	packetTypeUserId                    packetType = 13
   296  	packetTypePublicSubkey              packetType = 14
   297  	packetTypeUserAttribute             packetType = 17
   298  	packetTypeSymmetricallyEncryptedMDC packetType = 18
   299  )
   300  
   301  // peekVersion detects the version of a public key packet about to
   302  // be read. A bufio.Reader at the original position of the io.Reader
   303  // is returned.
   304  func peekVersion(r io.Reader) (bufr *bufio.Reader, ver byte, err error) {
   305  	bufr = bufio.NewReader(r)
   306  	var verBuf []byte
   307  	if verBuf, err = bufr.Peek(1); err != nil {
   308  		return
   309  	}
   310  	ver = verBuf[0]
   311  	return
   312  }
   313  
   314  // Read reads a single OpenPGP packet from the given io.Reader. If there is an
   315  // error parsing a packet, the whole packet is consumed from the input.
   316  func Read(r io.Reader) (p Packet, err error) {
   317  	tag, _, contents, err := readHeader(r)
   318  	if err != nil {
   319  		return
   320  	}
   321  
   322  	switch tag {
   323  	case packetTypeEncryptedKey:
   324  		p = new(EncryptedKey)
   325  	case packetTypeSignature:
   326  		var version byte
   327  		// Detect signature version
   328  		if contents, version, err = peekVersion(contents); err != nil {
   329  			return
   330  		}
   331  		if version < 4 {
   332  			p = new(SignatureV3)
   333  		} else {
   334  			p = new(Signature)
   335  		}
   336  	case packetTypeSymmetricKeyEncrypted:
   337  		p = new(SymmetricKeyEncrypted)
   338  	case packetTypeOnePassSignature:
   339  		p = new(OnePassSignature)
   340  	case packetTypePrivateKey, packetTypePrivateSubkey:
   341  		pk := new(PrivateKey)
   342  		if tag == packetTypePrivateSubkey {
   343  			pk.IsSubkey = true
   344  		}
   345  		p = pk
   346  	case packetTypePublicKey, packetTypePublicSubkey:
   347  		var version byte
   348  		if contents, version, err = peekVersion(contents); err != nil {
   349  			return
   350  		}
   351  		isSubkey := tag == packetTypePublicSubkey
   352  		if version < 4 {
   353  			p = &PublicKeyV3{IsSubkey: isSubkey}
   354  		} else {
   355  			p = &PublicKey{IsSubkey: isSubkey}
   356  		}
   357  	case packetTypeCompressed:
   358  		p = new(Compressed)
   359  	case packetTypeSymmetricallyEncrypted:
   360  		p = new(SymmetricallyEncrypted)
   361  	case packetTypeLiteralData:
   362  		p = new(LiteralData)
   363  	case packetTypeUserId:
   364  		p = new(UserId)
   365  	case packetTypeUserAttribute:
   366  		p = new(UserAttribute)
   367  	case packetTypeSymmetricallyEncryptedMDC:
   368  		se := new(SymmetricallyEncrypted)
   369  		se.MDC = true
   370  		p = se
   371  	default:
   372  		err = errors.UnknownPacketTypeError(tag)
   373  	}
   374  	if p != nil {
   375  		err = p.parse(contents)
   376  	}
   377  	if err != nil {
   378  		consumeAll(contents)
   379  	}
   380  	return
   381  }
   382  
   383  // SignatureType represents the different semantic meanings of an OpenPGP
   384  // signature. See RFC 4880, section 5.2.1.
   385  type SignatureType uint8
   386  
   387  const (
   388  	SigTypeBinary            SignatureType = 0
   389  	SigTypeText                            = 1
   390  	SigTypeGenericCert                     = 0x10
   391  	SigTypePersonaCert                     = 0x11
   392  	SigTypeCasualCert                      = 0x12
   393  	SigTypePositiveCert                    = 0x13
   394  	SigTypeSubkeyBinding                   = 0x18
   395  	SigTypePrimaryKeyBinding               = 0x19
   396  	SigTypeDirectSignature                 = 0x1F
   397  	SigTypeKeyRevocation                   = 0x20
   398  	SigTypeSubkeyRevocation                = 0x28
   399  )
   400  
   401  // PublicKeyAlgorithm represents the different public key system specified for
   402  // OpenPGP. See
   403  // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-12
   404  type PublicKeyAlgorithm uint8
   405  
   406  const (
   407  	PubKeyAlgoRSA            PublicKeyAlgorithm = 1
   408  	PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2
   409  	PubKeyAlgoRSASignOnly    PublicKeyAlgorithm = 3
   410  	PubKeyAlgoElGamal        PublicKeyAlgorithm = 16
   411  	PubKeyAlgoDSA            PublicKeyAlgorithm = 17
   412  	// RFC 6637, Section 5.
   413  	PubKeyAlgoECDH  PublicKeyAlgorithm = 18
   414  	PubKeyAlgoECDSA PublicKeyAlgorithm = 19
   415  )
   416  
   417  // CanEncrypt returns true if it's possible to encrypt a message to a public
   418  // key of the given type.
   419  func (pka PublicKeyAlgorithm) CanEncrypt() bool {
   420  	switch pka {
   421  	case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal:
   422  		return true
   423  	}
   424  	return false
   425  }
   426  
   427  // CanSign returns true if it's possible for a public key of the given type to
   428  // sign a message.
   429  func (pka PublicKeyAlgorithm) CanSign() bool {
   430  	switch pka {
   431  	case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA:
   432  		return true
   433  	}
   434  	return false
   435  }
   436  
   437  // CipherFunction represents the different block ciphers specified for OpenPGP. See
   438  // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13
   439  type CipherFunction uint8
   440  
   441  const (
   442  	Cipher3DES   CipherFunction = 2
   443  	CipherCAST5  CipherFunction = 3
   444  	CipherAES128 CipherFunction = 7
   445  	CipherAES192 CipherFunction = 8
   446  	CipherAES256 CipherFunction = 9
   447  )
   448  
   449  // KeySize returns the key size, in bytes, of cipher.
   450  func (cipher CipherFunction) KeySize() int {
   451  	switch cipher {
   452  	case Cipher3DES:
   453  		return 24
   454  	case CipherCAST5:
   455  		return cast5.KeySize
   456  	case CipherAES128:
   457  		return 16
   458  	case CipherAES192:
   459  		return 24
   460  	case CipherAES256:
   461  		return 32
   462  	}
   463  	return 0
   464  }
   465  
   466  // blockSize returns the block size, in bytes, of cipher.
   467  func (cipher CipherFunction) blockSize() int {
   468  	switch cipher {
   469  	case Cipher3DES:
   470  		return des.BlockSize
   471  	case CipherCAST5:
   472  		return 8
   473  	case CipherAES128, CipherAES192, CipherAES256:
   474  		return 16
   475  	}
   476  	return 0
   477  }
   478  
   479  // new returns a fresh instance of the given cipher.
   480  func (cipher CipherFunction) new(key []byte) (block cipher.Block) {
   481  	switch cipher {
   482  	case Cipher3DES:
   483  		block, _ = des.NewTripleDESCipher(key)
   484  	case CipherCAST5:
   485  		block, _ = cast5.NewCipher(key)
   486  	case CipherAES128, CipherAES192, CipherAES256:
   487  		block, _ = aes.NewCipher(key)
   488  	}
   489  	return
   490  }
   491  
   492  // readMPI reads a big integer from r. The bit length returned is the bit
   493  // length that was specified in r. This is preserved so that the integer can be
   494  // reserialized exactly.
   495  func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) {
   496  	var buf [2]byte
   497  	_, err = readFull(r, buf[0:])
   498  	if err != nil {
   499  		return
   500  	}
   501  	bitLength = uint16(buf[0])<<8 | uint16(buf[1])
   502  	numBytes := (int(bitLength) + 7) / 8
   503  	mpi = make([]byte, numBytes)
   504  	_, err = readFull(r, mpi)
   505  	return
   506  }
   507  
   508  // mpiLength returns the length of the given *big.Int when serialized as an
   509  // MPI.
   510  func mpiLength(n *big.Int) (mpiLengthInBytes int) {
   511  	mpiLengthInBytes = 2 /* MPI length */
   512  	mpiLengthInBytes += (n.BitLen() + 7) / 8
   513  	return
   514  }
   515  
   516  // writeMPI serializes a big integer to w.
   517  func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
   518  	_, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)})
   519  	if err == nil {
   520  		_, err = w.Write(mpiBytes)
   521  	}
   522  	return
   523  }
   524  
   525  // writeBig serializes a *big.Int to w.
   526  func writeBig(w io.Writer, i *big.Int) error {
   527  	return writeMPI(w, uint16(i.BitLen()), i.Bytes())
   528  }
   529  
   530  // CompressionAlgo Represents the different compression algorithms
   531  // supported by OpenPGP (except for BZIP2, which is not currently
   532  // supported). See Section 9.3 of RFC 4880.
   533  type CompressionAlgo uint8
   534  
   535  const (
   536  	CompressionNone CompressionAlgo = 0
   537  	CompressionZIP  CompressionAlgo = 1
   538  	CompressionZLIB CompressionAlgo = 2
   539  )