SubtleCrypto.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. JS_DEFINE_ALLOCATOR(SubtleCrypto);
  27. JS::NonnullGCPtr<SubtleCrypto> SubtleCrypto::create(JS::Realm& realm)
  28. {
  29. return realm.heap().allocate<SubtleCrypto>(realm, realm);
  30. }
  31. SubtleCrypto::SubtleCrypto(JS::Realm& realm)
  32. : PlatformObject(realm)
  33. {
  34. }
  35. SubtleCrypto::~SubtleCrypto() = default;
  36. void SubtleCrypto::initialize(JS::Realm& realm)
  37. {
  38. Base::initialize(realm);
  39. WEB_SET_PROTOTYPE_FOR_INTERFACE(SubtleCrypto);
  40. }
  41. // https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm
  42. WebIDL::ExceptionOr<SubtleCrypto::NormalizedAlgorithmAndParameter> SubtleCrypto::normalize_an_algorithm(AlgorithmIdentifier const& algorithm, String operation)
  43. {
  44. auto& realm = this->realm();
  45. auto& vm = this->vm();
  46. // If alg is an instance of a DOMString:
  47. if (algorithm.has<String>()) {
  48. // Return the result of running the normalize an algorithm algorithm,
  49. // with the alg set to a new Algorithm dictionary whose name attribute is alg, and with the op set to op.
  50. auto dictionary = JS::make_handle(JS::Object::create(realm, realm.intrinsics().object_prototype()));
  51. TRY(dictionary->create_data_property("name", JS::PrimitiveString::create(vm, algorithm.get<String>())));
  52. return normalize_an_algorithm(dictionary, operation);
  53. }
  54. // If alg is an object:
  55. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  56. // NOTE: There should always be a container at the op key.
  57. auto internal_object = supported_algorithms();
  58. auto maybe_registered_algorithms = internal_object.get(operation);
  59. auto registered_algorithms = maybe_registered_algorithms.value();
  60. // 2. Let initialAlg be the result of converting the ECMAScript object represented by alg to
  61. // the IDL dictionary type Algorithm, as defined by [WebIDL].
  62. // 3. If an error occurred, return the error and terminate this algorithm.
  63. // Note: We're not going to bother creating an Algorithm object, all we want is the name attribute so that we can
  64. // fetch the actual algorithm factory from the registeredAlgorithms map.
  65. auto initial_algorithm = TRY(algorithm.get<JS::Handle<JS::Object>>()->get("name"));
  66. // 4. Let algName be the value of the name attribute of initialAlg.
  67. auto algorithm_name = TRY(initial_algorithm.to_string(vm));
  68. RegisteredAlgorithm desired_type;
  69. // 5. If registeredAlgorithms contains a key that is a case-insensitive string match for algName:
  70. if (auto it = registered_algorithms.find(algorithm_name); it != registered_algorithms.end()) {
  71. // 1. Set algName to the value of the matching key.
  72. // 2. Let desiredType be the IDL dictionary type stored at algName in registeredAlgorithms.
  73. desired_type = it->value;
  74. } else {
  75. // Otherwise:
  76. // Return a new NotSupportedError and terminate this algorithm.
  77. return WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Algorithm '{}' is not supported", algorithm_name)));
  78. }
  79. // 8. Let normalizedAlgorithm be the result of converting the ECMAScript object represented by alg
  80. // to the IDL dictionary type desiredType, as defined by [WebIDL].
  81. // 9. Set the name attribute of normalizedAlgorithm to algName.
  82. // 10. If an error occurred, return the error and terminate this algorithm.
  83. // 11. Let dictionaries be a list consisting of the IDL dictionary type desiredType
  84. // and all of desiredType's inherited dictionaries, in order from least to most derived.
  85. // 12. For each dictionary dictionary in dictionaries:
  86. // Note: All of these steps are handled by the create_methods and parameter_from_value methods.
  87. auto methods = desired_type.create_methods(realm);
  88. auto parameter = TRY(desired_type.parameter_from_value(vm, algorithm.get<JS::Handle<JS::Object>>()));
  89. auto normalized_algorithm = NormalizedAlgorithmAndParameter { move(methods), move(parameter) };
  90. // 13. Return normalizedAlgorithm.
  91. return normalized_algorithm;
  92. }
  93. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-digest
  94. JS::NonnullGCPtr<JS::Promise> SubtleCrypto::digest(AlgorithmIdentifier const& algorithm, JS::Handle<WebIDL::BufferSource> const& data)
  95. {
  96. auto& realm = this->realm();
  97. // 1. Let algorithm be the algorithm parameter passed to the digest() method.
  98. // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the digest() method.
  99. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*data->raw_object());
  100. if (data_buffer_or_error.is_error())
  101. return WebIDL::create_rejected_promise_from_exception(realm, WebIDL::OperationError::create(realm, "Failed to copy bytes from ArrayBuffer"_fly_string));
  102. auto data_buffer = data_buffer_or_error.release_value();
  103. // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "digest".
  104. auto normalized_algorithm = normalize_an_algorithm(algorithm, "digest"_string);
  105. // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  106. // FIXME: Spec bug: link to https://webidl.spec.whatwg.org/#a-promise-rejected-with
  107. if (normalized_algorithm.is_error())
  108. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  109. // 5. Let promise be a new Promise.
  110. auto promise = WebIDL::create_promise(realm);
  111. // 6. Return promise and perform the remaining steps in parallel.
  112. Platform::EventLoopPlugin::the().deferred_invoke([&realm, algorithm_object = normalized_algorithm.release_value(), promise, data_buffer = move(data_buffer)]() -> void {
  113. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  114. // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  115. // FIXME: Need spec reference to https://webidl.spec.whatwg.org/#reject
  116. // 8. Let result be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.
  117. auto result = algorithm_object.methods->digest(*algorithm_object.parameter, data_buffer);
  118. if (result.is_exception()) {
  119. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result.release_error()).release_value().value());
  120. return;
  121. }
  122. // 9. Resolve promise with result.
  123. WebIDL::resolve_promise(realm, promise, result.release_value());
  124. });
  125. return verify_cast<JS::Promise>(*promise->promise());
  126. }
  127. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-generateKey
  128. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::generate_key(AlgorithmIdentifier algorithm, bool extractable, Vector<Bindings::KeyUsage> key_usages)
  129. {
  130. auto& realm = this->realm();
  131. // 1. Let algorithm, extractable and usages be the algorithm, extractable and keyUsages
  132. // parameters passed to the generateKey() method, respectively.
  133. // 2. Let normalizedAlgorithm be the result of normalizing an algorithm,
  134. // with alg set to algorithm and op set to "generateKey".
  135. auto normalized_algorithm = normalize_an_algorithm(algorithm, "generateKey"_string);
  136. // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  137. if (normalized_algorithm.is_error())
  138. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  139. // 4. Let promise be a new Promise.
  140. auto promise = WebIDL::create_promise(realm);
  141. // 5. Return promise and perform the remaining steps in parallel.
  142. Platform::EventLoopPlugin::the().deferred_invoke([&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, extractable, key_usages = move(key_usages)]() -> void {
  143. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  144. // 6. If the following steps or referenced procedures say to throw an error, reject promise with
  145. // the returned error and then terminate the algorithm.
  146. // 7. Let result be the result of performing the generate key operation specified by normalizedAlgorithm
  147. // using algorithm, extractable and usages.
  148. auto result_or_error = normalized_algorithm.methods->generate_key(*normalized_algorithm.parameter, extractable, key_usages);
  149. if (result_or_error.is_error()) {
  150. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result_or_error.release_error()).release_value().value());
  151. return;
  152. }
  153. auto result = result_or_error.release_value();
  154. // 8. If result is a CryptoKey object:
  155. // If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.
  156. // If result is a CryptoKeyPair object:
  157. // If the [[usages]] internal slot of the privateKey attribute of result is the empty sequence, then throw a SyntaxError.
  158. // 9. Resolve promise with result.
  159. result.visit(
  160. [&](JS::NonnullGCPtr<CryptoKey>& key) {
  161. if ((key->type() == Bindings::KeyType::Secret || key->type() == Bindings::KeyType::Private) && key_usages.is_empty()) {
  162. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  163. return;
  164. }
  165. WebIDL::resolve_promise(realm, promise, key);
  166. },
  167. [&](JS::NonnullGCPtr<CryptoKeyPair>& key_pair) {
  168. if (key_pair->private_key()->internal_usages().is_empty()) {
  169. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  170. return;
  171. }
  172. WebIDL::resolve_promise(realm, promise, key_pair);
  173. });
  174. });
  175. return verify_cast<JS::Promise>(*promise->promise());
  176. }
  177. // https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey
  178. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::import_key(Bindings::KeyFormat format, KeyDataType key_data, AlgorithmIdentifier algorithm, bool extractable, Vector<Bindings::KeyUsage> key_usages)
  179. {
  180. auto& realm = this->realm();
  181. // 1. Let format, algorithm, extractable and usages, be the format, algorithm, extractable
  182. // and key_usages parameters passed to the importKey() method, respectively.
  183. Variant<ByteBuffer, Bindings::JsonWebKey, Empty> real_key_data;
  184. // 2. If format is equal to the string "raw", "pkcs8", or "spki":
  185. if (format == Bindings::KeyFormat::Raw || format == Bindings::KeyFormat::Pkcs8 || format == Bindings::KeyFormat::Spki) {
  186. // 1. If the keyData parameter passed to the importKey() method is a JsonWebKey dictionary, throw a TypeError.
  187. if (key_data.has<Bindings::JsonWebKey>()) {
  188. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  189. }
  190. // 2. Let keyData be the result of getting a copy of the bytes held by the keyData parameter passed to the importKey() method.
  191. real_key_data = MUST(WebIDL::get_buffer_source_copy(*key_data.get<JS::Handle<WebIDL::BufferSource>>()->raw_object()));
  192. }
  193. if (format == Bindings::KeyFormat::Jwk) {
  194. // 1. If the keyData parameter passed to the importKey() method is not a JsonWebKey dictionary, throw a TypeError.
  195. if (!key_data.has<Bindings::JsonWebKey>()) {
  196. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "JsonWebKey");
  197. }
  198. // 2. Let keyData be the keyData parameter passed to the importKey() method.
  199. real_key_data = key_data.get<Bindings::JsonWebKey>();
  200. }
  201. // NOTE: The spec jumps to 5 here for some reason?
  202. // 5. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "importKey".
  203. auto normalized_algorithm = normalize_an_algorithm(algorithm, "importKey"_string);
  204. // 6. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  205. if (normalized_algorithm.is_error())
  206. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  207. // 7. Let promise be a new Promise.
  208. auto promise = WebIDL::create_promise(realm);
  209. // 8. Return promise and perform the remaining steps in parallel.
  210. 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 {
  211. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  212. // 9. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  213. // 10. Let result be the CryptoKey object that results from performing the import key operation
  214. // specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.
  215. auto maybe_result = normalized_algorithm.methods->import_key(*normalized_algorithm.parameter, format, real_key_data.downcast<CryptoKey::InternalKeyData>(), extractable, key_usages);
  216. if (maybe_result.is_error()) {
  217. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), maybe_result.release_error()).release_value().value());
  218. return;
  219. }
  220. auto result = maybe_result.release_value();
  221. // 11. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.
  222. if ((result->type() == Bindings::KeyType::Secret || result->type() == Bindings::KeyType::Private) && key_usages.is_empty()) {
  223. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  224. return;
  225. }
  226. // 12. Set the [[extractable]] internal slot of result to extractable.
  227. result->set_extractable(extractable);
  228. // 13. Set the [[usages]] internal slot of result to the normalized value of usages.
  229. normalize_key_usages(key_usages);
  230. result->set_usages(key_usages);
  231. // 14. Resolve promise with result.
  232. WebIDL::resolve_promise(realm, promise, result);
  233. });
  234. return verify_cast<JS::Promise>(*promise->promise());
  235. }
  236. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-exportKey
  237. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::export_key(Bindings::KeyFormat format, JS::NonnullGCPtr<CryptoKey> key)
  238. {
  239. auto& realm = this->realm();
  240. // 1. Let format and key be the format and key parameters passed to the exportKey() method, respectively.
  241. // 2. Let promise be a new Promise.
  242. auto promise = WebIDL::create_promise(realm);
  243. // 3. Return promise and perform the remaining steps in parallel.
  244. Platform::EventLoopPlugin::the().deferred_invoke([&realm, key, this, promise, format]() -> void {
  245. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  246. // 4. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  247. // 5. If the name member of the [[algorithm]] internal slot of key does not identify a registered algorithm that supports the export key operation,
  248. // then throw a NotSupportedError.
  249. // Note: Handled by the base AlgorithmMethods implementation
  250. auto& algorithm = verify_cast<KeyAlgorithm>(*key->algorithm());
  251. // FIXME: Stash the AlgorithmMethods on the KeyAlgorithm
  252. auto normalized_algorithm_or_error = normalize_an_algorithm(algorithm.name(), "exportKey"_string);
  253. if (normalized_algorithm_or_error.is_error()) {
  254. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), normalized_algorithm_or_error.release_error()).release_value().value());
  255. return;
  256. }
  257. auto normalized_algorithm = normalized_algorithm_or_error.release_value();
  258. // 6. If the [[extractable]] internal slot of key is false, then throw an InvalidAccessError.
  259. if (!key->extractable()) {
  260. WebIDL::reject_promise(realm, promise, WebIDL::InvalidAccessError::create(realm, "Key is not extractable"_fly_string));
  261. return;
  262. }
  263. // 7. Let result be the result of performing the export key operation specified by the [[algorithm]] internal slot of key using key and format.
  264. auto result_or_error = normalized_algorithm.methods->export_key(format, key);
  265. if (result_or_error.is_error()) {
  266. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), result_or_error.release_error()).release_value().value());
  267. return;
  268. }
  269. // 8. Resolve promise with result.
  270. WebIDL::resolve_promise(realm, promise, result_or_error.release_value());
  271. });
  272. return verify_cast<JS::Promise>(*promise->promise());
  273. }
  274. SubtleCrypto::SupportedAlgorithmsMap& SubtleCrypto::supported_algorithms_internal()
  275. {
  276. static SubtleCrypto::SupportedAlgorithmsMap s_supported_algorithms;
  277. return s_supported_algorithms;
  278. }
  279. // https://w3c.github.io/webcrypto/#algorithm-normalization-internalS
  280. SubtleCrypto::SupportedAlgorithmsMap SubtleCrypto::supported_algorithms()
  281. {
  282. auto& internal_object = supported_algorithms_internal();
  283. if (!internal_object.is_empty()) {
  284. return internal_object;
  285. }
  286. // 1. For each value, v in the List of supported operations,
  287. // set the v key of the internal object supportedAlgorithms to a new associative container.
  288. auto supported_operations = Vector {
  289. "encrypt"_string,
  290. "decrypt"_string,
  291. "sign"_string,
  292. "verify"_string,
  293. "digest"_string,
  294. "deriveBits"_string,
  295. "wrapKey"_string,
  296. "unwrapKey"_string,
  297. "generateKey"_string,
  298. "importKey"_string,
  299. "exportKey"_string,
  300. "get key length"_string,
  301. };
  302. for (auto& operation : supported_operations) {
  303. internal_object.set(operation, {});
  304. }
  305. // https://w3c.github.io/webcrypto/#algorithm-conventions
  306. // https://w3c.github.io/webcrypto/#sha
  307. define_an_algorithm<SHA>("digest"_string, "SHA-1"_string);
  308. define_an_algorithm<SHA>("digest"_string, "SHA-256"_string);
  309. define_an_algorithm<SHA>("digest"_string, "SHA-384"_string);
  310. define_an_algorithm<SHA>("digest"_string, "SHA-512"_string);
  311. // https://w3c.github.io/webcrypto/#pbkdf2
  312. define_an_algorithm<PBKDF2>("importKey"_string, "PBKDF2"_string);
  313. // FIXME: define_an_algorithm("deriveBits"_string, "PBKDF2"_string, "Pbkdf2Params"_string);
  314. // FIXME: define_an_algorithm("get key length"_string, "PBKDF2"_string, ""_string);
  315. // https://w3c.github.io/webcrypto/#rsa-oaep
  316. define_an_algorithm<RSAOAEP, RsaHashedKeyGenParams>("generateKey"_string, "RSA-OAEP"_string);
  317. define_an_algorithm<RSAOAEP>("exportKey"_string, "RSA-OAEP"_string);
  318. // FIXME: encrypt, decrypt, importKey
  319. return internal_object;
  320. }
  321. // https://w3c.github.io/webcrypto/#concept-define-an-algorithm
  322. template<typename Methods, typename Param>
  323. void SubtleCrypto::define_an_algorithm(AK::String op, AK::String algorithm)
  324. {
  325. auto& internal_object = supported_algorithms_internal();
  326. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  327. // NOTE: There should always be a container at the op key.
  328. auto maybe_registered_algorithms = internal_object.get(op);
  329. auto registered_algorithms = maybe_registered_algorithms.value();
  330. // 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.
  331. registered_algorithms.set(algorithm, RegisteredAlgorithm { &Methods::create, &Param::from_value });
  332. internal_object.set(op, registered_algorithms);
  333. }
  334. }