SubtleCrypto.cpp 14 KB

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