2 * Copyright (C) 2013 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "modules/crypto/SubtleCrypto.h"
34 #include "bindings/core/v8/Dictionary.h"
35 #include "core/dom/ExecutionContext.h"
36 #include "modules/crypto/CryptoKey.h"
37 #include "modules/crypto/CryptoResultImpl.h"
38 #include "modules/crypto/NormalizeAlgorithm.h"
39 #include "platform/JSONValues.h"
40 #include "public/platform/Platform.h"
41 #include "public/platform/WebCrypto.h"
42 #include "public/platform/WebCryptoAlgorithm.h"
43 #include "wtf/ArrayBufferView.h"
47 // Seems like the generated bindings should take care of these however it
48 // currently doesn't. See also http://crbug.com/264520
49 static bool ensureNotNull(const ArrayPiece& x, const char* paramName, CryptoResult* result)
52 String message = String("Invalid ") + paramName + String(" argument");
53 result->completeWithError(WebCryptoErrorTypeType, WebString(message));
59 static bool ensureNotNull(CryptoKey* key, const char* paramName, CryptoResult* result)
62 String message = String("Invalid ") + paramName + String(" argument");
63 result->completeWithError(WebCryptoErrorTypeType, WebString(message));
69 static bool parseAlgorithm(const Dictionary& raw, WebCryptoOperation op, WebCryptoAlgorithm& algorithm, CryptoResult* result)
72 bool success = normalizeAlgorithm(raw, op, algorithm, &error);
74 result->completeWithError(error.errorType, error.errorDetails);
78 static bool canAccessWebCrypto(ScriptState* scriptState, CryptoResult* result)
80 const SecurityOrigin* origin = scriptState->executionContext()->securityOrigin();
82 if (!origin->canAccessFeatureRequiringSecureOrigin(errorMessage)) {
83 result->completeWithError(WebCryptoErrorTypeNotSupported, errorMessage);
90 static ScriptPromise startCryptoOperation(ScriptState* scriptState, const Dictionary& rawAlgorithm, CryptoKey* key, WebCryptoOperation operationType, const ArrayPiece& signature, const ArrayPiece& dataBuffer)
92 RefPtr<CryptoResultImpl> result = CryptoResultImpl::create(scriptState);
93 ScriptPromise promise = result->promise();
95 if (!canAccessWebCrypto(scriptState, result.get()))
98 bool requiresKey = operationType != WebCryptoOperationDigest;
100 if (requiresKey && !ensureNotNull(key, "key", result.get()))
102 if (operationType == WebCryptoOperationVerify && !ensureNotNull(signature, "signature", result.get()))
104 if (!ensureNotNull(dataBuffer, "dataBuffer", result.get()))
107 WebCryptoAlgorithm algorithm;
108 if (!parseAlgorithm(rawAlgorithm, operationType, algorithm, result.get()))
111 if (requiresKey && !key->canBeUsedForAlgorithm(algorithm, operationType, result.get()))
114 const unsigned char* data = dataBuffer.bytes();
115 unsigned dataSize = dataBuffer.byteLength();
117 switch (operationType) {
118 case WebCryptoOperationEncrypt:
119 Platform::current()->crypto()->encrypt(algorithm, key->key(), data, dataSize, result->result());
121 case WebCryptoOperationDecrypt:
122 Platform::current()->crypto()->decrypt(algorithm, key->key(), data, dataSize, result->result());
124 case WebCryptoOperationSign:
125 Platform::current()->crypto()->sign(algorithm, key->key(), data, dataSize, result->result());
127 case WebCryptoOperationVerify:
128 Platform::current()->crypto()->verifySignature(algorithm, key->key(), signature.bytes(), signature.byteLength(), data, dataSize, result->result());
130 case WebCryptoOperationDigest:
131 Platform::current()->crypto()->digest(algorithm, data, dataSize, result->result());
134 ASSERT_NOT_REACHED();
135 return ScriptPromise();
141 static bool copyStringProperty(const char* property, const Dictionary& source, JSONObject* destination)
144 if (!DictionaryHelper::get(source, property, value))
146 destination->setString(property, value);
150 static bool copySequenceOfStringProperty(const char* property, const Dictionary& source, JSONObject* destination)
152 Vector<String> value;
153 if (!DictionaryHelper::get(source, property, value))
155 RefPtr<JSONArray> jsonArray = JSONArray::create();
156 for (unsigned i = 0; i < value.size(); ++i)
157 jsonArray->pushString(value[i]);
158 destination->setArray(property, jsonArray.release());
162 // FIXME: At the time of writing this is not a part of the spec. It is based an
163 // an unpublished editor's draft for:
164 // https://www.w3.org/Bugs/Public/show_bug.cgi?id=24963
165 // See http://crbug.com/373917.
166 static bool copyJwkDictionaryToJson(const Dictionary& dict, CString& jsonUtf8, CryptoResult* result)
168 RefPtr<JSONObject> jsonObject = JSONObject::create();
170 if (!copyStringProperty("kty", dict, jsonObject.get())) {
171 result->completeWithError(WebCryptoErrorTypeData, "The required JWK property \"kty\" was missing");
175 copyStringProperty("use", dict, jsonObject.get());
176 copySequenceOfStringProperty("key_ops", dict, jsonObject.get());
177 copyStringProperty("alg", dict, jsonObject.get());
180 if (DictionaryHelper::get(dict, "ext", ext))
181 jsonObject->setBoolean("ext", ext);
183 const char* const propertyNames[] = { "d", "n", "e", "p", "q", "dp", "dq", "qi", "k" };
184 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(propertyNames); ++i)
185 copyStringProperty(propertyNames[i], dict, jsonObject.get());
187 String json = jsonObject->toJSONString();
188 jsonUtf8 = json.utf8();
192 SubtleCrypto::SubtleCrypto()
196 ScriptPromise SubtleCrypto::encrypt(ScriptState* scriptState, const Dictionary& rawAlgorithm, CryptoKey* key, const ArrayPiece& data)
198 return startCryptoOperation(scriptState, rawAlgorithm, key, WebCryptoOperationEncrypt, ArrayPiece(), data);
201 ScriptPromise SubtleCrypto::decrypt(ScriptState* scriptState, const Dictionary& rawAlgorithm, CryptoKey* key, const ArrayPiece& data)
203 return startCryptoOperation(scriptState, rawAlgorithm, key, WebCryptoOperationDecrypt, ArrayPiece(), data);
206 ScriptPromise SubtleCrypto::sign(ScriptState* scriptState, const Dictionary& rawAlgorithm, CryptoKey* key, const ArrayPiece& data)
208 return startCryptoOperation(scriptState, rawAlgorithm, key, WebCryptoOperationSign, ArrayPiece(), data);
211 ScriptPromise SubtleCrypto::verifySignature(ScriptState* scriptState, const Dictionary& rawAlgorithm, CryptoKey* key, const ArrayPiece& signature, const ArrayPiece& data)
213 return startCryptoOperation(scriptState, rawAlgorithm, key, WebCryptoOperationVerify, signature, data);
216 ScriptPromise SubtleCrypto::digest(ScriptState* scriptState, const Dictionary& rawAlgorithm, const ArrayPiece& data)
218 return startCryptoOperation(scriptState, rawAlgorithm, 0, WebCryptoOperationDigest, ArrayPiece(), data);
221 ScriptPromise SubtleCrypto::generateKey(ScriptState* scriptState, const Dictionary& rawAlgorithm, bool extractable, const Vector<String>& rawKeyUsages)
223 RefPtr<CryptoResultImpl> result = CryptoResultImpl::create(scriptState);
224 ScriptPromise promise = result->promise();
226 if (!canAccessWebCrypto(scriptState, result.get()))
229 WebCryptoKeyUsageMask keyUsages;
230 if (!CryptoKey::parseUsageMask(rawKeyUsages, keyUsages, result.get()))
233 WebCryptoAlgorithm algorithm;
234 if (!parseAlgorithm(rawAlgorithm, WebCryptoOperationGenerateKey, algorithm, result.get()))
237 Platform::current()->crypto()->generateKey(algorithm, extractable, keyUsages, result->result());
241 ScriptPromise SubtleCrypto::importKey(ScriptState* scriptState, const String& rawFormat, const ArrayPiece& keyData, const Dictionary& rawAlgorithm, bool extractable, const Vector<String>& rawKeyUsages)
243 RefPtr<CryptoResultImpl> result = CryptoResultImpl::create(scriptState);
244 ScriptPromise promise = result->promise();
246 if (!canAccessWebCrypto(scriptState, result.get()))
249 if (!ensureNotNull(keyData, "keyData", result.get()))
252 WebCryptoKeyFormat format;
253 if (!CryptoKey::parseFormat(rawFormat, format, result.get()))
256 if (format == WebCryptoKeyFormatJwk) {
257 result->completeWithError(WebCryptoErrorTypeData, "Key data must be an object for JWK import");
261 WebCryptoKeyUsageMask keyUsages;
262 if (!CryptoKey::parseUsageMask(rawKeyUsages, keyUsages, result.get()))
265 WebCryptoAlgorithm algorithm;
266 if (!parseAlgorithm(rawAlgorithm, WebCryptoOperationImportKey, algorithm, result.get()))
269 Platform::current()->crypto()->importKey(format, keyData.bytes(), keyData.byteLength(), algorithm, extractable, keyUsages, result->result());
273 ScriptPromise SubtleCrypto::importKey(ScriptState* scriptState, const String& rawFormat, const Dictionary& keyData, const Dictionary& rawAlgorithm, bool extractable, const Vector<String>& rawKeyUsages)
275 RefPtr<CryptoResultImpl> result = CryptoResultImpl::create(scriptState);
276 ScriptPromise promise = result->promise();
278 if (!canAccessWebCrypto(scriptState, result.get()))
281 WebCryptoKeyFormat format;
282 if (!CryptoKey::parseFormat(rawFormat, format, result.get()))
285 WebCryptoKeyUsageMask keyUsages;
286 if (!CryptoKey::parseUsageMask(rawKeyUsages, keyUsages, result.get()))
289 if (format != WebCryptoKeyFormatJwk) {
290 result->completeWithError(WebCryptoErrorTypeData, "Key data must be a buffer for non-JWK formats");
294 WebCryptoAlgorithm algorithm;
295 if (!parseAlgorithm(rawAlgorithm, WebCryptoOperationImportKey, algorithm, result.get()))
299 if (!copyJwkDictionaryToJson(keyData, jsonUtf8, result.get()))
302 Platform::current()->crypto()->importKey(format, reinterpret_cast<const unsigned char*>(jsonUtf8.data()), jsonUtf8.length(), algorithm, extractable, keyUsages, result->result());
306 ScriptPromise SubtleCrypto::exportKey(ScriptState* scriptState, const String& rawFormat, CryptoKey* key)
308 RefPtr<CryptoResultImpl> result = CryptoResultImpl::create(scriptState);
309 ScriptPromise promise = result->promise();
311 if (!canAccessWebCrypto(scriptState, result.get()))
314 if (!ensureNotNull(key, "key", result.get()))
317 WebCryptoKeyFormat format;
318 if (!CryptoKey::parseFormat(rawFormat, format, result.get()))
321 if (!key->extractable()) {
322 result->completeWithError(WebCryptoErrorTypeInvalidAccess, "key is not extractable");
326 Platform::current()->crypto()->exportKey(format, key->key(), result->result());
330 ScriptPromise SubtleCrypto::wrapKey(ScriptState* scriptState, const String& rawFormat, CryptoKey* key, CryptoKey* wrappingKey, const Dictionary& rawWrapAlgorithm)
332 RefPtr<CryptoResultImpl> result = CryptoResultImpl::create(scriptState);
333 ScriptPromise promise = result->promise();
335 if (!canAccessWebCrypto(scriptState, result.get()))
338 if (!ensureNotNull(key, "key", result.get()))
341 if (!ensureNotNull(wrappingKey, "wrappingKey", result.get()))
344 WebCryptoKeyFormat format;
345 if (!CryptoKey::parseFormat(rawFormat, format, result.get()))
348 WebCryptoAlgorithm wrapAlgorithm;
349 if (!parseAlgorithm(rawWrapAlgorithm, WebCryptoOperationWrapKey, wrapAlgorithm, result.get()))
352 if (!key->extractable()) {
353 result->completeWithError(WebCryptoErrorTypeInvalidAccess, "key is not extractable");
357 if (!wrappingKey->canBeUsedForAlgorithm(wrapAlgorithm, WebCryptoOperationWrapKey, result.get()))
360 Platform::current()->crypto()->wrapKey(format, key->key(), wrappingKey->key(), wrapAlgorithm, result->result());
364 ScriptPromise SubtleCrypto::unwrapKey(ScriptState* scriptState, const String& rawFormat, const ArrayPiece& wrappedKey, CryptoKey* unwrappingKey, const Dictionary& rawUnwrapAlgorithm, const Dictionary& rawUnwrappedKeyAlgorithm, bool extractable, const Vector<String>& rawKeyUsages)
366 RefPtr<CryptoResultImpl> result = CryptoResultImpl::create(scriptState);
367 ScriptPromise promise = result->promise();
369 if (!canAccessWebCrypto(scriptState, result.get()))
372 if (!ensureNotNull(wrappedKey, "wrappedKey", result.get()))
374 if (!ensureNotNull(unwrappingKey, "unwrappingKey", result.get()))
377 WebCryptoKeyFormat format;
378 if (!CryptoKey::parseFormat(rawFormat, format, result.get()))
381 WebCryptoKeyUsageMask keyUsages;
382 if (!CryptoKey::parseUsageMask(rawKeyUsages, keyUsages, result.get()))
385 WebCryptoAlgorithm unwrapAlgorithm;
386 if (!parseAlgorithm(rawUnwrapAlgorithm, WebCryptoOperationUnwrapKey, unwrapAlgorithm, result.get()))
389 WebCryptoAlgorithm unwrappedKeyAlgorithm;
390 if (!parseAlgorithm(rawUnwrappedKeyAlgorithm, WebCryptoOperationImportKey, unwrappedKeyAlgorithm, result.get()))
393 if (!unwrappingKey->canBeUsedForAlgorithm(unwrapAlgorithm, WebCryptoOperationUnwrapKey, result.get()))
396 Platform::current()->crypto()->unwrapKey(format, wrappedKey.bytes(), wrappedKey.byteLength(), unwrappingKey->key(), unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages, result->result());