1 // Copyright 2015 The Chromium Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "verify_signed_data.h"
16 
17 #include <openssl/bytestring.h>
18 #include <openssl/digest.h>
19 #include <openssl/err.h>
20 #include <openssl/evp.h>
21 #include <openssl/pki/signature_verify_cache.h>
22 #include <openssl/rsa.h>
23 #include <openssl/sha2.h>
24 
25 #include "cert_errors.h"
26 #include "input.h"
27 #include "parse_values.h"
28 #include "parser.h"
29 #include "signature_algorithm.h"
30 
31 BSSL_NAMESPACE_BEGIN
32 
33 namespace {
34 
SHA256UpdateWithLengthPrefixedData(SHA256_CTX * s_ctx,const uint8_t * data,uint64_t length)35 bool SHA256UpdateWithLengthPrefixedData(SHA256_CTX *s_ctx, const uint8_t *data,
36                                         uint64_t length) {
37   return (SHA256_Update(s_ctx, reinterpret_cast<uint8_t *>(&length),
38                         sizeof(length)) &&
39           SHA256_Update(s_ctx, data, length));
40 }
41 
42 // Increase to make incompatible changes in the computation of the
43 // cache key.
44 constexpr uint32_t VerifyCacheKeyVersion = 1;
45 
SignatureVerifyCacheKey(std::string_view algorithm_name,der::Input signed_data,der::Input signature_value_bytes,EVP_PKEY * public_key)46 std::string SignatureVerifyCacheKey(std::string_view algorithm_name,
47                                     der::Input signed_data,
48                                     der::Input signature_value_bytes,
49                                     EVP_PKEY *public_key) {
50   SHA256_CTX s_ctx;
51   bssl::ScopedCBB public_key_cbb;
52   uint8_t digest[SHA256_DIGEST_LENGTH];
53   uint32_t version = VerifyCacheKeyVersion;
54   if (CBB_init(public_key_cbb.get(), 128) &&
55       EVP_marshal_public_key(public_key_cbb.get(), public_key) &&
56       SHA256_Init(&s_ctx) &&
57       SHA256_Update(&s_ctx, reinterpret_cast<uint8_t *>(&version),
58                     sizeof(version)) &&
59       SHA256UpdateWithLengthPrefixedData(
60           &s_ctx, reinterpret_cast<const uint8_t *>(algorithm_name.data()),
61           algorithm_name.length()) &&
62       SHA256UpdateWithLengthPrefixedData(&s_ctx, CBB_data(public_key_cbb.get()),
63                                          CBB_len(public_key_cbb.get())) &&
64       SHA256UpdateWithLengthPrefixedData(&s_ctx, signature_value_bytes.data(),
65                                          signature_value_bytes.size()) &&
66       SHA256UpdateWithLengthPrefixedData(&s_ctx, signed_data.data(),
67                                          signed_data.size()) &&
68       SHA256_Final(digest, &s_ctx)) {
69     return std::string(reinterpret_cast<char *>(digest), sizeof(digest));
70   }
71   return std::string();
72 }
73 
74 // Place an instance of this class on the call stack to automatically clear
75 // the OpenSSL error stack on function exit.
76 // TODO(crbug.com/boringssl/38): Remove this when the library is more robust to
77 // leaving things in the error queue.
78 class OpenSSLErrStackTracer {
79  public:
~OpenSSLErrStackTracer()80   ~OpenSSLErrStackTracer() { ERR_clear_error(); }
81 };
82 
83 }  // namespace
84 
85 // Parses an RSA public key or EC public key from SPKI to an EVP_PKEY. Returns
86 // true on success.
87 //
88 // This function only recognizes the "pk-rsa" (rsaEncryption) flavor of RSA
89 // public key from RFC 5912.
90 //
91 //     pk-rsa PUBLIC-KEY ::= {
92 //      IDENTIFIER rsaEncryption
93 //      KEY RSAPublicKey
94 //      PARAMS TYPE NULL ARE absent
95 //      -- Private key format not in this module --
96 //      CERT-KEY-USAGE {digitalSignature, nonRepudiation,
97 //      keyEncipherment, dataEncipherment, keyCertSign, cRLSign}
98 //     }
99 //
100 // COMPATIBILITY NOTE: RFC 5912 and RFC 3279 are in disagreement on the value
101 // of parameters for rsaEncryption. Whereas RFC 5912 says they must be absent,
102 // RFC 3279 says they must be NULL:
103 //
104 //     The rsaEncryption OID is intended to be used in the algorithm field
105 //     of a value of type AlgorithmIdentifier.  The parameters field MUST
106 //     have ASN.1 type NULL for this algorithm identifier.
107 //
108 // Following RFC 3279 in this case.
109 //
110 // In the case of parsing EC keys, RFC 5912 describes all the ECDSA
111 // signature algorithms as requiring a public key of type "pk-ec":
112 //
113 //     pk-ec PUBLIC-KEY ::= {
114 //      IDENTIFIER id-ecPublicKey
115 //      KEY ECPoint
116 //      PARAMS TYPE ECParameters ARE required
117 //      -- Private key format not in this module --
118 //      CERT-KEY-USAGE { digitalSignature, nonRepudiation, keyAgreement,
119 //                           keyCertSign, cRLSign }
120 //     }
121 //
122 // Moreover RFC 5912 stipulates what curves are allowed. The ECParameters
123 // MUST NOT use an implicitCurve or specificCurve for PKIX:
124 //
125 //     ECParameters ::= CHOICE {
126 //      namedCurve      CURVE.&id({NamedCurve})
127 //      -- implicitCurve   NULL
128 //        -- implicitCurve MUST NOT be used in PKIX
129 //      -- specifiedCurve  SpecifiedCurve
130 //        -- specifiedCurve MUST NOT be used in PKIX
131 //        -- Details for specifiedCurve can be found in [X9.62]
132 //        -- Any future additions to this CHOICE should be coordinated
133 //        -- with ANSI X.9.
134 //     }
135 //     -- If you need to be able to decode ANSI X.9 parameter structures,
136 //     -- uncomment the implicitCurve and specifiedCurve above, and also
137 //     -- uncomment the following:
138 //     --(WITH COMPONENTS {namedCurve PRESENT})
139 //
140 // The namedCurves are extensible. The ones described by RFC 5912 are:
141 //
142 //     NamedCurve CURVE ::= {
143 //     { ID secp192r1 } | { ID sect163k1 } | { ID sect163r2 } |
144 //     { ID secp224r1 } | { ID sect233k1 } | { ID sect233r1 } |
145 //     { ID secp256r1 } | { ID sect283k1 } | { ID sect283r1 } |
146 //     { ID secp384r1 } | { ID sect409k1 } | { ID sect409r1 } |
147 //     { ID secp521r1 } | { ID sect571k1 } | { ID sect571r1 },
148 //     ... -- Extensible
149 //     }
ParsePublicKey(der::Input public_key_spki,bssl::UniquePtr<EVP_PKEY> * public_key)150 bool ParsePublicKey(der::Input public_key_spki,
151                     bssl::UniquePtr<EVP_PKEY> *public_key) {
152   // Parse the SPKI to an EVP_PKEY.
153   OpenSSLErrStackTracer err_tracer;
154 
155   CBS cbs;
156   CBS_init(&cbs, public_key_spki.data(), public_key_spki.size());
157   public_key->reset(EVP_parse_public_key(&cbs));
158   if (!*public_key || CBS_len(&cbs) != 0) {
159     public_key->reset();
160     return false;
161   }
162   return true;
163 }
164 
VerifySignedData(SignatureAlgorithm algorithm,der::Input signed_data,const der::BitString & signature_value,EVP_PKEY * public_key,SignatureVerifyCache * cache)165 bool VerifySignedData(SignatureAlgorithm algorithm, der::Input signed_data,
166                       const der::BitString &signature_value,
167                       EVP_PKEY *public_key, SignatureVerifyCache *cache) {
168   int expected_pkey_id = 1;
169   const EVP_MD *digest = nullptr;
170   bool is_rsa_pss = false;
171   std::string_view cache_algorithm_name;
172   switch (algorithm) {
173     case SignatureAlgorithm::kRsaPkcs1Sha1:
174       expected_pkey_id = EVP_PKEY_RSA;
175       digest = EVP_sha1();
176       cache_algorithm_name = "RsaPkcs1Sha1";
177       break;
178     case SignatureAlgorithm::kRsaPkcs1Sha256:
179       expected_pkey_id = EVP_PKEY_RSA;
180       digest = EVP_sha256();
181       cache_algorithm_name = "RsaPkcs1Sha256";
182       break;
183     case SignatureAlgorithm::kRsaPkcs1Sha384:
184       expected_pkey_id = EVP_PKEY_RSA;
185       digest = EVP_sha384();
186       cache_algorithm_name = "RsaPkcs1Sha384";
187       break;
188     case SignatureAlgorithm::kRsaPkcs1Sha512:
189       expected_pkey_id = EVP_PKEY_RSA;
190       digest = EVP_sha512();
191       cache_algorithm_name = "RsaPkcs1Sha512";
192       break;
193 
194     case SignatureAlgorithm::kEcdsaSha1:
195       expected_pkey_id = EVP_PKEY_EC;
196       digest = EVP_sha1();
197       cache_algorithm_name = "EcdsaSha1";
198       break;
199     case SignatureAlgorithm::kEcdsaSha256:
200       expected_pkey_id = EVP_PKEY_EC;
201       digest = EVP_sha256();
202       cache_algorithm_name = "EcdsaSha256";
203       break;
204     case SignatureAlgorithm::kEcdsaSha384:
205       expected_pkey_id = EVP_PKEY_EC;
206       digest = EVP_sha384();
207       cache_algorithm_name = "EcdsaSha384";
208       break;
209     case SignatureAlgorithm::kEcdsaSha512:
210       expected_pkey_id = EVP_PKEY_EC;
211       digest = EVP_sha512();
212       cache_algorithm_name = "EcdsaSha512";
213       break;
214 
215     case SignatureAlgorithm::kRsaPssSha256:
216       expected_pkey_id = EVP_PKEY_RSA;
217       digest = EVP_sha256();
218       cache_algorithm_name = "RsaPssSha256";
219       is_rsa_pss = true;
220       break;
221     case SignatureAlgorithm::kRsaPssSha384:
222       expected_pkey_id = EVP_PKEY_RSA;
223       digest = EVP_sha384();
224       cache_algorithm_name = "RsaPssSha384";
225       is_rsa_pss = true;
226       break;
227     case SignatureAlgorithm::kRsaPssSha512:
228       expected_pkey_id = EVP_PKEY_RSA;
229       digest = EVP_sha512();
230       cache_algorithm_name = "RsaPssSha512";
231       is_rsa_pss = true;
232       break;
233   }
234 
235   if (expected_pkey_id != EVP_PKEY_id(public_key)) {
236     return false;
237   }
238 
239   // For the supported algorithms the signature value must be a whole
240   // number of bytes.
241   if (signature_value.unused_bits() != 0) {
242     return false;
243   }
244   der::Input signature_value_bytes = signature_value.bytes();
245 
246   std::string cache_key;
247   if (cache) {
248     cache_key = SignatureVerifyCacheKey(cache_algorithm_name, signed_data,
249                                         signature_value_bytes, public_key);
250     if (!cache_key.empty()) {
251       switch (cache->Check(cache_key)) {
252         case SignatureVerifyCache::Value::kValid:
253           return true;
254         case SignatureVerifyCache::Value::kInvalid:
255           return false;
256         case SignatureVerifyCache::Value::kUnknown:
257           break;
258       }
259     }
260   }
261 
262   OpenSSLErrStackTracer err_tracer;
263 
264   bssl::ScopedEVP_MD_CTX ctx;
265   EVP_PKEY_CTX *pctx = nullptr;  // Owned by |ctx|.
266 
267   if (!EVP_DigestVerifyInit(ctx.get(), &pctx, digest, nullptr, public_key)) {
268     return false;
269   }
270 
271   if (is_rsa_pss) {
272     // All supported RSASSA-PSS algorithms match signing and MGF-1 digest. They
273     // also use the digest length as the salt length, which is specified with -1
274     // in OpenSSL's API.
275     if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
276         !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST)) {
277       return false;
278     }
279   }
280 
281   bool ret = 1 == EVP_DigestVerify(ctx.get(), signature_value_bytes.data(),
282                                    signature_value_bytes.size(),
283                                    signed_data.data(), signed_data.size());
284   if (!cache_key.empty()) {
285     cache->Store(cache_key, ret ? SignatureVerifyCache::Value::kValid
286                                 : SignatureVerifyCache::Value::kInvalid);
287   }
288 
289   return ret;
290 }
291 
VerifySignedData(SignatureAlgorithm algorithm,der::Input signed_data,const der::BitString & signature_value,der::Input public_key_spki,SignatureVerifyCache * cache)292 bool VerifySignedData(SignatureAlgorithm algorithm, der::Input signed_data,
293                       const der::BitString &signature_value,
294                       der::Input public_key_spki, SignatureVerifyCache *cache) {
295   bssl::UniquePtr<EVP_PKEY> public_key;
296   if (!ParsePublicKey(public_key_spki, &public_key)) {
297     return false;
298   }
299   return VerifySignedData(algorithm, signed_data, signature_value,
300                           public_key.get(), cache);
301 }
302 
303 BSSL_NAMESPACE_END
304