SubtleCrypto.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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/SubtleCrypto.h>
  14. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  15. #include <LibWeb/Platform/EventLoopPlugin.h>
  16. #include <LibWeb/WebIDL/AbstractOperations.h>
  17. #include <LibWeb/WebIDL/Buffers.h>
  18. #include <LibWeb/WebIDL/ExceptionOr.h>
  19. #include <LibWeb/WebIDL/Promise.h>
  20. namespace Web::Crypto {
  21. static void normalize_key_usages(Vector<Bindings::KeyUsage>& key_usages)
  22. {
  23. quick_sort(key_usages);
  24. }
  25. JS_DEFINE_ALLOCATOR(SubtleCrypto);
  26. JS::NonnullGCPtr<SubtleCrypto> SubtleCrypto::create(JS::Realm& realm)
  27. {
  28. return realm.heap().allocate<SubtleCrypto>(realm, realm);
  29. }
  30. SubtleCrypto::SubtleCrypto(JS::Realm& realm)
  31. : PlatformObject(realm)
  32. {
  33. }
  34. SubtleCrypto::~SubtleCrypto() = default;
  35. void SubtleCrypto::initialize(JS::Realm& realm)
  36. {
  37. Base::initialize(realm);
  38. set_prototype(&Bindings::ensure_web_prototype<Bindings::SubtleCryptoPrototype>(realm, "SubtleCrypto"_fly_string));
  39. }
  40. // https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm
  41. WebIDL::ExceptionOr<SubtleCrypto::NormalizedAlgorithmAndParameter> SubtleCrypto::normalize_an_algorithm(AlgorithmIdentifier const& algorithm, String operation)
  42. {
  43. auto& realm = this->realm();
  44. auto& vm = this->vm();
  45. // If alg is an instance of a DOMString:
  46. if (algorithm.has<String>()) {
  47. // Return the result of running the normalize an algorithm algorithm,
  48. // with the alg set to a new Algorithm dictionary whose name attribute is alg, and with the op set to op.
  49. auto dictionary = JS::make_handle(JS::Object::create(realm, realm.intrinsics().object_prototype()));
  50. TRY(dictionary->create_data_property("name", JS::PrimitiveString::create(vm, algorithm.get<String>())));
  51. return normalize_an_algorithm(dictionary, operation);
  52. }
  53. // If alg is an object:
  54. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  55. // NOTE: There should always be a container at the op key.
  56. auto internal_object = supported_algorithms();
  57. auto maybe_registered_algorithms = internal_object.get(operation);
  58. auto registered_algorithms = maybe_registered_algorithms.value();
  59. // 2. Let initialAlg be the result of converting the ECMAScript object represented by alg to
  60. // the IDL dictionary type Algorithm, as defined by [WebIDL].
  61. // 3. If an error occurred, return the error and terminate this algorithm.
  62. // Note: We're not going to bother creating an Algorithm object, all we want is the name attribute so that we can
  63. // fetch the actual algorithm factory from the registeredAlgorithms map.
  64. auto initial_algorithm = TRY(algorithm.get<JS::Handle<JS::Object>>()->get("name"));
  65. // 4. Let algName be the value of the name attribute of initialAlg.
  66. auto algorithm_name = TRY(initial_algorithm.to_string(vm));
  67. RegisteredAlgorithm desired_type;
  68. // 5. If registeredAlgorithms contains a key that is a case-insensitive string match for algName:
  69. if (auto it = registered_algorithms.find(algorithm_name); it != registered_algorithms.end()) {
  70. // 1. Set algName to the value of the matching key.
  71. // 2. Let desiredType be the IDL dictionary type stored at algName in registeredAlgorithms.
  72. desired_type = it->value;
  73. } else {
  74. // Otherwise:
  75. // Return a new NotSupportedError and terminate this algorithm.
  76. return WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Algorithm '{}' is not supported", algorithm_name)));
  77. }
  78. // 8. Let normalizedAlgorithm be the result of converting the ECMAScript object represented by alg
  79. // to the IDL dictionary type desiredType, as defined by [WebIDL].
  80. // 9. Set the name attribute of normalizedAlgorithm to algName.
  81. // 10. If an error occurred, return the error and terminate this algorithm.
  82. // 11. Let dictionaries be a list consisting of the IDL dictionary type desiredType
  83. // and all of desiredType's inherited dictionaries, in order from least to most derived.
  84. // 12. For each dictionary dictionary in dictionaries:
  85. // Note: All of these steps are handled by the create_methods and parameter_from_value methods.
  86. auto methods = desired_type.create_methods(realm);
  87. auto parameter = TRY(desired_type.parameter_from_value(vm, algorithm.get<JS::Handle<JS::Object>>()));
  88. auto normalized_algorithm = NormalizedAlgorithmAndParameter { move(methods), move(parameter) };
  89. // 13. Return normalizedAlgorithm.
  90. return normalized_algorithm;
  91. }
  92. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-digest
  93. JS::NonnullGCPtr<JS::Promise> SubtleCrypto::digest(AlgorithmIdentifier const& algorithm, JS::Handle<WebIDL::BufferSource> const& data)
  94. {
  95. auto& realm = this->realm();
  96. // 1. Let algorithm be the algorithm parameter passed to the digest() method.
  97. // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the digest() method.
  98. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*data->raw_object());
  99. if (data_buffer_or_error.is_error())
  100. return WebIDL::create_rejected_promise_from_exception(realm, WebIDL::OperationError::create(realm, "Failed to copy bytes from ArrayBuffer"_fly_string));
  101. auto data_buffer = data_buffer_or_error.release_value();
  102. // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "digest".
  103. auto normalized_algorithm = normalize_an_algorithm(algorithm, "digest"_string);
  104. // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  105. // FIXME: Spec bug: link to https://webidl.spec.whatwg.org/#a-promise-rejected-with
  106. if (normalized_algorithm.is_error())
  107. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  108. // 5. Let promise be a new Promise.
  109. auto promise = WebIDL::create_promise(realm);
  110. // 6. Return promise and perform the remaining steps in parallel.
  111. Platform::EventLoopPlugin::the().deferred_invoke([&realm, algorithm_object = normalized_algorithm.release_value(), promise, data_buffer = move(data_buffer)]() -> void {
  112. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  113. // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  114. // FIXME: Need spec reference to https://webidl.spec.whatwg.org/#reject
  115. // 8. Let result be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.
  116. auto result = algorithm_object.methods->digest(*algorithm_object.parameter, data_buffer);
  117. if (result.is_exception()) {
  118. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result.release_error()).release_value().value());
  119. return;
  120. }
  121. // 9. Resolve promise with result.
  122. WebIDL::resolve_promise(realm, promise, result.release_value());
  123. });
  124. return verify_cast<JS::Promise>(*promise->promise());
  125. }
  126. // https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey
  127. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::import_key(Bindings::KeyFormat format, KeyDataType key_data, AlgorithmIdentifier algorithm, bool extractable, Vector<Bindings::KeyUsage> key_usages)
  128. {
  129. auto& realm = this->realm();
  130. // 1. Let format, algorithm, extractable and usages, be the format, algorithm, extractable
  131. // and key_usages parameters passed to the importKey() method, respectively.
  132. Variant<ByteBuffer, Bindings::JsonWebKey, Empty> real_key_data;
  133. // 2. If format is equal to the string "raw", "pkcs8", or "spki":
  134. if (format == Bindings::KeyFormat::Raw || format == Bindings::KeyFormat::Pkcs8 || format == Bindings::KeyFormat::Spki) {
  135. // 1. If the keyData parameter passed to the importKey() method is a JsonWebKey dictionary, throw a TypeError.
  136. if (key_data.has<Bindings::JsonWebKey>()) {
  137. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  138. }
  139. // 2. Let keyData be the result of getting a copy of the bytes held by the keyData parameter passed to the importKey() method.
  140. real_key_data = MUST(WebIDL::get_buffer_source_copy(*key_data.get<JS::Handle<WebIDL::BufferSource>>()->raw_object()));
  141. }
  142. if (format == Bindings::KeyFormat::Jwk) {
  143. // 1. If the keyData parameter passed to the importKey() method is not a JsonWebKey dictionary, throw a TypeError.
  144. if (!key_data.has<Bindings::JsonWebKey>()) {
  145. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "JsonWebKey");
  146. }
  147. // 2. Let keyData be the keyData parameter passed to the importKey() method.
  148. real_key_data = key_data.get<Bindings::JsonWebKey>();
  149. }
  150. // NOTE: The spec jumps to 5 here for some reason?
  151. // 5. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "importKey".
  152. auto normalized_algorithm = normalize_an_algorithm(algorithm, "importKey"_string);
  153. // 6. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  154. if (normalized_algorithm.is_error())
  155. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  156. // 7. Let promise be a new Promise.
  157. auto promise = WebIDL::create_promise(realm);
  158. // 8. Return promise and perform the remaining steps in parallel.
  159. 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 {
  160. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  161. // 9. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  162. // 10. Let result be the CryptoKey object that results from performing the import key operation
  163. // specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.
  164. auto maybe_result = normalized_algorithm.methods->import_key(*normalized_algorithm.parameter, format, real_key_data.downcast<CryptoKey::InternalKeyData>(), extractable, key_usages);
  165. if (maybe_result.is_error()) {
  166. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), maybe_result.release_error()).release_value().value());
  167. return;
  168. }
  169. auto result = maybe_result.release_value();
  170. // 11. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.
  171. if ((result->type() == Bindings::KeyType::Secret || result->type() == Bindings::KeyType::Private) && key_usages.is_empty()) {
  172. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  173. return;
  174. }
  175. // 12. Set the [[extractable]] internal slot of result to extractable.
  176. result->set_extractable(extractable);
  177. // 13. Set the [[usages]] internal slot of result to the normalized value of usages.
  178. normalize_key_usages(key_usages);
  179. result->set_usages(key_usages);
  180. // 14. Resolve promise with result.
  181. WebIDL::resolve_promise(realm, promise, result);
  182. });
  183. return verify_cast<JS::Promise>(*promise->promise());
  184. }
  185. SubtleCrypto::SupportedAlgorithmsMap& SubtleCrypto::supported_algorithms_internal()
  186. {
  187. static SubtleCrypto::SupportedAlgorithmsMap s_supported_algorithms;
  188. return s_supported_algorithms;
  189. }
  190. // https://w3c.github.io/webcrypto/#algorithm-normalization-internalS
  191. SubtleCrypto::SupportedAlgorithmsMap SubtleCrypto::supported_algorithms()
  192. {
  193. auto& internal_object = supported_algorithms_internal();
  194. if (!internal_object.is_empty()) {
  195. return internal_object;
  196. }
  197. // 1. For each value, v in the List of supported operations,
  198. // set the v key of the internal object supportedAlgorithms to a new associative container.
  199. auto supported_operations = Vector {
  200. "encrypt"_string,
  201. "decrypt"_string,
  202. "sign"_string,
  203. "verify"_string,
  204. "digest"_string,
  205. "deriveBits"_string,
  206. "wrapKey"_string,
  207. "unwrapKey"_string,
  208. "generateKey"_string,
  209. "importKey"_string,
  210. "exportKey"_string,
  211. "get key length"_string,
  212. };
  213. for (auto& operation : supported_operations) {
  214. internal_object.set(operation, {});
  215. }
  216. // https://w3c.github.io/webcrypto/#algorithm-conventions
  217. // https://w3c.github.io/webcrypto/#sha
  218. define_an_algorithm<SHA>("digest"_string, "SHA-1"_string);
  219. define_an_algorithm<SHA>("digest"_string, "SHA-256"_string);
  220. define_an_algorithm<SHA>("digest"_string, "SHA-384"_string);
  221. define_an_algorithm<SHA>("digest"_string, "SHA-512"_string);
  222. // https://w3c.github.io/webcrypto/#pbkdf2
  223. define_an_algorithm<PBKDF2>("importKey"_string, "PBKDF2"_string);
  224. // FIXME: define_an_algorithm("deriveBits"_string, "PBKDF2"_string, "Pbkdf2Params"_string);
  225. // FIXME: define_an_algorithm("get key length"_string, "PBKDF2"_string, ""_string);
  226. return internal_object;
  227. }
  228. // https://w3c.github.io/webcrypto/#concept-define-an-algorithm
  229. template<typename Methods, typename Param>
  230. void SubtleCrypto::define_an_algorithm(AK::String op, AK::String algorithm)
  231. {
  232. auto& internal_object = supported_algorithms_internal();
  233. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  234. // NOTE: There should always be a container at the op key.
  235. auto maybe_registered_algorithms = internal_object.get(op);
  236. auto registered_algorithms = maybe_registered_algorithms.value();
  237. // 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.
  238. registered_algorithms.set(algorithm, RegisteredAlgorithm { &Methods::create, &Param::from_value });
  239. internal_object.set(op, registered_algorithms);
  240. }
  241. }