| 1 | package pkcs7 |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto" |
| 6 | "crypto/aes" |
| 7 | "crypto/cipher" |
| 8 | "crypto/des" |
| 9 | "crypto/rand" |
| 10 | "crypto/rsa" |
| 11 | "crypto/x509" |
| 12 | "crypto/x509/pkix" |
| 13 | "encoding/asn1" |
| 14 | "errors" |
| 15 | "fmt" |
| 16 | ) |
| 17 | |
| 18 | // ErrUnsupportedAlgorithm tells you when our quick dev assumptions have failed |
| 19 | var ErrUnsupportedAlgorithm = errors.New("pkcs7: cannot decrypt data: only RSA, DES, DES-EDE3, AES-256-CBC and AES-128-GCM supported") |
| 20 | |
| 21 | // ErrUnsupportedAsymmetricEncryptionAlgorithm is returned when attempting to use an unknown asymmetric encryption algorithm |
| 22 | var ErrUnsupportedAsymmetricEncryptionAlgorithm = errors.New("pkcs7: cannot decrypt data: only RSA PKCS#1 v1.5 and RSA OAEP are supported") |
| 23 | |
| 24 | // ErrUnsupportedKeyType is returned when attempting to encrypting keys using a key that's not an RSA key |
| 25 | var ErrUnsupportedKeyType = errors.New("pkcs7: only RSA keys are supported") |
| 26 | |
| 27 | // ErrNotEncryptedContent is returned when attempting to Decrypt data that is not encrypted data |
| 28 | var ErrNotEncryptedContent = errors.New("pkcs7: content data is a decryptable data type") |
| 29 | |
| 30 | // Decrypt decrypts encrypted content info for recipient cert and private key |
| 31 | func (p7 *PKCS7) Decrypt(cert *x509.Certificate, pkey crypto.PrivateKey) ([]byte, error) { |
| 32 | data, ok := p7.raw.(envelopedData) |
| 33 | if !ok { |
| 34 | return nil, ErrNotEncryptedContent |
| 35 | } |
| 36 | recipient := selectRecipientForCertificate(data.RecipientInfos, cert) |
| 37 | if recipient.EncryptedKey == nil { |
| 38 | return nil, errors.New("pkcs7: no enveloped recipient for provided certificate") |
| 39 | } |
| 40 | switch pkey := pkey.(type) { |
| 41 | case crypto.Decrypter: |
| 42 | var opts crypto.DecrypterOpts |
| 43 | switch algorithm := recipient.KeyEncryptionAlgorithm.Algorithm; { |
| 44 | case algorithm.Equal(OIDEncryptionAlgorithmRSAESOAEP): |
| 45 | hashFunc, err := getHashFuncForKeyEncryptionAlgorithm(recipient.KeyEncryptionAlgorithm) |
| 46 | if err != nil { |
| 47 | return nil, err |
| 48 | } |
| 49 | opts = &rsa.OAEPOptions{Hash: hashFunc} |
| 50 | case algorithm.Equal(OIDEncryptionAlgorithmRSA): |
| 51 | opts = &rsa.PKCS1v15DecryptOptions{} |
| 52 | default: |
| 53 | return nil, ErrUnsupportedAsymmetricEncryptionAlgorithm |
| 54 | } |
| 55 | contentKey, err := pkey.Decrypt(rand.Reader, recipient.EncryptedKey, opts) |
| 56 | if err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | return data.EncryptedContentInfo.decrypt(contentKey) |
| 60 | } |
| 61 | return nil, ErrUnsupportedAlgorithm |
| 62 | } |
| 63 | |
| 64 | // RFC 4055, 4.1 |
| 65 | // The current ASN.1 parser does not support non-integer defaults so the 'default:' tags here do nothing. |
| 66 | type rsaOAEPAlgorithmParameters struct { |
| 67 | HashFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:0,default:sha1Identifier"` |
| 68 | MaskGenFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:1,default:mgf1SHA1Identifier"` |
| 69 | PSourceFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:2,default:pSpecifiedEmptyIdentifier"` |
| 70 | } |
| 71 | |
| 72 | func getHashFuncForKeyEncryptionAlgorithm(keyEncryptionAlgorithm pkix.AlgorithmIdentifier) (crypto.Hash, error) { |
| 73 | invalidHashFunc := crypto.Hash(0) |
| 74 | params := &rsaOAEPAlgorithmParameters{ |
| 75 | HashFunc: pkix.AlgorithmIdentifier{Algorithm: OIDDigestAlgorithmSHA1}, // set default hash algorithm to SHA1 |
| 76 | } |
| 77 | var rest []byte |
| 78 | rest, err := asn1.Unmarshal(keyEncryptionAlgorithm.Parameters.FullBytes, params) |
| 79 | if err != nil { |
| 80 | return invalidHashFunc, fmt.Errorf("pkcs7: failed unmarshaling key encryption algorithm parameters: %v", err) |
| 81 | } |
| 82 | if len(rest) != 0 { |
| 83 | return invalidHashFunc, errors.New("pkcs7: trailing data after RSA OAEP parameters") |
| 84 | } |
| 85 | |
| 86 | switch { |
| 87 | case params.HashFunc.Algorithm.Equal(OIDDigestAlgorithmSHA1): |
| 88 | return crypto.SHA1, nil |
| 89 | case params.HashFunc.Algorithm.Equal(OIDDigestAlgorithmSHA224): |
| 90 | return crypto.SHA224, nil |
| 91 | case params.HashFunc.Algorithm.Equal(OIDDigestAlgorithmSHA256): |
| 92 | return crypto.SHA256, nil |
| 93 | case params.HashFunc.Algorithm.Equal(OIDDigestAlgorithmSHA384): |
| 94 | return crypto.SHA384, nil |
| 95 | case params.HashFunc.Algorithm.Equal(OIDDigestAlgorithmSHA512): |
| 96 | return crypto.SHA512, nil |
| 97 | default: |
| 98 | return invalidHashFunc, errors.New("pkcs7: unsupported hash function for RSA OAEP") |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | // DecryptUsingPSK decrypts encrypted data using caller provided |
| 103 | // pre-shared secret |
| 104 | func (p7 *PKCS7) DecryptUsingPSK(key []byte) ([]byte, error) { |
| 105 | data, ok := p7.raw.(encryptedData) |
| 106 | if !ok { |
| 107 | return nil, ErrNotEncryptedContent |
| 108 | } |
| 109 | return data.EncryptedContentInfo.decrypt(key) |
| 110 | } |
| 111 | |
| 112 | func (eci encryptedContentInfo) decrypt(key []byte) ([]byte, error) { |
| 113 | alg := eci.ContentEncryptionAlgorithm.Algorithm |
| 114 | if !alg.Equal(OIDEncryptionAlgorithmDESCBC) && |
| 115 | !alg.Equal(OIDEncryptionAlgorithmDESEDE3CBC) && |
| 116 | !alg.Equal(OIDEncryptionAlgorithmAES256CBC) && |
| 117 | !alg.Equal(OIDEncryptionAlgorithmAES128CBC) && |
| 118 | !alg.Equal(OIDEncryptionAlgorithmAES128GCM) && |
| 119 | !alg.Equal(OIDEncryptionAlgorithmAES256GCM) { |
| 120 | return nil, ErrUnsupportedAlgorithm |
| 121 | } |
| 122 | |
| 123 | // EncryptedContent can either be constructed of multple OCTET STRINGs |
| 124 | // or _be_ a tagged OCTET STRING |
| 125 | var cyphertext []byte |
| 126 | if eci.EncryptedContent.IsCompound { |
| 127 | // Complex case to concat all of the children OCTET STRINGs |
| 128 | var buf bytes.Buffer |
| 129 | cypherbytes := eci.EncryptedContent.Bytes |
| 130 | for { |
| 131 | var part []byte |
| 132 | cypherbytes, _ = asn1.Unmarshal(cypherbytes, &part) |
| 133 | buf.Write(part) |
| 134 | if cypherbytes == nil { |
| 135 | break |
| 136 | } |
| 137 | } |
| 138 | cyphertext = buf.Bytes() |
| 139 | } else { |
| 140 | // Simple case, the bytes _are_ the cyphertext |
| 141 | cyphertext = eci.EncryptedContent.Bytes |
| 142 | } |
| 143 | |
| 144 | var block cipher.Block |
| 145 | var err error |
| 146 | |
| 147 | switch { |
| 148 | case alg.Equal(OIDEncryptionAlgorithmDESCBC): |
| 149 | block, err = des.NewCipher(key) |
| 150 | case alg.Equal(OIDEncryptionAlgorithmDESEDE3CBC): |
| 151 | block, err = des.NewTripleDESCipher(key) |
| 152 | case alg.Equal(OIDEncryptionAlgorithmAES256CBC), alg.Equal(OIDEncryptionAlgorithmAES256GCM): |
| 153 | fallthrough |
| 154 | case alg.Equal(OIDEncryptionAlgorithmAES128GCM), alg.Equal(OIDEncryptionAlgorithmAES128CBC): |
| 155 | block, err = aes.NewCipher(key) |
| 156 | } |
| 157 | |
| 158 | if err != nil { |
| 159 | return nil, err |
| 160 | } |
| 161 | |
| 162 | if alg.Equal(OIDEncryptionAlgorithmAES128GCM) || alg.Equal(OIDEncryptionAlgorithmAES256GCM) { |
| 163 | params := aesGCMParameters{} |
| 164 | paramBytes := eci.ContentEncryptionAlgorithm.Parameters.Bytes |
| 165 | |
| 166 | _, err := asn1.Unmarshal(paramBytes, ¶ms) |
| 167 | if err != nil { |
| 168 | return nil, err |
| 169 | } |
| 170 | |
| 171 | gcm, err := cipher.NewGCM(block) |
| 172 | if err != nil { |
| 173 | return nil, err |
| 174 | } |
| 175 | |
| 176 | if len(params.Nonce) != gcm.NonceSize() { |
| 177 | return nil, errors.New("pkcs7: encryption algorithm parameters are incorrect") |
| 178 | } |
| 179 | if params.ICVLen != gcm.Overhead() { |
| 180 | return nil, errors.New("pkcs7: encryption algorithm parameters are incorrect") |
| 181 | } |
| 182 | |
| 183 | plaintext, err := gcm.Open(nil, params.Nonce, cyphertext, nil) |
| 184 | if err != nil { |
| 185 | return nil, err |
| 186 | } |
| 187 | |
| 188 | return plaintext, nil |
| 189 | } |
| 190 | |
| 191 | iv := eci.ContentEncryptionAlgorithm.Parameters.Bytes |
| 192 | if len(iv) != block.BlockSize() { |
| 193 | return nil, errors.New("pkcs7: encryption algorithm parameters are malformed") |
| 194 | } |
| 195 | mode := cipher.NewCBCDecrypter(block, iv) |
| 196 | plaintext := make([]byte, len(cyphertext)) |
| 197 | mode.CryptBlocks(plaintext, cyphertext) |
| 198 | if plaintext, err = unpad(plaintext, mode.BlockSize()); err != nil { |
| 199 | return nil, err |
| 200 | } |
| 201 | return plaintext, nil |
| 202 | } |
| 203 | |
| 204 | func unpad(data []byte, blocklen int) ([]byte, error) { |
| 205 | if blocklen < 1 { |
| 206 | return nil, fmt.Errorf("pkcs7: invalid blocklen %d", blocklen) |
| 207 | } |
| 208 | if len(data)%blocklen != 0 || len(data) == 0 { |
| 209 | return nil, fmt.Errorf("pkcs7: invalid data len %d", len(data)) |
| 210 | } |
| 211 | |
| 212 | // the last byte is the length of padding |
| 213 | padlen := int(data[len(data)-1]) |
| 214 | |
| 215 | // check padding integrity, all bytes should be the same |
| 216 | pad := data[len(data)-padlen:] |
| 217 | for _, padbyte := range pad { |
| 218 | if padbyte != byte(padlen) { |
| 219 | return nil, errors.New("pkcs7: invalid padding") |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | return data[:len(data)-padlen], nil |
| 224 | } |
| 225 | |
| 226 | func selectRecipientForCertificate(recipients []recipientInfo, cert *x509.Certificate) recipientInfo { |
| 227 | for _, recp := range recipients { |
| 228 | if isCertMatchForIssuerAndSerial(cert, recp.IssuerAndSerialNumber) { |
| 229 | return recp |
| 230 | } |
| 231 | } |
| 232 | return recipientInfo{} |
| 233 | } |