Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(786)

Unified Diff: content/renderer/webcrypto/webcrypto_impl.cc

Issue 25906002: [webcrypto] Add JWK import for HMAC and AES-CBC key. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: fixes for eroman, plus additional validation of AES key size Created 7 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « content/renderer/webcrypto/webcrypto_impl.h ('k') | content/renderer/webcrypto/webcrypto_impl_nss.cc » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: content/renderer/webcrypto/webcrypto_impl.cc
diff --git a/content/renderer/webcrypto/webcrypto_impl.cc b/content/renderer/webcrypto/webcrypto_impl.cc
index 47b7ef52ca76e2e11cf14052b158b2d4fcf42015..e3464938ecb2a46f0699a1d4524d325ad74894c2 100644
--- a/content/renderer/webcrypto/webcrypto_impl.cc
+++ b/content/renderer/webcrypto/webcrypto_impl.cc
@@ -4,10 +4,19 @@
#include "content/renderer/webcrypto/webcrypto_impl.h"
+#include <algorithm>
+#include <functional>
+#include <map>
+#include <sstream>
+#include "base/json/json_reader.h"
+#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
-#include "third_party/WebKit/public/platform/WebArrayBuffer.h"
+#include "base/strings/string_piece.h"
+#include "base/values.h"
+#include "content/renderer/webcrypto/webcrypto_util.h"
#include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
+#include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
#include "third_party/WebKit/public/platform/WebCryptoKey.h"
namespace content {
@@ -22,28 +31,175 @@ bool IsAlgorithmAsymmetric(const WebKit::WebCryptoAlgorithm& algorithm) {
algorithm.id() == WebKit::WebCryptoAlgorithmIdRsaOaep);
}
-} // namespace
+// Binds a specific key length value to a compatible factory function.
+typedef WebKit::WebCryptoAlgorithm (*AlgFactoryFuncWithOneShortArg)(
+ unsigned short);
+template <AlgFactoryFuncWithOneShortArg func, unsigned short key_length>
+WebKit::WebCryptoAlgorithm BindAlgFactoryWithKeyLen() {
+ return func(key_length);
+}
-WebCryptoImpl::WebCryptoImpl() {
- Init();
+// Binds a WebCryptoAlgorithmId value to a compatible factory function.
+typedef WebKit::WebCryptoAlgorithm (*AlgFactoryFuncWithWebCryptoAlgIdArg)(
+ WebKit::WebCryptoAlgorithmId);
+template <AlgFactoryFuncWithWebCryptoAlgIdArg func,
+ WebKit::WebCryptoAlgorithmId algorithm_id>
+WebKit::WebCryptoAlgorithm BindAlgFactoryAlgorithmId() {
+ return func(algorithm_id);
}
-// static
-// TODO(eroman): This works by re-allocating a new buffer. It would be better if
-// the WebArrayBuffer could just be truncated instead.
-void WebCryptoImpl::ShrinkBuffer(
- WebKit::WebArrayBuffer* buffer,
- unsigned new_size) {
- DCHECK_LE(new_size, buffer->byteLength());
+// Defines a map between a JWK 'alg' string ID and a corresponding Web Crypto
+// factory function.
+typedef WebKit::WebCryptoAlgorithm (*AlgFactoryFuncNoArgs)();
+typedef std::map<std::string, AlgFactoryFuncNoArgs> JwkAlgFactoryMap;
+
+class JwkAlgorithmFactoryMap {
+ public:
+ JwkAlgorithmFactoryMap() {
+ map_["HS256"] =
+ &BindAlgFactoryWithKeyLen<CreateHmacAlgorithmByDigestLen, 256>;
+ map_["HS384"] =
+ &BindAlgFactoryWithKeyLen<CreateHmacAlgorithmByDigestLen, 384>;
+ map_["HS512"] =
+ &BindAlgFactoryWithKeyLen<CreateHmacAlgorithmByDigestLen, 512>;
+ map_["RS256"] =
+ &BindAlgFactoryAlgorithmId<CreateRsaSsaAlgorithm,
+ WebKit::WebCryptoAlgorithmIdSha256>;
+ map_["RS384"] =
+ &BindAlgFactoryAlgorithmId<CreateRsaSsaAlgorithm,
+ WebKit::WebCryptoAlgorithmIdSha384>;
+ map_["RS512"] =
+ &BindAlgFactoryAlgorithmId<CreateRsaSsaAlgorithm,
+ WebKit::WebCryptoAlgorithmIdSha512>;
+ map_["RSA1_5"] =
+ &BindAlgFactoryAlgorithmId<CreateAlgorithm,
+ WebKit::WebCryptoAlgorithmIdRsaEsPkcs1v1_5>;
+ map_["RSA-OAEP"] =
+ &BindAlgFactoryAlgorithmId<CreateRsaOaepAlgorithm,
+ WebKit::WebCryptoAlgorithmIdSha1>;
+ map_["A128KW"] = &WebKit::WebCryptoAlgorithm::createNull;
+ map_["A256KW"] = &WebKit::WebCryptoAlgorithm::createNull;
+ map_["A128GCM"] =
+ &BindAlgFactoryAlgorithmId<CreateAlgorithm,
+ WebKit::WebCryptoAlgorithmIdAesGcm>;
+ map_["A256GCM"] =
+ &BindAlgFactoryAlgorithmId<CreateAlgorithm,
+ WebKit::WebCryptoAlgorithmIdAesGcm>;
+ map_["A128CBC"] =
+ &BindAlgFactoryAlgorithmId<CreateAlgorithm,
+ WebKit::WebCryptoAlgorithmIdAesCbc>;
+ map_["A256CBC"] =
+ &BindAlgFactoryAlgorithmId<CreateAlgorithm,
+ WebKit::WebCryptoAlgorithmIdAesCbc>;
+ map_["A384CBC"] =
+ &BindAlgFactoryAlgorithmId<CreateAlgorithm,
+ WebKit::WebCryptoAlgorithmIdAesCbc>;
+ map_["A512CBC"] =
+ &BindAlgFactoryAlgorithmId<CreateAlgorithm,
aproskuryakov 2013/11/05 08:52:15 A128GCM...A512CBC are not registered in JWA, why i
padolph 2013/11/05 16:35:57 Mark Watson at Netflix is working with JOSE to get
aproskuryakov 2013/11/07 22:05:41 One reason why I'm asking is that there is no such
+ WebKit::WebCryptoAlgorithmIdAesCbc>;
+ }
+
+ WebKit::WebCryptoAlgorithm CreateAlgorithmFromName(
+ const std::string& alg_id) const {
+ const JwkAlgFactoryMap::const_iterator pos = map_.find(alg_id);
+ if (pos == map_.end())
+ return WebKit::WebCryptoAlgorithm::createNull();
+ return pos->second();
+ }
+
+ private:
+ JwkAlgFactoryMap map_;
+};
+
+base::LazyInstance<JwkAlgorithmFactoryMap> jwk_alg_factory =
+ LAZY_INSTANCE_INITIALIZER;
+
+// TODO(padolph): Verify this logic is sufficient to judge algorithm
+// "consistency" for JWK import, and for all supported algorithms.
+bool WebCryptoAlgorithmsConsistent(const WebKit::WebCryptoAlgorithm& alg1,
+ const WebKit::WebCryptoAlgorithm& alg2) {
+ DCHECK(!alg1.isNull());
+ DCHECK(!alg2.isNull());
+ if (alg1.id() == alg2.id()) {
+ if (alg1.id() == WebKit::WebCryptoAlgorithmIdHmac ||
+ alg1.id() == WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 ||
+ alg1.id() == WebKit::WebCryptoAlgorithmIdRsaOaep) {
+ if (WebCryptoAlgorithmsConsistent(GetInnerHashAlgorithm(alg1),
+ GetInnerHashAlgorithm(alg2))) {
+ return true;
+ }
+ return false;
+ }
+ return true;
+ }
+ return false;
+}
+
+// Returns true if the left side of the string is an exact match.
+// For example, for "foobar", "foo" would return true but "oob" would not.
+bool DoesLeftSideOfStringMatch(const std::string& str,
+ const std::string& match_str) {
+ DCHECK(!str.empty());
+ DCHECK(!match_str.empty());
+ const size_t match_idx = str.find(match_str);
+ if (match_idx == std::string::npos)
+ return false;
+ return match_idx == 0;
+}
+
+// Returns true if the right side of the string is exactly match.
+// For example, for "foobar", "bar" would return true but "oba" would not.
+bool DoesRightSideOfStringMatch(const std::string& str,
+ const std::string& match_str) {
+ DCHECK(!str.empty());
+ DCHECK(!match_str.empty());
+ const size_t match_idx = str.rfind(match_str);
+ if (match_idx == std::string::npos)
+ return false;
+ const std::string found_match(str.substr(match_idx));
+ assert(!found_match.empty());
+ const bool is_right_side = found_match == match_str;
+ // match_idx is also the length of the left side of the string.
+ DCHECK(is_right_side == (str.length() == match_idx + match_str.length()));
+ return is_right_side;
+}
+
+// Returns true if the input JWK alg string is one of the AES types enumerated
padolph 2013/11/05 16:35:57 eroman: What do you think of this approach? These
eroman 2013/11/07 05:49:41 Verifying the key bit length is a good addition to
padolph 2013/11/07 17:58:21 Thanks for the reply. I did not think of the gener
eroman 2013/11/07 20:54:37 Sounds good. Note also that you can rename JwkAlgo
+// below, namely "AdddKW", "AdddCBC", or "AdddGCM", where 'ddd' is the key
+// length.
+bool IsJwkAlgAes(const std::string& jwk_alg) {
+ if (jwk_alg.empty() || !DoesLeftSideOfStringMatch(jwk_alg, "A"))
+ return false;
+ return DoesRightSideOfStringMatch(jwk_alg, "KW") ||
+ DoesRightSideOfStringMatch(jwk_alg, "CBC") ||
+ DoesRightSideOfStringMatch(jwk_alg, "GCM");
+}
+
+// Extracts an unsigned int from the middle of a string like "AAAAddAA", where
+// 'A' is a non-numeric character and 'd' is (radix 10). This is used to extract
+// the key length in bits from a JWK AES alg ID.
+bool ExtractUnsignedIntFromString(const std::string& jwk_alg,
+ unsigned int* key_len) {
+ // This logic assumes we are looking for radix 10 numbers.
+ const size_t start_idx = jwk_alg.find_first_of("123456789");
+ if (start_idx == std::string::npos)
+ return false;
+ std::istringstream stream(jwk_alg.substr(start_idx));
+ unsigned int number;
+ // Note: istringstream::operator>>() stops parsing when it hits a non-numeric
+ // character. Also, it will fail if the number being parsed is inconsistent
+ // with the input type.
+ stream >> number;
+ if (stream.fail())
+ return false;
+ *key_len = number;
+ return true;
+}
- if (new_size == buffer->byteLength())
- return;
+} // namespace
- WebKit::WebArrayBuffer new_buffer =
- WebKit::WebArrayBuffer::create(new_size, 1);
- DCHECK(!new_buffer.isNull());
- memcpy(new_buffer.data(), buffer->data(), new_size);
- *buffer = new_buffer;
+WebCryptoImpl::WebCryptoImpl() {
+ Init();
}
// static
@@ -150,15 +306,25 @@ void WebCryptoImpl::importKey(
WebKit::WebCryptoKeyUsageMask usage_mask,
WebKit::WebCryptoResult result) {
WebKit::WebCryptoKey key = WebKit::WebCryptoKey::createNull();
- if (!ImportKeyInternal(format,
- key_data,
- key_data_size,
- algorithm_or_null,
- extractable,
- usage_mask,
- &key)) {
- result.completeWithError();
- return;
+ if (format == WebKit::WebCryptoKeyFormatJwk) {
+ if (!ImportKeyJwk(key_data,
+ key_data_size,
+ algorithm_or_null,
+ extractable,
+ usage_mask,
+ &key)) {
+ result.completeWithError();
+ }
+ } else {
+ if (!ImportKeyInternal(format,
+ key_data,
+ key_data_size,
+ algorithm_or_null,
+ extractable,
+ usage_mask,
+ &key)) {
+ result.completeWithError();
+ }
}
DCHECK(key.handle());
DCHECK(!key.algorithm().isNull());
@@ -204,4 +370,238 @@ void WebCryptoImpl::verifySignature(
}
}
+bool WebCryptoImpl::ImportKeyJwk(
+ const unsigned char* key_data,
+ unsigned key_data_size,
+ const WebKit::WebCryptoAlgorithm& algorithm_or_null,
+ bool extractable,
+ WebKit::WebCryptoKeyUsageMask usage_mask,
+ WebKit::WebCryptoKey* key) {
+
+ // JSON Web Key Format (JWK)
+ // http://tools.ietf.org/html/draft-ietf-jose-json-web-key-16
+ // TODO(padolph): Not all possible values are handled by this code right now
+ //
+ // A JWK is a simple JSON dictionary with the following entries
+ // - "kty" (Key Type) Parameter, REQUIRED
+ // - <kty-specific parameters, see below>, REQUIRED
+ // - "use" (Key Use) Parameter, OPTIONAL
+ // - "alg" (Algorithm) Parameter, OPTIONAL
+ // - "extractable" (Key Exportability), OPTIONAL [NOTE: not yet part of JOSE]
+ // (all other entries are ignored)
+ //
+ // Input key_data contains the JWK. To build a Web Crypto Key, the JWK values
+ // are parsed out and used as follows:
+ // Web Crypto Key type <-- (deduced)
+ // Web Crypto Key extractable <-- extractable
+ // Web Crypto Key algorithm <-- alg
+ // Web Crypto Key keyUsage <-- usage
+ // Web Crypto Key keying material <-- kty-specific parameters
+ //
+ // Values for each entry are case-sensitive and defined in
+ // http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-16.
+ // Note that not all values specified by JOSE are handled by this code. Only
+ // handled values are listed.
+ // - kty (Key Type)
+ // +-------+--------------------------------------------------------------+
+ // | "RSA" | RSA [RFC3447] |
+ // | "oct" | Octet sequence (used to represent symmetric keys) |
+ // +-------+--------------------------------------------------------------+
+ // - use (Key Use)
+ // +-------+--------------------------------------------------------------+
+ // | "enc" | encrypt and decrypt operations |
+ // | "sig" | sign and verify (MAC) operations |
+ // | "wrap"| key wrap and unwrap [not yet part of JOSE] |
+ // +-------+--------------------------------------------------------------+
+ // - extractable (Key Exportability)
+ // +-------+--------------------------------------------------------------+
+ // | true | Key may be exported from the trusted environment |
+ // | false | Key cannot exit the trusted environment |
+ // +-------+--------------------------------------------------------------+
+ // - alg (Algorithm)
+ // See http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-16
+ // +--------------+-------------------------------------------------------+
+ // | Digital Signature or MAC Algorithm |
+ // +--------------+-------------------------------------------------------+
+ // | "HS256" | HMAC using SHA-256 hash algorithm |
+ // | "HS384" | HMAC using SHA-384 hash algorithm |
+ // | "HS512" | HMAC using SHA-512 hash algorithm |
+ // | "RS256" | RSASSA using SHA-256 hash algorithm |
+ // | "RS384" | RSASSA using SHA-384 hash algorithm |
+ // | "RS512" | RSASSA using SHA-512 hash algorithm |
+ // +--------------+-------------------------------------------------------|
+ // | Key Management Algorithm |
+ // +--------------+-------------------------------------------------------+
+ // | "RSA1_5" | RSAES-PKCS1-V1_5 [RFC3447] |
+ // | "RSA-OAEP" | RSAES using Optimal Asymmetric Encryption Padding |
+ // | | (OAEP) [RFC3447], with the default parameters |
+ // | | specified by RFC3447 in Section A.2.1 |
+ // | "A128KW" | Advanced Encryption Standard (AES) Key Wrap Algorithm |
+ // | | [RFC3394] using 128 bit keys |
+ // | "A256KW" | AES Key Wrap Algorithm using 256 bit keys |
+ // | "A128GCM" | AES in Galois/Counter Mode (GCM) [NIST.800-38D] using |
+ // | | 128 bit keys |
+ // | "A256GCM" | AES GCM using 256 bit keys |
+ // | "A128CBC" | AES in Cipher Block Chaining Mode (CBC) with PKCS #5 |
+ // | | padding [NIST.800-38A] [not yet part of JOSE] |
+ // | "A256CBC" | AES CBC using 256 bit keys [not yet part of JOSE] |
+ // | "A384CBC" | AES CBC using 384 bit keys [not yet part of JOSE] |
+ // | "A512CBC" | AES CBC using 512 bit keys [not yet part of JOSE] |
+ // +--------------+-------------------------------------------------------+
+ //
+ // kty-specific parameters
+ // The value of kty determines the type and content of the keying material
+ // carried in the JWK to be imported. Currently only two possibilities are
+ // supported: a raw key or an RSA public key. RSA private keys are not
+ // supported because typical applications seldom need to import a private key,
+ // and the large number of JWK parameters required to describe one.
+ // - kty == "oct" (symmetric or other raw key)
+ // +-------+--------------------------------------------------------------+
+ // | "k" | Contains the value of the symmetric (or other single-valued) |
+ // | | key. It is represented as the base64url encoding of the |
+ // | | octet sequence containing the key value. |
+ // +-------+--------------------------------------------------------------+
+ // - kty == "RSA" (RSA public key)
+ // +-------+--------------------------------------------------------------+
+ // | "n" | Contains the modulus value for the RSA public key. It is |
+ // | | represented as the base64url encoding of the value's |
+ // | | unsigned big endian representation as an octet sequence. |
+ // +-------+--------------------------------------------------------------+
+ // | "e" | Contains the exponent value for the RSA public key. It is |
+ // | | represented as the base64url encoding of the value's |
+ // | | unsigned big endian representation as an octet sequence. |
+ // +-------+--------------------------------------------------------------+
+ //
+ // Conflict resolution
+ // The algorithm_or_null, extractable, and usage_mask input parameters may be
+ // different from similar values inside the JWK. The Web Crypto spec says that
+ // if a JWK value is present but is inconsistent with the input value, it is
+ // an error and the operation must fail. Conversely, should they be missing
+ // from the JWK, the input values should be used to "fill-in" for the
+ // corresponding JWK-optional values (use, alg, extractable).
+
+ DCHECK(key);
+
+ // Parse the incoming JWK JSON.
+ if (!key_data || !key_data_size)
+ return false;
+ base::StringPiece json_string(reinterpret_cast<const char*>(key_data),
+ key_data_size);
+ scoped_ptr<base::Value> value(base::JSONReader::Read(json_string));
+ // Note, bare pointer dict_value is ok since it points into scoped value.
+ base::DictionaryValue* dict_value = NULL;
+ if (!value.get() || !value->GetAsDictionary(&dict_value) || !dict_value)
+ return false;
+
+ // JWK "kty". Exit early if this required JWK parameter is missing.
+ std::string jwk_kty_value;
+ if (!dict_value->GetString("kty", &jwk_kty_value))
+ return false;
+
+ // JWK "extractable" (optional) --> extractable parameter
+ {
+ bool jwk_extractable_value;
+ if (dict_value->GetBoolean("extractable", &jwk_extractable_value)) {
+ if (jwk_extractable_value != extractable)
+ return false;
+ }
+ }
+
+ // JWK "alg" (optional) --> algorithm parameter
+ // Note: input algorithm is also optional, so we have six cases to handle.
+ // 1. JWK alg present but unrecognized: error
+ // 2. JWK alg valid AND input algorithm isNull: use JWK value
+ // 3. JWK alg valid AND input algorithm specified, but JWK value
+ // inconsistent with input: error
+ // 4. JWK alg valid AND input algorithm specified, both consistent: use
+ // input value (because it has potentially more details)
+ // 5. JWK alg missing AND input algorithm isNull: error
+ // 6. JWK alg missing AND input algorithm specified: use input value
+ WebKit::WebCryptoAlgorithm algorithm =
+ WebKit::WebCryptoAlgorithm::createNull();
+ std::string jwk_alg_value;
+ if (dict_value->GetString("alg", &jwk_alg_value)) {
+ // JWK alg present
+ const WebKit::WebCryptoAlgorithm jwk_algorithm =
+ jwk_alg_factory.Get().CreateAlgorithmFromName(jwk_alg_value);
+ if (jwk_algorithm.isNull()) {
+ // JWK alg unrecognized
+ return false; // case 1
+ }
+ // JWK alg valid
+ if (algorithm_or_null.isNull()) {
+ // input algorithm not specified
+ algorithm = jwk_algorithm; // case 2
+ } else {
+ // input algorithm specified
+ if (!WebCryptoAlgorithmsConsistent(jwk_algorithm, algorithm_or_null))
+ return false; // case 3
+ algorithm = algorithm_or_null; // case 4
+ }
+ } else {
+ // JWK alg missing
+ if (algorithm_or_null.isNull())
+ return false; // case 5
+ algorithm = algorithm_or_null; // case 6
+ }
+ DCHECK(!algorithm.isNull());
+
+ // JWK "use" (optional) --> usage_mask parameter
+ std::string jwk_use_value;
+ if (dict_value->GetString("use", &jwk_use_value)) {
+ WebKit::WebCryptoKeyUsageMask jwk_usage_mask = 0;
+ if (jwk_use_value == "enc") {
+ jwk_usage_mask =
+ WebKit::WebCryptoKeyUsageEncrypt | WebKit::WebCryptoKeyUsageDecrypt;
+ } else if (jwk_use_value == "sig") {
+ jwk_usage_mask =
+ WebKit::WebCryptoKeyUsageSign | WebKit::WebCryptoKeyUsageVerify;
+ } else if (jwk_use_value == "wrap") {
+ jwk_usage_mask =
+ WebKit::WebCryptoKeyUsageWrapKey | WebKit::WebCryptoKeyUsageUnwrapKey;
+ } else {
+ return false;
+ }
+ if ((jwk_usage_mask & usage_mask) != usage_mask) {
+ // A usage_mask must be a subset of jwk_usage_mask.
+ return false;
+ }
+ }
+
+ // JWK keying material --> ImportKeyInternal()
+ if (jwk_kty_value == "oct") {
+ std::string jwk_k_value_url64;
+ if (!dict_value->GetString("k", &jwk_k_value_url64))
+ return false;
+ std::string jwk_k_value;
+ if (!Base64DecodeUrlSafe(jwk_k_value_url64, &jwk_k_value) ||
+ !jwk_k_value.size()) {
+ return false;
+ }
+ // AES JWK alg ID's embed the intended key length in the ID string. Validate
+ // the actual key length against it.
+ if (IsJwkAlgAes(jwk_alg_value)) {
+ unsigned int jwk_alg_key_len_bits = 0;
+ if (ExtractUnsignedIntFromString(jwk_alg_value, &jwk_alg_key_len_bits) &&
+ (jwk_alg_key_len_bits / 8 != jwk_k_value.size())) {
+ return false;
+ }
+ }
+ return ImportKeyInternal(WebKit::WebCryptoKeyFormatRaw,
+ reinterpret_cast<const uint8*>(jwk_k_value.data()),
+ jwk_k_value.size(),
+ algorithm,
+ extractable,
+ usage_mask,
+ key);
+ } else if (jwk_kty_value == "RSA") {
+ // TODO(padolph): JWK import RSA public key
+ return false;
+ } else {
+ return false;
+ }
+
+ return true;
+}
+
} // namespace content
« no previous file with comments | « content/renderer/webcrypto/webcrypto_impl.h ('k') | content/renderer/webcrypto/webcrypto_impl_nss.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698