SubtleCrypto.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, stelar7 <dudedbz@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/QuickSort.h>
  8. #include <LibCrypto/Hash/HashManager.h>
  9. #include <LibJS/Runtime/ArrayBuffer.h>
  10. #include <LibJS/Runtime/Promise.h>
  11. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  12. #include <LibWeb/Bindings/Intrinsics.h>
  13. #include <LibWeb/Crypto/KeyAlgorithms.h>
  14. #include <LibWeb/Crypto/SubtleCrypto.h>
  15. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  16. #include <LibWeb/Platform/EventLoopPlugin.h>
  17. #include <LibWeb/WebIDL/AbstractOperations.h>
  18. #include <LibWeb/WebIDL/Buffers.h>
  19. #include <LibWeb/WebIDL/ExceptionOr.h>
  20. #include <LibWeb/WebIDL/Promise.h>
  21. namespace Web::Crypto {
  22. static void normalize_key_usages(Vector<Bindings::KeyUsage>& key_usages)
  23. {
  24. quick_sort(key_usages);
  25. }
  26. struct RegisteredAlgorithm {
  27. NonnullOwnPtr<AlgorithmMethods> (*create_methods)(JS::Realm&) = nullptr;
  28. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> (*parameter_from_value)(JS::VM&, JS::Value) = nullptr;
  29. };
  30. using SupportedAlgorithmsMap = HashMap<String, HashMap<String, RegisteredAlgorithm, AK::ASCIICaseInsensitiveStringTraits>>;
  31. static SupportedAlgorithmsMap& supported_algorithms_internal();
  32. static SupportedAlgorithmsMap supported_algorithms();
  33. template<typename Methods, typename Param = AlgorithmParams>
  34. static void define_an_algorithm(String op, String algorithm);
  35. JS_DEFINE_ALLOCATOR(SubtleCrypto);
  36. JS::NonnullGCPtr<SubtleCrypto> SubtleCrypto::create(JS::Realm& realm)
  37. {
  38. return realm.heap().allocate<SubtleCrypto>(realm, realm);
  39. }
  40. SubtleCrypto::SubtleCrypto(JS::Realm& realm)
  41. : PlatformObject(realm)
  42. {
  43. }
  44. SubtleCrypto::~SubtleCrypto() = default;
  45. void SubtleCrypto::initialize(JS::Realm& realm)
  46. {
  47. Base::initialize(realm);
  48. WEB_SET_PROTOTYPE_FOR_INTERFACE(SubtleCrypto);
  49. }
  50. // https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm
  51. WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> normalize_an_algorithm(JS::Realm& realm, AlgorithmIdentifier const& algorithm, String operation)
  52. {
  53. auto& vm = realm.vm();
  54. // If alg is an instance of a DOMString:
  55. if (algorithm.has<String>()) {
  56. // Return the result of running the normalize an algorithm algorithm,
  57. // with the alg set to a new Algorithm dictionary whose name attribute is alg, and with the op set to op.
  58. auto dictionary = JS::make_handle(JS::Object::create(realm, realm.intrinsics().object_prototype()));
  59. TRY(dictionary->create_data_property("name", JS::PrimitiveString::create(vm, algorithm.get<String>())));
  60. return normalize_an_algorithm(realm, dictionary, operation);
  61. }
  62. // If alg is an object:
  63. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  64. // NOTE: There should always be a container at the op key.
  65. auto internal_object = supported_algorithms();
  66. auto maybe_registered_algorithms = internal_object.get(operation);
  67. auto registered_algorithms = maybe_registered_algorithms.value();
  68. // 2. Let initialAlg be the result of converting the ECMAScript object represented by alg to
  69. // the IDL dictionary type Algorithm, as defined by [WebIDL].
  70. // 3. If an error occurred, return the error and terminate this algorithm.
  71. // Note: We're not going to bother creating an Algorithm object, all we want is the name attribute so that we can
  72. // fetch the actual algorithm factory from the registeredAlgorithms map.
  73. auto initial_algorithm = TRY(algorithm.get<JS::Handle<JS::Object>>()->get("name"));
  74. // 4. Let algName be the value of the name attribute of initialAlg.
  75. auto algorithm_name = TRY(initial_algorithm.to_string(vm));
  76. RegisteredAlgorithm desired_type;
  77. // 5. If registeredAlgorithms contains a key that is a case-insensitive string match for algName:
  78. if (auto it = registered_algorithms.find(algorithm_name); it != registered_algorithms.end()) {
  79. // 1. Set algName to the value of the matching key.
  80. // 2. Let desiredType be the IDL dictionary type stored at algName in registeredAlgorithms.
  81. desired_type = it->value;
  82. } else {
  83. // Otherwise:
  84. // Return a new NotSupportedError and terminate this algorithm.
  85. return WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Algorithm '{}' is not supported for operation '{}'", algorithm_name, operation)));
  86. }
  87. // 8. Let normalizedAlgorithm be the result of converting the ECMAScript object represented by alg
  88. // to the IDL dictionary type desiredType, as defined by [WebIDL].
  89. // 9. Set the name attribute of normalizedAlgorithm to algName.
  90. // 10. If an error occurred, return the error and terminate this algorithm.
  91. // 11. Let dictionaries be a list consisting of the IDL dictionary type desiredType
  92. // and all of desiredType's inherited dictionaries, in order from least to most derived.
  93. // 12. For each dictionary dictionary in dictionaries:
  94. // Note: All of these steps are handled by the create_methods and parameter_from_value methods.
  95. auto methods = desired_type.create_methods(realm);
  96. auto parameter = TRY(desired_type.parameter_from_value(vm, algorithm.get<JS::Handle<JS::Object>>()));
  97. auto normalized_algorithm = NormalizedAlgorithmAndParameter { move(methods), move(parameter) };
  98. // 13. Return normalizedAlgorithm.
  99. return normalized_algorithm;
  100. }
  101. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-encrypt
  102. JS::NonnullGCPtr<JS::Promise> SubtleCrypto::encrypt(AlgorithmIdentifier const& algorithm, JS::NonnullGCPtr<CryptoKey> key, JS::Handle<WebIDL::BufferSource> const& data_parameter)
  103. {
  104. auto& realm = this->realm();
  105. auto& vm = this->vm();
  106. // 1. Let algorithm and key be the algorithm and key parameters passed to the encrypt() method, respectively.
  107. // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the encrypt() method.
  108. auto data_or_error = WebIDL::get_buffer_source_copy(*data_parameter->raw_object());
  109. if (data_or_error.is_error()) {
  110. VERIFY(data_or_error.error().code() == ENOMEM);
  111. return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)));
  112. }
  113. auto data = data_or_error.release_value();
  114. // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "encrypt".
  115. auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "encrypt"_string);
  116. // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  117. if (normalized_algorithm.is_error())
  118. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  119. // 5. Let promise be a new Promise.
  120. auto promise = WebIDL::create_promise(realm);
  121. // 6. Return promise and perform the remaining steps in parallel.
  122. Platform::EventLoopPlugin::the().deferred_invoke([&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, key, data = move(data)]() -> void {
  123. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  124. // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  125. // 8. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.
  126. if (normalized_algorithm.parameter->name != key->algorithm_name()) {
  127. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Algorithm mismatch"_fly_string));
  128. return;
  129. }
  130. // 9. If the [[usages]] internal slot of key does not contain an entry that is "encrypt", then throw an InvalidAccessError.
  131. if (!key->internal_usages().contains_slow(Bindings::KeyUsage::Encrypt)) {
  132. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Key does not support encryption"_fly_string));
  133. return;
  134. }
  135. // 10. Let ciphertext be the result of performing the encrypt operation specified by normalizedAlgorithm using algorithm and key and with data as plaintext.
  136. auto cipher_text = normalized_algorithm.methods->encrypt(*normalized_algorithm.parameter, key, data);
  137. if (cipher_text.is_error()) {
  138. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), cipher_text.release_error()).release_value().value());
  139. return;
  140. }
  141. // 9. Resolve promise with ciphertext.
  142. WebIDL::resolve_promise(realm, promise, cipher_text.release_value());
  143. });
  144. return verify_cast<JS::Promise>(*promise->promise());
  145. }
  146. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-decrypt
  147. JS::NonnullGCPtr<JS::Promise> SubtleCrypto::decrypt(AlgorithmIdentifier const& algorithm, JS::NonnullGCPtr<CryptoKey> key, JS::Handle<WebIDL::BufferSource> const& data_parameter)
  148. {
  149. auto& realm = this->realm();
  150. auto& vm = this->vm();
  151. // 1. Let algorithm and key be the algorithm and key parameters passed to the decrypt() method, respectively.
  152. // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the decrypt() method.
  153. auto data_or_error = WebIDL::get_buffer_source_copy(*data_parameter->raw_object());
  154. if (data_or_error.is_error()) {
  155. VERIFY(data_or_error.error().code() == ENOMEM);
  156. return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)));
  157. }
  158. auto data = data_or_error.release_value();
  159. // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "decrypt".
  160. auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "decrypt"_string);
  161. // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  162. if (normalized_algorithm.is_error())
  163. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  164. // 5. Let promise be a new Promise.
  165. auto promise = WebIDL::create_promise(realm);
  166. // 6. Return promise and perform the remaining steps in parallel.
  167. Platform::EventLoopPlugin::the().deferred_invoke([&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, key, data = move(data)]() -> void {
  168. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  169. // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  170. // 8. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.
  171. if (normalized_algorithm.parameter->name != key->algorithm_name()) {
  172. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Algorithm mismatch"_fly_string));
  173. return;
  174. }
  175. // 9. If the [[usages]] internal slot of key does not contain an entry that is "decrypt", then throw an InvalidAccessError.
  176. if (!key->internal_usages().contains_slow(Bindings::KeyUsage::Decrypt)) {
  177. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Key does not support encryption"_fly_string));
  178. return;
  179. }
  180. // 10. Let plaintext be the result of performing the decrypt operation specified by normalizedAlgorithm using algorithm and key and with data as ciphertext.
  181. auto plain_text = normalized_algorithm.methods->decrypt(*normalized_algorithm.parameter, key, data);
  182. if (plain_text.is_error()) {
  183. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), plain_text.release_error()).release_value().value());
  184. return;
  185. }
  186. // 9. Resolve promise with plaintext.
  187. WebIDL::resolve_promise(realm, promise, plain_text.release_value());
  188. });
  189. return verify_cast<JS::Promise>(*promise->promise());
  190. }
  191. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-digest
  192. JS::NonnullGCPtr<JS::Promise> SubtleCrypto::digest(AlgorithmIdentifier const& algorithm, JS::Handle<WebIDL::BufferSource> const& data)
  193. {
  194. auto& realm = this->realm();
  195. auto& vm = this->vm();
  196. // 1. Let algorithm be the algorithm parameter passed to the digest() method.
  197. // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the digest() method.
  198. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*data->raw_object());
  199. if (data_buffer_or_error.is_error()) {
  200. VERIFY(data_buffer_or_error.error().code() == ENOMEM);
  201. return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)));
  202. }
  203. auto data_buffer = data_buffer_or_error.release_value();
  204. // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "digest".
  205. auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "digest"_string);
  206. // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  207. // FIXME: Spec bug: link to https://webidl.spec.whatwg.org/#a-promise-rejected-with
  208. if (normalized_algorithm.is_error())
  209. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  210. // 5. Let promise be a new Promise.
  211. auto promise = WebIDL::create_promise(realm);
  212. // 6. Return promise and perform the remaining steps in parallel.
  213. Platform::EventLoopPlugin::the().deferred_invoke([&realm, algorithm_object = normalized_algorithm.release_value(), promise, data_buffer = move(data_buffer)]() -> void {
  214. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  215. // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  216. // FIXME: Need spec reference to https://webidl.spec.whatwg.org/#reject
  217. // 8. Let result be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.
  218. auto result = algorithm_object.methods->digest(*algorithm_object.parameter, data_buffer);
  219. if (result.is_exception()) {
  220. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result.release_error()).release_value().value());
  221. return;
  222. }
  223. // 9. Resolve promise with result.
  224. WebIDL::resolve_promise(realm, promise, result.release_value());
  225. });
  226. return verify_cast<JS::Promise>(*promise->promise());
  227. }
  228. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-generateKey
  229. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::generate_key(AlgorithmIdentifier algorithm, bool extractable, Vector<Bindings::KeyUsage> key_usages)
  230. {
  231. auto& realm = this->realm();
  232. // 1. Let algorithm, extractable and usages be the algorithm, extractable and keyUsages
  233. // parameters passed to the generateKey() method, respectively.
  234. // 2. Let normalizedAlgorithm be the result of normalizing an algorithm,
  235. // with alg set to algorithm and op set to "generateKey".
  236. auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "generateKey"_string);
  237. // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  238. if (normalized_algorithm.is_error())
  239. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  240. // 4. Let promise be a new Promise.
  241. auto promise = WebIDL::create_promise(realm);
  242. // 5. Return promise and perform the remaining steps in parallel.
  243. Platform::EventLoopPlugin::the().deferred_invoke([&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, extractable, key_usages = move(key_usages)]() -> void {
  244. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  245. // 6. If the following steps or referenced procedures say to throw an error, reject promise with
  246. // the returned error and then terminate the algorithm.
  247. // 7. Let result be the result of performing the generate key operation specified by normalizedAlgorithm
  248. // using algorithm, extractable and usages.
  249. auto result_or_error = normalized_algorithm.methods->generate_key(*normalized_algorithm.parameter, extractable, key_usages);
  250. if (result_or_error.is_error()) {
  251. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result_or_error.release_error()).release_value().value());
  252. return;
  253. }
  254. auto result = result_or_error.release_value();
  255. // 8. If result is a CryptoKey object:
  256. // If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.
  257. // If result is a CryptoKeyPair object:
  258. // If the [[usages]] internal slot of the privateKey attribute of result is the empty sequence, then throw a SyntaxError.
  259. // 9. Resolve promise with result.
  260. result.visit(
  261. [&](JS::NonnullGCPtr<CryptoKey>& key) {
  262. if ((key->type() == Bindings::KeyType::Secret || key->type() == Bindings::KeyType::Private) && key_usages.is_empty()) {
  263. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  264. return;
  265. }
  266. WebIDL::resolve_promise(realm, promise, key);
  267. },
  268. [&](JS::NonnullGCPtr<CryptoKeyPair>& key_pair) {
  269. if (key_pair->private_key()->internal_usages().is_empty()) {
  270. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  271. return;
  272. }
  273. WebIDL::resolve_promise(realm, promise, key_pair);
  274. });
  275. });
  276. return verify_cast<JS::Promise>(*promise->promise());
  277. }
  278. // https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey
  279. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::import_key(Bindings::KeyFormat format, KeyDataType key_data, AlgorithmIdentifier algorithm, bool extractable, Vector<Bindings::KeyUsage> key_usages)
  280. {
  281. auto& realm = this->realm();
  282. // 1. Let format, algorithm, extractable and usages, be the format, algorithm, extractable
  283. // and key_usages parameters passed to the importKey() method, respectively.
  284. Variant<ByteBuffer, Bindings::JsonWebKey, Empty> real_key_data;
  285. // 2. If format is equal to the string "raw", "pkcs8", or "spki":
  286. if (format == Bindings::KeyFormat::Raw || format == Bindings::KeyFormat::Pkcs8 || format == Bindings::KeyFormat::Spki) {
  287. // 1. If the keyData parameter passed to the importKey() method is a JsonWebKey dictionary, throw a TypeError.
  288. if (key_data.has<Bindings::JsonWebKey>()) {
  289. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  290. }
  291. // 2. Let keyData be the result of getting a copy of the bytes held by the keyData parameter passed to the importKey() method.
  292. real_key_data = MUST(WebIDL::get_buffer_source_copy(*key_data.get<JS::Handle<WebIDL::BufferSource>>()->raw_object()));
  293. }
  294. if (format == Bindings::KeyFormat::Jwk) {
  295. // 1. If the keyData parameter passed to the importKey() method is not a JsonWebKey dictionary, throw a TypeError.
  296. if (!key_data.has<Bindings::JsonWebKey>()) {
  297. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "JsonWebKey");
  298. }
  299. // 2. Let keyData be the keyData parameter passed to the importKey() method.
  300. real_key_data = key_data.get<Bindings::JsonWebKey>();
  301. }
  302. // NOTE: The spec jumps to 5 here for some reason?
  303. // 5. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "importKey".
  304. auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "importKey"_string);
  305. // 6. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  306. if (normalized_algorithm.is_error())
  307. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  308. // 7. Let promise be a new Promise.
  309. auto promise = WebIDL::create_promise(realm);
  310. // 8. Return promise and perform the remaining steps in parallel.
  311. Platform::EventLoopPlugin::the().deferred_invoke([&realm, real_key_data = move(real_key_data), normalized_algorithm = normalized_algorithm.release_value(), promise, format, extractable, key_usages = move(key_usages), algorithm = move(algorithm)]() mutable -> void {
  312. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  313. // 9. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  314. // 10. Let result be the CryptoKey object that results from performing the import key operation
  315. // specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.
  316. auto maybe_result = normalized_algorithm.methods->import_key(*normalized_algorithm.parameter, format, real_key_data.downcast<CryptoKey::InternalKeyData>(), extractable, key_usages);
  317. if (maybe_result.is_error()) {
  318. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), maybe_result.release_error()).release_value().value());
  319. return;
  320. }
  321. auto result = maybe_result.release_value();
  322. // 11. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.
  323. if ((result->type() == Bindings::KeyType::Secret || result->type() == Bindings::KeyType::Private) && key_usages.is_empty()) {
  324. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  325. return;
  326. }
  327. // 12. Set the [[extractable]] internal slot of result to extractable.
  328. result->set_extractable(extractable);
  329. // 13. Set the [[usages]] internal slot of result to the normalized value of usages.
  330. normalize_key_usages(key_usages);
  331. result->set_usages(key_usages);
  332. // 14. Resolve promise with result.
  333. WebIDL::resolve_promise(realm, promise, result);
  334. });
  335. return verify_cast<JS::Promise>(*promise->promise());
  336. }
  337. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-exportKey
  338. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::export_key(Bindings::KeyFormat format, JS::NonnullGCPtr<CryptoKey> key)
  339. {
  340. auto& realm = this->realm();
  341. // 1. Let format and key be the format and key parameters passed to the exportKey() method, respectively.
  342. // 2. Let promise be a new Promise.
  343. auto promise = WebIDL::create_promise(realm);
  344. // 3. Return promise and perform the remaining steps in parallel.
  345. Platform::EventLoopPlugin::the().deferred_invoke([&realm, key, promise, format]() -> void {
  346. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  347. // 4. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  348. // 5. If the name member of the [[algorithm]] internal slot of key does not identify a registered algorithm that supports the export key operation,
  349. // then throw a NotSupportedError.
  350. // Note: Handled by the base AlgorithmMethods implementation
  351. auto& algorithm = verify_cast<KeyAlgorithm>(*key->algorithm());
  352. // FIXME: Stash the AlgorithmMethods on the KeyAlgorithm
  353. auto normalized_algorithm_or_error = normalize_an_algorithm(realm, algorithm.name(), "exportKey"_string);
  354. if (normalized_algorithm_or_error.is_error()) {
  355. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), normalized_algorithm_or_error.release_error()).release_value().value());
  356. return;
  357. }
  358. auto normalized_algorithm = normalized_algorithm_or_error.release_value();
  359. // 6. If the [[extractable]] internal slot of key is false, then throw an InvalidAccessError.
  360. if (!key->extractable()) {
  361. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Key is not extractable"_fly_string));
  362. return;
  363. }
  364. // 7. Let result be the result of performing the export key operation specified by the [[algorithm]] internal slot of key using key and format.
  365. auto result_or_error = normalized_algorithm.methods->export_key(format, key);
  366. if (result_or_error.is_error()) {
  367. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result_or_error.release_error()).release_value().value());
  368. return;
  369. }
  370. // 8. Resolve promise with result.
  371. WebIDL::resolve_promise(realm, promise, result_or_error.release_value());
  372. });
  373. return verify_cast<JS::Promise>(*promise->promise());
  374. }
  375. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-sign
  376. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::sign(AlgorithmIdentifier const& algorithm, JS::NonnullGCPtr<CryptoKey> key, JS::Handle<WebIDL::BufferSource> const& data_parameter)
  377. {
  378. auto& realm = this->realm();
  379. auto& vm = this->vm();
  380. // 1. Let algorithm and key be the algorithm and key parameters passed to the sign() method, respectively.
  381. // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the sign() method.
  382. auto data_or_error = WebIDL::get_buffer_source_copy(*data_parameter->raw_object());
  383. if (data_or_error.is_error()) {
  384. VERIFY(data_or_error.error().code() == ENOMEM);
  385. return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)));
  386. }
  387. auto data = data_or_error.release_value();
  388. // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "sign".
  389. auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "sign"_string);
  390. // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  391. if (normalized_algorithm.is_error())
  392. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  393. // 5. Let promise be a new Promise.
  394. auto promise = WebIDL::create_promise(realm);
  395. // 6. Return promise and perform the remaining steps in parallel.
  396. Platform::EventLoopPlugin::the().deferred_invoke([&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, key, data = move(data)]() -> void {
  397. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  398. // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  399. // 8. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.
  400. if (normalized_algorithm.parameter->name != key->algorithm_name()) {
  401. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Algorithm mismatch"_fly_string));
  402. return;
  403. }
  404. // 9. If the [[usages]] internal slot of key does not contain an entry that is "sign", then throw an InvalidAccessError.
  405. if (!key->internal_usages().contains_slow(Bindings::KeyUsage::Sign)) {
  406. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Key does not support signing"_fly_string));
  407. return;
  408. }
  409. // 10. Let result be the result of performing the sign operation specified by normalizedAlgorithm using key and algorithm and with data as message.
  410. auto result = normalized_algorithm.methods->sign(*normalized_algorithm.parameter, key, data);
  411. if (result.is_error()) {
  412. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result.release_error()).release_value().value());
  413. return;
  414. }
  415. // 9. Resolve promise with result.
  416. WebIDL::resolve_promise(realm, promise, result.release_value());
  417. });
  418. return verify_cast<JS::Promise>(*promise->promise());
  419. }
  420. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-verify
  421. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::verify(AlgorithmIdentifier const& algorithm, JS::NonnullGCPtr<CryptoKey> key, JS::Handle<WebIDL::BufferSource> const& signature_data, JS::Handle<WebIDL::BufferSource> const& data_parameter)
  422. {
  423. auto& realm = this->realm();
  424. auto& vm = this->vm();
  425. // 1. Let algorithm and key be the algorithm and key parameters passed to the verify() method, respectively.
  426. // 2. Let signature be the result of getting a copy of the bytes held by the signature parameter passed to the verify() method.
  427. auto signature_or_error = WebIDL::get_buffer_source_copy(*signature_data->raw_object());
  428. if (signature_or_error.is_error()) {
  429. VERIFY(signature_or_error.error().code() == ENOMEM);
  430. return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)));
  431. }
  432. auto signature = signature_or_error.release_value();
  433. // 3. Let data be the result of getting a copy of the bytes held by the data parameter passed to the verify() method.
  434. auto data_or_error = WebIDL::get_buffer_source_copy(*data_parameter->raw_object());
  435. if (data_or_error.is_error()) {
  436. VERIFY(data_or_error.error().code() == ENOMEM);
  437. return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)));
  438. }
  439. auto data = data_or_error.release_value();
  440. // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "verify".
  441. auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "verify"_string);
  442. // 5. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  443. if (normalized_algorithm.is_error())
  444. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  445. // 6. Let promise be a new Promise.
  446. auto promise = WebIDL::create_promise(realm);
  447. // 7. Return promise and perform the remaining steps in parallel.
  448. Platform::EventLoopPlugin::the().deferred_invoke([&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, key, signature = move(signature), data = move(data)]() -> void {
  449. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  450. // 8. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  451. // 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.
  452. if (normalized_algorithm.parameter->name != key->algorithm_name()) {
  453. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Algorithm mismatch"_fly_string));
  454. return;
  455. }
  456. // 10. If the [[usages]] internal slot of key does not contain an entry that is "verify", then throw an InvalidAccessError.
  457. if (!key->internal_usages().contains_slow(Bindings::KeyUsage::Verify)) {
  458. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Key does not support verification"_fly_string));
  459. return;
  460. }
  461. // 11. Let result be the result of performing the verify operation specified by normalizedAlgorithm using key, algorithm and signature and with data as message.
  462. auto result = normalized_algorithm.methods->verify(*normalized_algorithm.parameter, key, signature, data);
  463. if (result.is_error()) {
  464. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result.release_error()).release_value().value());
  465. return;
  466. }
  467. // 12. Resolve promise with result.
  468. WebIDL::resolve_promise(realm, promise, result.release_value());
  469. });
  470. return verify_cast<JS::Promise>(*promise->promise());
  471. }
  472. // https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveBits
  473. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::derive_bits(AlgorithmIdentifier algorithm, JS::NonnullGCPtr<CryptoKey> base_key, u32 length)
  474. {
  475. auto& realm = this->realm();
  476. // 1. Let algorithm, baseKey and length, be the algorithm, baseKey and length parameters passed to the deriveBits() method, respectively.
  477. // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "deriveBits".
  478. auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "deriveBits"_string);
  479. // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  480. if (normalized_algorithm.is_error())
  481. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  482. // 4. Let promise be a new Promise object.
  483. auto promise = WebIDL::create_promise(realm);
  484. // 5. Return promise and perform the remaining steps in parallel.
  485. Platform::EventLoopPlugin::the().deferred_invoke([&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, base_key, length]() -> void {
  486. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  487. // 6. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  488. // 7. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of baseKey then throw an InvalidAccessError.
  489. if (normalized_algorithm.parameter->name != base_key->algorithm_name()) {
  490. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Algorithm mismatch"_fly_string));
  491. return;
  492. }
  493. // 8. If the [[usages]] internal slot of baseKey does not contain an entry that is "deriveBits", then throw an InvalidAccessError.
  494. if (!base_key->internal_usages().contains_slow(Bindings::KeyUsage::Derivebits)) {
  495. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Key does not support deriving bits"_fly_string));
  496. return;
  497. }
  498. // 9. Let result be the result of creating an ArrayBuffer containing the result of performing the derive bits operation specified by normalizedAlgorithm using baseKey, algorithm and length.
  499. auto result = normalized_algorithm.methods->derive_bits(*normalized_algorithm.parameter, base_key, length);
  500. if (result.is_error()) {
  501. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result.release_error()).release_value().value());
  502. return;
  503. }
  504. // 10. Resolve promise with result.
  505. WebIDL::resolve_promise(realm, promise, result.release_value());
  506. });
  507. return verify_cast<JS::Promise>(*promise->promise());
  508. }
  509. SupportedAlgorithmsMap& supported_algorithms_internal()
  510. {
  511. static SupportedAlgorithmsMap s_supported_algorithms;
  512. return s_supported_algorithms;
  513. }
  514. // https://w3c.github.io/webcrypto/#algorithm-normalization-internalS
  515. SupportedAlgorithmsMap supported_algorithms()
  516. {
  517. auto& internal_object = supported_algorithms_internal();
  518. if (!internal_object.is_empty()) {
  519. return internal_object;
  520. }
  521. // 1. For each value, v in the List of supported operations,
  522. // set the v key of the internal object supportedAlgorithms to a new associative container.
  523. auto supported_operations = Vector {
  524. "encrypt"_string,
  525. "decrypt"_string,
  526. "sign"_string,
  527. "verify"_string,
  528. "digest"_string,
  529. "deriveBits"_string,
  530. "wrapKey"_string,
  531. "unwrapKey"_string,
  532. "generateKey"_string,
  533. "importKey"_string,
  534. "exportKey"_string,
  535. "get key length"_string,
  536. };
  537. for (auto& operation : supported_operations) {
  538. internal_object.set(operation, {});
  539. }
  540. // https://w3c.github.io/webcrypto/#algorithm-conventions
  541. // https://w3c.github.io/webcrypto/#sha
  542. define_an_algorithm<SHA>("digest"_string, "SHA-1"_string);
  543. define_an_algorithm<SHA>("digest"_string, "SHA-256"_string);
  544. define_an_algorithm<SHA>("digest"_string, "SHA-384"_string);
  545. define_an_algorithm<SHA>("digest"_string, "SHA-512"_string);
  546. // https://w3c.github.io/webcrypto/#pbkdf2
  547. define_an_algorithm<PBKDF2>("importKey"_string, "PBKDF2"_string);
  548. define_an_algorithm<PBKDF2, PBKDF2Params>("deriveBits"_string, "PBKDF2"_string);
  549. define_an_algorithm<PBKDF2>("get key length"_string, "PBKDF2"_string);
  550. // https://w3c.github.io/webcrypto/#rsa-oaep
  551. define_an_algorithm<RSAOAEP, RsaHashedKeyGenParams>("generateKey"_string, "RSA-OAEP"_string);
  552. define_an_algorithm<RSAOAEP>("exportKey"_string, "RSA-OAEP"_string);
  553. define_an_algorithm<RSAOAEP, RsaHashedImportParams>("importKey"_string, "RSA-OAEP"_string);
  554. define_an_algorithm<RSAOAEP, RsaOaepParams>("encrypt"_string, "RSA-OAEP"_string);
  555. define_an_algorithm<RSAOAEP, RsaOaepParams>("decrypt"_string, "RSA-OAEP"_string);
  556. // https://w3c.github.io/webcrypto/#ecdsa
  557. define_an_algorithm<ECDSA, EcdsaParams>("sign"_string, "ECDSA"_string);
  558. define_an_algorithm<ECDSA, EcdsaParams>("verify"_string, "ECDSA"_string);
  559. define_an_algorithm<ECDSA, EcKeyGenParams>("generateKey"_string, "ECDSA"_string);
  560. // https://wicg.github.io/webcrypto-secure-curves/#ed25519
  561. define_an_algorithm<ED25519>("sign"_string, "Ed25519"_string);
  562. define_an_algorithm<ED25519>("verify"_string, "Ed25519"_string);
  563. define_an_algorithm<ED25519>("generateKey"_string, "Ed25519"_string);
  564. return internal_object;
  565. }
  566. // https://w3c.github.io/webcrypto/#concept-define-an-algorithm
  567. template<typename Methods, typename Param>
  568. void define_an_algorithm(AK::String op, AK::String algorithm)
  569. {
  570. auto& internal_object = supported_algorithms_internal();
  571. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  572. // NOTE: There should always be a container at the op key.
  573. auto maybe_registered_algorithms = internal_object.get(op);
  574. auto registered_algorithms = maybe_registered_algorithms.value();
  575. // 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.
  576. registered_algorithms.set(algorithm, RegisteredAlgorithm { &Methods::create, &Param::from_value });
  577. internal_object.set(op, registered_algorithms);
  578. }
  579. }