...

Source file src/golang.org/x/crypto/openpgp/packet/packet.go

Documentation: golang.org/x/crypto/openpgp/packet

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

View as plain text