Mac Partial Swap: Fix sub-layer rounding issue
[chromium-blink-merge.git] / net / cert / internal / verify_signed_data.cc
blob4d7bdefe87f5b49ca942bdff9ec116954b3cf5e6
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/cert/internal/verify_signed_data.h"
7 #include "base/logging.h"
8 #include "net/der/parse_values.h"
10 // TODO(eroman): There is no intention to implement this for non-OpenSSL. Remove
11 // this branch once the migration is complete. This could have been done as a
12 // conditional file (_openssl.cc) in the build file instead, but that is likely
13 // not worth the effort at this point.
15 #if !defined(USE_OPENSSL)
17 namespace net {
19 bool VerifySignedData(const SignatureAlgorithm& signature_algorithm,
20 const der::Input& signed_data,
21 const der::BitString& signature_value,
22 const der::Input& public_key,
23 const SignaturePolicy* policy) {
24 NOTIMPLEMENTED();
25 return false;
28 } // namespace net
30 #else
32 #include <openssl/digest.h>
33 #include <openssl/ec.h>
34 #include <openssl/ec_key.h>
35 #include <openssl/evp.h>
36 #include <openssl/rsa.h>
37 #include <openssl/x509.h>
39 #include "base/compiler_specific.h"
40 #include "crypto/openssl_util.h"
41 #include "crypto/scoped_openssl_types.h"
42 #include "net/cert/internal/signature_algorithm.h"
43 #include "net/cert/internal/signature_policy.h"
44 #include "net/der/input.h"
45 #include "net/der/parser.h"
47 namespace net {
49 namespace {
51 // Converts a DigestAlgorithm to an equivalent EVP_MD*.
52 WARN_UNUSED_RESULT bool GetDigest(DigestAlgorithm digest, const EVP_MD** out) {
53 *out = nullptr;
55 switch (digest) {
56 case DigestAlgorithm::Sha1:
57 *out = EVP_sha1();
58 break;
59 case DigestAlgorithm::Sha256:
60 *out = EVP_sha256();
61 break;
62 case DigestAlgorithm::Sha384:
63 *out = EVP_sha384();
64 break;
65 case DigestAlgorithm::Sha512:
66 *out = EVP_sha512();
67 break;
70 return *out != nullptr;
73 // Sets the RSASSA-PSS parameters on |pctx|. Returns true on success.
74 WARN_UNUSED_RESULT bool ApplyRsaPssOptions(const RsaPssParameters* params,
75 EVP_PKEY_CTX* pctx) {
76 // BoringSSL takes a signed int for the salt length, and interprets
77 // negative values in a special manner. Make sure not to silently underflow.
78 base::CheckedNumeric<int> salt_length_bytes_int(params->salt_length());
79 if (!salt_length_bytes_int.IsValid())
80 return false;
82 const EVP_MD* mgf1_hash;
83 if (!GetDigest(params->mgf1_hash(), &mgf1_hash))
84 return false;
86 return EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) &&
87 EVP_PKEY_CTX_set_rsa_mgf1_md(pctx, mgf1_hash) &&
88 EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
89 salt_length_bytes_int.ValueOrDie());
92 // TODO(eroman): This function is not strict enough. It accepts BER, other RSA
93 // OIDs, and does not check id-rsaEncryption parameters.
94 WARN_UNUSED_RESULT bool ImportPkeyFromSpki(const der::Input& spki,
95 int expected_pkey_id,
96 crypto::ScopedEVP_PKEY* pkey) {
97 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
99 const uint8_t* ptr = spki.UnsafeData();
100 pkey->reset(d2i_PUBKEY(nullptr, &ptr, spki.Length()));
101 if (!pkey->get() || ptr != spki.UnsafeData() + spki.Length() ||
102 EVP_PKEY_id(pkey->get()) != expected_pkey_id) {
103 pkey->reset();
104 return false;
107 return true;
110 // Parses an RSA public key from SPKI to an EVP_PKEY.
112 // Returns true on success.
114 // There are two flavors of RSA public key that this function should recognize
115 // from RFC 5912 (however note that pk-rsaSSA-PSS is not supported in the
116 // current implementation).
117 // TODO(eroman): Support id-RSASSA-PSS and its associated parameters.
119 // pk-rsa PUBLIC-KEY ::= {
120 // IDENTIFIER rsaEncryption
121 // KEY RSAPublicKey
122 // PARAMS TYPE NULL ARE absent
123 // -- Private key format not in this module --
124 // CERT-KEY-USAGE {digitalSignature, nonRepudiation,
125 // keyEncipherment, dataEncipherment, keyCertSign, cRLSign}
126 // }
128 // ...
130 // pk-rsaSSA-PSS PUBLIC-KEY ::= {
131 // IDENTIFIER id-RSASSA-PSS
132 // KEY RSAPublicKey
133 // PARAMS TYPE RSASSA-PSS-params ARE optional
134 // -- Private key format not in this module --
135 // CERT-KEY-USAGE { nonRepudiation, digitalSignature,
136 // keyCertSign, cRLSign }
137 // }
139 // Any RSA signature algorithm can accept a "pk-rsa" (rsaEncryption). However a
140 // "pk-rsaSSA-PSS" key is only accepted if the signature algorithm was for PSS
141 // mode:
143 // sa-rsaSSA-PSS SIGNATURE-ALGORITHM ::= {
144 // IDENTIFIER id-RSASSA-PSS
145 // PARAMS TYPE RSASSA-PSS-params ARE required
146 // HASHES { mda-sha1 | mda-sha224 | mda-sha256 | mda-sha384
147 // | mda-sha512 }
148 // PUBLIC-KEYS { pk-rsa | pk-rsaSSA-PSS }
149 // SMIME-CAPS { IDENTIFIED BY id-RSASSA-PSS }
150 // }
152 // Moreover, if a "pk-rsaSSA-PSS" key was used and it optionally provided
153 // parameters for the algorithm, they must match those of the signature
154 // algorithm.
156 // COMPATIBILITY NOTE: RFC 5912 and RFC 3279 are in disagreement on the value
157 // of parameters for rsaEncryption. Whereas RFC 5912 says they must be absent,
158 // RFC 3279 says they must be NULL:
160 // The rsaEncryption OID is intended to be used in the algorithm field
161 // of a value of type AlgorithmIdentifier. The parameters field MUST
162 // have ASN.1 type NULL for this algorithm identifier.
164 // Following RFC 3279 in this case.
165 WARN_UNUSED_RESULT bool ParseRsaKeyFromSpki(const der::Input& public_key_spki,
166 crypto::ScopedEVP_PKEY* pkey,
167 const SignaturePolicy* policy) {
168 if (!ImportPkeyFromSpki(public_key_spki, EVP_PKEY_RSA, pkey))
169 return false;
171 // Extract the modulus length from the key.
172 crypto::ScopedRSA rsa(EVP_PKEY_get1_RSA(pkey->get()));
173 if (!rsa)
174 return false;
175 unsigned int modulus_length_bits = BN_num_bits(rsa->n);
177 return policy->IsAcceptableModulusLengthForRsa(modulus_length_bits);
180 // Does signature verification using either RSA or ECDSA.
181 WARN_UNUSED_RESULT bool DoVerify(const SignatureAlgorithm& algorithm,
182 const der::Input& signed_data,
183 const der::BitString& signature_value,
184 EVP_PKEY* public_key) {
185 DCHECK(algorithm.algorithm() == SignatureAlgorithmId::RsaPkcs1 ||
186 algorithm.algorithm() == SignatureAlgorithmId::RsaPss ||
187 algorithm.algorithm() == SignatureAlgorithmId::Ecdsa);
189 // For the supported algorithms the signature value must be a whole
190 // number of bytes.
191 if (signature_value.unused_bits() != 0)
192 return false;
193 const der::Input& signature_value_bytes = signature_value.bytes();
195 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
197 crypto::ScopedEVP_MD_CTX ctx(EVP_MD_CTX_create());
198 EVP_PKEY_CTX* pctx = nullptr; // Owned by |ctx|.
200 const EVP_MD* digest;
201 if (!GetDigest(algorithm.digest(), &digest))
202 return false;
204 if (!EVP_DigestVerifyInit(ctx.get(), &pctx, digest, nullptr, public_key))
205 return false;
207 // Set the RSASSA-PSS specific options.
208 if (algorithm.algorithm() == SignatureAlgorithmId::RsaPss &&
209 !ApplyRsaPssOptions(algorithm.ParamsForRsaPss(), pctx)) {
210 return false;
213 if (!EVP_DigestVerifyUpdate(ctx.get(), signed_data.UnsafeData(),
214 signed_data.Length())) {
215 return false;
218 return 1 == EVP_DigestVerifyFinal(ctx.get(),
219 signature_value_bytes.UnsafeData(),
220 signature_value_bytes.Length());
223 // Parses an EC public key from SPKI to an EVP_PKEY.
225 // Returns true on success.
227 // RFC 5912 describes all the ECDSA signature algorithms as requiring a public
228 // key of type "pk-ec":
230 // pk-ec PUBLIC-KEY ::= {
231 // IDENTIFIER id-ecPublicKey
232 // KEY ECPoint
233 // PARAMS TYPE ECParameters ARE required
234 // -- Private key format not in this module --
235 // CERT-KEY-USAGE { digitalSignature, nonRepudiation, keyAgreement,
236 // keyCertSign, cRLSign }
237 // }
239 // Moreover RFC 5912 stipulates what curves are allowed. The ECParameters
240 // MUST NOT use an implicitCurve or specificCurve for PKIX:
242 // ECParameters ::= CHOICE {
243 // namedCurve CURVE.&id({NamedCurve})
244 // -- implicitCurve NULL
245 // -- implicitCurve MUST NOT be used in PKIX
246 // -- specifiedCurve SpecifiedCurve
247 // -- specifiedCurve MUST NOT be used in PKIX
248 // -- Details for specifiedCurve can be found in [X9.62]
249 // -- Any future additions to this CHOICE should be coordinated
250 // -- with ANSI X.9.
251 // }
252 // -- If you need to be able to decode ANSI X.9 parameter structures,
253 // -- uncomment the implicitCurve and specifiedCurve above, and also
254 // -- uncomment the following:
255 // --(WITH COMPONENTS {namedCurve PRESENT})
257 // The namedCurves are extensible. The ones described by RFC 5912 are:
259 // NamedCurve CURVE ::= {
260 // { ID secp192r1 } | { ID sect163k1 } | { ID sect163r2 } |
261 // { ID secp224r1 } | { ID sect233k1 } | { ID sect233r1 } |
262 // { ID secp256r1 } | { ID sect283k1 } | { ID sect283r1 } |
263 // { ID secp384r1 } | { ID sect409k1 } | { ID sect409r1 } |
264 // { ID secp521r1 } | { ID sect571k1 } | { ID sect571r1 },
265 // ... -- Extensible
266 // }
267 WARN_UNUSED_RESULT bool ParseEcKeyFromSpki(const der::Input& public_key_spki,
268 crypto::ScopedEVP_PKEY* pkey,
269 const SignaturePolicy* policy) {
270 if (!ImportPkeyFromSpki(public_key_spki, EVP_PKEY_EC, pkey))
271 return false;
273 // Extract the curve name.
274 crypto::ScopedEC_KEY ec(EVP_PKEY_get1_EC_KEY(pkey->get()));
275 if (!ec.get())
276 return false; // Unexpected.
277 int curve_nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec.get()));
279 return policy->IsAcceptableCurveForEcdsa(curve_nid);
282 } // namespace
284 bool VerifySignedData(const SignatureAlgorithm& signature_algorithm,
285 const der::Input& signed_data,
286 const der::BitString& signature_value,
287 const der::Input& public_key_spki,
288 const SignaturePolicy* policy) {
289 if (!policy->IsAcceptableSignatureAlgorithm(signature_algorithm))
290 return false;
292 crypto::ScopedEVP_PKEY public_key;
294 // Parse the SPKI to an EVP_PKEY appropriate for the signature algorithm.
295 switch (signature_algorithm.algorithm()) {
296 case SignatureAlgorithmId::RsaPkcs1:
297 case SignatureAlgorithmId::RsaPss:
298 if (!ParseRsaKeyFromSpki(public_key_spki, &public_key, policy))
299 return false;
300 break;
301 case SignatureAlgorithmId::Ecdsa:
302 if (!ParseEcKeyFromSpki(public_key_spki, &public_key, policy))
303 return false;
304 break;
307 return DoVerify(signature_algorithm, signed_data, signature_value,
308 public_key.get());
311 } // namespace net
313 #endif