Source file src/crypto/rsa/pkcs1v15.go

     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 rsa
     6  
     7  import (
     8  	"bytes"
     9  	"crypto"
    10  	"crypto/internal/boring"
    11  	"crypto/internal/randutil"
    12  	"crypto/subtle"
    13  	"errors"
    14  	"io"
    15  )
    16  
    17  // This file implements encryption and decryption using PKCS #1 v1.5 padding.
    18  
    19  // PKCS1v15DecryptOptions is for passing options to PKCS #1 v1.5 decryption using
    20  // the [crypto.Decrypter] interface.
    21  type PKCS1v15DecryptOptions struct {
    22  	// SessionKeyLen is the length of the session key that is being
    23  	// decrypted. If not zero, then a padding error during decryption will
    24  	// cause a random plaintext of this length to be returned rather than
    25  	// an error. These alternatives happen in constant time.
    26  	SessionKeyLen int
    27  }
    28  
    29  // EncryptPKCS1v15 encrypts the given message with RSA and the padding
    30  // scheme from PKCS #1 v1.5.  The message must be no longer than the
    31  // length of the public modulus minus 11 bytes.
    32  //
    33  // The random parameter is used as a source of entropy to ensure that
    34  // encrypting the same message twice doesn't result in the same
    35  // ciphertext. Most applications should use [crypto/rand.Reader]
    36  // as random. Note that the returned ciphertext does not depend
    37  // deterministically on the bytes read from random, and may change
    38  // between calls and/or between versions.
    39  //
    40  // WARNING: use of this function to encrypt plaintexts other than
    41  // session keys is dangerous. Use RSA OAEP in new protocols.
    42  func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error) {
    43  	randutil.MaybeReadByte(random)
    44  
    45  	if err := checkPub(pub); err != nil {
    46  		return nil, err
    47  	}
    48  	k := pub.Size()
    49  	if len(msg) > k-11 {
    50  		return nil, ErrMessageTooLong
    51  	}
    52  
    53  	if boring.Enabled && random == boring.RandReader {
    54  		bkey, err := boringPublicKey(pub)
    55  		if err != nil {
    56  			return nil, err
    57  		}
    58  		return boring.EncryptRSAPKCS1(bkey, msg)
    59  	}
    60  	boring.UnreachableExceptTests()
    61  
    62  	// EM = 0x00 || 0x02 || PS || 0x00 || M
    63  	em := make([]byte, k)
    64  	em[1] = 2
    65  	ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):]
    66  	err := nonZeroRandomBytes(ps, random)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  	em[len(em)-len(msg)-1] = 0
    71  	copy(mm, msg)
    72  
    73  	if boring.Enabled {
    74  		var bkey *boring.PublicKeyRSA
    75  		bkey, err = boringPublicKey(pub)
    76  		if err != nil {
    77  			return nil, err
    78  		}
    79  		return boring.EncryptRSANoPadding(bkey, em)
    80  	}
    81  
    82  	return encrypt(pub, em)
    83  }
    84  
    85  // DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5.
    86  // The random parameter is legacy and ignored, and it can be nil.
    87  //
    88  // Note that whether this function returns an error or not discloses secret
    89  // information. If an attacker can cause this function to run repeatedly and
    90  // learn whether each instance returned an error then they can decrypt and
    91  // forge signatures as if they had the private key. See
    92  // DecryptPKCS1v15SessionKey for a way of solving this problem.
    93  func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error) {
    94  	if err := checkPub(&priv.PublicKey); err != nil {
    95  		return nil, err
    96  	}
    97  
    98  	if boring.Enabled {
    99  		bkey, err := boringPrivateKey(priv)
   100  		if err != nil {
   101  			return nil, err
   102  		}
   103  		out, err := boring.DecryptRSAPKCS1(bkey, ciphertext)
   104  		if err != nil {
   105  			return nil, ErrDecryption
   106  		}
   107  		return out, nil
   108  	}
   109  
   110  	valid, out, index, err := decryptPKCS1v15(priv, ciphertext)
   111  	if err != nil {
   112  		return nil, err
   113  	}
   114  	if valid == 0 {
   115  		return nil, ErrDecryption
   116  	}
   117  	return out[index:], nil
   118  }
   119  
   120  // DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding
   121  // scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it
   122  // can be nil.
   123  //
   124  // DecryptPKCS1v15SessionKey returns an error if the ciphertext is the wrong
   125  // length or if the ciphertext is greater than the public modulus. Otherwise, no
   126  // error is returned. If the padding is valid, the resulting plaintext message
   127  // is copied into key. Otherwise, key is unchanged. These alternatives occur in
   128  // constant time. It is intended that the user of this function generate a
   129  // random session key beforehand and continue the protocol with the resulting
   130  // value.
   131  //
   132  // Note that if the session key is too small then it may be possible for an
   133  // attacker to brute-force it. If they can do that then they can learn whether a
   134  // random value was used (because it'll be different for the same ciphertext)
   135  // and thus whether the padding was correct. This also defeats the point of this
   136  // function. Using at least a 16-byte key will protect against this attack.
   137  //
   138  // This method implements protections against Bleichenbacher chosen ciphertext
   139  // attacks [0] described in RFC 3218 Section 2.3.2 [1]. While these protections
   140  // make a Bleichenbacher attack significantly more difficult, the protections
   141  // are only effective if the rest of the protocol which uses
   142  // DecryptPKCS1v15SessionKey is designed with these considerations in mind. In
   143  // particular, if any subsequent operations which use the decrypted session key
   144  // leak any information about the key (e.g. whether it is a static or random
   145  // key) then the mitigations are defeated. This method must be used extremely
   146  // carefully, and typically should only be used when absolutely necessary for
   147  // compatibility with an existing protocol (such as TLS) that is designed with
   148  // these properties in mind.
   149  //
   150  //   - [0] “Chosen Ciphertext Attacks Against Protocols Based on the RSA Encryption
   151  //     Standard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology (Crypto '98)
   152  //   - [1] RFC 3218, Preventing the Million Message Attack on CMS,
   153  //     https://www.rfc-editor.org/rfc/rfc3218.html
   154  func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error {
   155  	if err := checkPub(&priv.PublicKey); err != nil {
   156  		return err
   157  	}
   158  	k := priv.Size()
   159  	if k-(len(key)+3+8) < 0 {
   160  		return ErrDecryption
   161  	}
   162  
   163  	valid, em, index, err := decryptPKCS1v15(priv, ciphertext)
   164  	if err != nil {
   165  		return err
   166  	}
   167  
   168  	if len(em) != k {
   169  		// This should be impossible because decryptPKCS1v15 always
   170  		// returns the full slice.
   171  		return ErrDecryption
   172  	}
   173  
   174  	valid &= subtle.ConstantTimeEq(int32(len(em)-index), int32(len(key)))
   175  	subtle.ConstantTimeCopy(valid, key, em[len(em)-len(key):])
   176  	return nil
   177  }
   178  
   179  // decryptPKCS1v15 decrypts ciphertext using priv. It returns one or zero in
   180  // valid that indicates whether the plaintext was correctly structured.
   181  // In either case, the plaintext is returned in em so that it may be read
   182  // independently of whether it was valid in order to maintain constant memory
   183  // access patterns. If the plaintext was valid then index contains the index of
   184  // the original message in em, to allow constant time padding removal.
   185  func decryptPKCS1v15(priv *PrivateKey, ciphertext []byte) (valid int, em []byte, index int, err error) {
   186  	k := priv.Size()
   187  	if k < 11 {
   188  		err = ErrDecryption
   189  		return
   190  	}
   191  
   192  	if boring.Enabled {
   193  		var bkey *boring.PrivateKeyRSA
   194  		bkey, err = boringPrivateKey(priv)
   195  		if err != nil {
   196  			return
   197  		}
   198  		em, err = boring.DecryptRSANoPadding(bkey, ciphertext)
   199  		if err != nil {
   200  			return
   201  		}
   202  	} else {
   203  		em, err = decrypt(priv, ciphertext, noCheck)
   204  		if err != nil {
   205  			return
   206  		}
   207  	}
   208  
   209  	firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
   210  	secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2)
   211  
   212  	// The remainder of the plaintext must be a string of non-zero random
   213  	// octets, followed by a 0, followed by the message.
   214  	//   lookingForIndex: 1 iff we are still looking for the zero.
   215  	//   index: the offset of the first zero byte.
   216  	lookingForIndex := 1
   217  
   218  	for i := 2; i < len(em); i++ {
   219  		equals0 := subtle.ConstantTimeByteEq(em[i], 0)
   220  		index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index)
   221  		lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex)
   222  	}
   223  
   224  	// The PS padding must be at least 8 bytes long, and it starts two
   225  	// bytes into em.
   226  	validPS := subtle.ConstantTimeLessOrEq(2+8, index)
   227  
   228  	valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1) & validPS
   229  	index = subtle.ConstantTimeSelect(valid, index+1, 0)
   230  	return valid, em, index, nil
   231  }
   232  
   233  // nonZeroRandomBytes fills the given slice with non-zero random octets.
   234  func nonZeroRandomBytes(s []byte, random io.Reader) (err error) {
   235  	_, err = io.ReadFull(random, s)
   236  	if err != nil {
   237  		return
   238  	}
   239  
   240  	for i := 0; i < len(s); i++ {
   241  		for s[i] == 0 {
   242  			_, err = io.ReadFull(random, s[i:i+1])
   243  			if err != nil {
   244  				return
   245  			}
   246  			// In tests, the PRNG may return all zeros so we do
   247  			// this to break the loop.
   248  			s[i] ^= 0x42
   249  		}
   250  	}
   251  
   252  	return
   253  }
   254  
   255  // These are ASN1 DER structures:
   256  //
   257  //	DigestInfo ::= SEQUENCE {
   258  //	  digestAlgorithm AlgorithmIdentifier,
   259  //	  digest OCTET STRING
   260  //	}
   261  //
   262  // For performance, we don't use the generic ASN1 encoder. Rather, we
   263  // precompute a prefix of the digest value that makes a valid ASN1 DER string
   264  // with the correct contents.
   265  var hashPrefixes = map[crypto.Hash][]byte{
   266  	crypto.MD5:       {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10},
   267  	crypto.SHA1:      {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14},
   268  	crypto.SHA224:    {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
   269  	crypto.SHA256:    {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
   270  	crypto.SHA384:    {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
   271  	crypto.SHA512:    {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
   272  	crypto.MD5SHA1:   {}, // A special TLS case which doesn't use an ASN1 prefix.
   273  	crypto.RIPEMD160: {0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14},
   274  }
   275  
   276  // SignPKCS1v15 calculates the signature of hashed using
   277  // RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5.  Note that hashed must
   278  // be the result of hashing the input message using the given hash
   279  // function. If hash is zero, hashed is signed directly. This isn't
   280  // advisable except for interoperability.
   281  //
   282  // The random parameter is legacy and ignored, and it can be nil.
   283  //
   284  // This function is deterministic. Thus, if the set of possible
   285  // messages is small, an attacker may be able to build a map from
   286  // messages to signatures and identify the signed messages. As ever,
   287  // signatures provide authenticity, not confidentiality.
   288  func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
   289  	// pkcs1v15ConstructEM is called before boring.SignRSAPKCS1v15 to return
   290  	// consistent errors, including ErrMessageTooLong.
   291  	em, err := pkcs1v15ConstructEM(&priv.PublicKey, hash, hashed)
   292  	if err != nil {
   293  		return nil, err
   294  	}
   295  
   296  	if boring.Enabled {
   297  		bkey, err := boringPrivateKey(priv)
   298  		if err != nil {
   299  			return nil, err
   300  		}
   301  		return boring.SignRSAPKCS1v15(bkey, hash, hashed)
   302  	}
   303  
   304  	return decrypt(priv, em, withCheck)
   305  }
   306  
   307  func pkcs1v15ConstructEM(pub *PublicKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
   308  	// Special case: crypto.Hash(0) is used to indicate that the data is
   309  	// signed directly.
   310  	var prefix []byte
   311  	if hash != 0 {
   312  		if len(hashed) != hash.Size() {
   313  			return nil, errors.New("crypto/rsa: input must be hashed message")
   314  		}
   315  		var ok bool
   316  		prefix, ok = hashPrefixes[hash]
   317  		if !ok {
   318  			return nil, errors.New("crypto/rsa: unsupported hash function")
   319  		}
   320  	}
   321  
   322  	// EM = 0x00 || 0x01 || PS || 0x00 || T
   323  	k := pub.Size()
   324  	if k < len(prefix)+len(hashed)+2+8+1 {
   325  		return nil, ErrMessageTooLong
   326  	}
   327  	em := make([]byte, k)
   328  	em[1] = 1
   329  	for i := 2; i < k-len(prefix)-len(hashed)-1; i++ {
   330  		em[i] = 0xff
   331  	}
   332  	copy(em[k-len(prefix)-len(hashed):], prefix)
   333  	copy(em[k-len(hashed):], hashed)
   334  	return em, nil
   335  }
   336  
   337  // VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature.
   338  // hashed is the result of hashing the input message using the given hash
   339  // function and sig is the signature. A valid signature is indicated by
   340  // returning a nil error. If hash is zero then hashed is used directly. This
   341  // isn't advisable except for interoperability.
   342  //
   343  // The inputs are not considered confidential, and may leak through timing side
   344  // channels, or if an attacker has control of part of the inputs.
   345  func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {
   346  	if boring.Enabled {
   347  		bkey, err := boringPublicKey(pub)
   348  		if err != nil {
   349  			return err
   350  		}
   351  		if err := boring.VerifyRSAPKCS1v15(bkey, hash, hashed, sig); err != nil {
   352  			return ErrVerification
   353  		}
   354  		return nil
   355  	}
   356  
   357  	// RFC 8017 Section 8.2.2: If the length of the signature S is not k
   358  	// octets (where k is the length in octets of the RSA modulus n), output
   359  	// "invalid signature" and stop.
   360  	if pub.Size() != len(sig) {
   361  		return ErrVerification
   362  	}
   363  
   364  	em, err := encrypt(pub, sig)
   365  	if err != nil {
   366  		return ErrVerification
   367  	}
   368  
   369  	expected, err := pkcs1v15ConstructEM(pub, hash, hashed)
   370  	if err != nil {
   371  		return ErrVerification
   372  	}
   373  	if !bytes.Equal(em, expected) {
   374  		return ErrVerification
   375  	}
   376  
   377  	return nil
   378  }
   379  

View as plain text