SubtleCrypto.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. JS::ThrowCompletionOr<Bindings::Algorithm> SubtleCrypto::normalize_an_algorithm(AlgorithmIdentifier const& algorithm, String operation)
  37. {
  38. auto& realm = this->realm();
  39. // If alg is an instance of a DOMString:
  40. if (algorithm.has<String>()) {
  41. // Return the result of running the normalize an algorithm algorithm,
  42. // with the alg set to a new Algorithm dictionary whose name attribute is alg, and with the op set to op.
  43. auto dictionary = JS::make_handle(JS::Object::create(realm, realm.intrinsics().object_prototype()));
  44. TRY(dictionary->create_data_property("name", JS::PrimitiveString::create(realm.vm(), algorithm.get<String>())));
  45. TRY(dictionary->create_data_property("op", JS::PrimitiveString::create(realm.vm(), operation)));
  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. // FIXME: How do we turn this into an "Algorithm" in a nice way?
  57. // NOTE: For now, we just use the object as-is.
  58. auto initial_algorithm = algorithm.get<JS::Handle<JS::Object>>();
  59. // 3. If an error occurred, return the error and terminate this algorithm.
  60. auto has_name = TRY(initial_algorithm->has_property("name"));
  61. if (!has_name) {
  62. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Algorithm");
  63. }
  64. // 4. Let algName be the value of the name attribute of initialAlg.
  65. auto algorithm_name = TRY(TRY(initial_algorithm->get("name")).to_string(realm.vm()));
  66. String desired_type;
  67. // 5. If registeredAlgorithms contains a key that is a case-insensitive string match for algName:
  68. if (registered_algorithms.contains(algorithm_name)) {
  69. // 1. Set algName to the value of the matching key.
  70. auto it = registered_algorithms.find(algorithm_name);
  71. algorithm_name = (*it).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. // FIXME: This should be a DOMException
  78. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotImplemented, algorithm_name);
  79. }
  80. // 8. Let normalizedAlgorithm be the result of converting the ECMAScript object represented by alg
  81. // to the IDL dictionary type desiredType, as defined by [WebIDL].
  82. // FIXME: Should IDL generate a struct for each of these?
  83. Bindings::Algorithm normalized_algorithm;
  84. // 9. Set the name attribute of normalizedAlgorithm to algName.
  85. normalized_algorithm.name = algorithm_name;
  86. // 10. If an error occurred, return the error and terminate this algorithm.
  87. // FIXME: 11. Let dictionaries be a list consisting of the IDL dictionary type desiredType
  88. // and all of desiredType's inherited dictionaries, in order from least to most derived.
  89. // FIXME: 12. For each dictionary dictionary in dictionaries:
  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. auto promise = WebIDL::create_rejected_promise(realm, WebIDL::OperationError::create(realm, "Failed to copy bytes from ArrayBuffer"_fly_string));
  102. return verify_cast<JS::Promise>(*promise->promise());
  103. }
  104. auto data_buffer = data_buffer_or_error.release_value();
  105. // 3. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "digest".
  106. auto normalized_algorithm = normalize_an_algorithm(algorithm, "digest"_string);
  107. // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  108. // FIXME: Spec bug: link to https://webidl.spec.whatwg.org/#a-promise-rejected-with
  109. if (normalized_algorithm.is_error()) {
  110. auto promise = WebIDL::create_rejected_promise(realm, normalized_algorithm.release_error().release_value().value());
  111. return verify_cast<JS::Promise>(*promise->promise());
  112. }
  113. // 5. Let promise be a new Promise.
  114. auto promise = WebIDL::create_promise(realm);
  115. // 6. Return promise and perform the remaining steps in parallel.
  116. Platform::EventLoopPlugin::the().deferred_invoke([&realm, algorithm_object = normalized_algorithm.release_value(), promise, data_buffer = move(data_buffer)]() -> void {
  117. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  118. // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  119. // FIXME: Need spec reference to https://webidl.spec.whatwg.org/#reject
  120. // 8. Let result be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.
  121. auto algorithm_name = algorithm_object.name;
  122. ::Crypto::Hash::HashKind hash_kind;
  123. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  124. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  125. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  126. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  127. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  128. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  129. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  130. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  131. } else {
  132. WebIDL::reject_promise(realm, promise, WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name))));
  133. return;
  134. }
  135. ::Crypto::Hash::Manager hash { hash_kind };
  136. hash.update(data_buffer);
  137. auto digest = hash.digest();
  138. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  139. if (result_buffer.is_error()) {
  140. WebIDL::reject_promise(realm, promise, WebIDL::OperationError::create(realm, "Failed to create result buffer"_fly_string));
  141. return;
  142. }
  143. auto result = JS::ArrayBuffer::create(realm, result_buffer.release_value());
  144. // 9. Resolve promise with result.
  145. WebIDL::resolve_promise(realm, promise, result);
  146. });
  147. return verify_cast<JS::Promise>(*promise->promise());
  148. }
  149. // https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey
  150. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::import_key(Bindings::KeyFormat format, KeyDataType key_data, AlgorithmIdentifier algorithm, bool extractable, Vector<Bindings::KeyUsage> key_usages)
  151. {
  152. auto& realm = this->realm();
  153. // 1. Let format, algorithm, extractable and usages, be the format, algorithm, extractable
  154. // and key_usages parameters passed to the importKey() method, respectively.
  155. Variant<ByteBuffer, Bindings::JsonWebKey, Empty> real_key_data;
  156. // 2. If format is equal to the string "raw", "pkcs8", or "spki":
  157. if (format == Bindings::KeyFormat::Raw || format == Bindings::KeyFormat::Pkcs8 || format == Bindings::KeyFormat::Spki) {
  158. // 1. If the keyData parameter passed to the importKey() method is a JsonWebKey dictionary, throw a TypeError.
  159. if (key_data.has<Bindings::JsonWebKey>()) {
  160. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  161. }
  162. // 2. Let keyData be the result of getting a copy of the bytes held by the keyData parameter passed to the importKey() method.
  163. real_key_data = MUST(WebIDL::get_buffer_source_copy(*key_data.get<JS::Handle<WebIDL::BufferSource>>()->raw_object()));
  164. }
  165. if (format == Bindings::KeyFormat::Jwk) {
  166. // 1. If the keyData parameter passed to the importKey() method is not a JsonWebKey dictionary, throw a TypeError.
  167. if (!key_data.has<Bindings::JsonWebKey>()) {
  168. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "JsonWebKey");
  169. }
  170. // 2. Let keyData be the keyData parameter passed to the importKey() method.
  171. real_key_data = key_data.get<Bindings::JsonWebKey>();
  172. }
  173. // NOTE: The spec jumps to 5 here for some reason?
  174. // 5. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "importKey".
  175. auto normalized_algorithm = normalize_an_algorithm(algorithm, "importKey"_string);
  176. // 6. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  177. if (normalized_algorithm.is_error()) {
  178. auto promise = WebIDL::create_rejected_promise(realm, normalized_algorithm.release_error().release_value().value());
  179. return verify_cast<JS::Promise>(*promise->promise());
  180. }
  181. // 7. Let promise be a new Promise.
  182. auto promise = WebIDL::create_promise(realm);
  183. // 8. Return promise and perform the remaining steps in parallel.
  184. Platform::EventLoopPlugin::the().deferred_invoke([&realm, this, 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 {
  185. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  186. // 9. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  187. // 10. Let result be the CryptoKey object that results from performing the import key operation
  188. // specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.
  189. if (normalized_algorithm.name != "PBKDF2"sv) {
  190. WebIDL::reject_promise(realm, promise, WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Invalid algorithm '{}'", normalized_algorithm.name))));
  191. return;
  192. }
  193. auto maybe_result = pbkdf2_import_key(real_key_data, algorithm, format, extractable, key_usages);
  194. if (maybe_result.is_error()) {
  195. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), maybe_result.release_error()).release_value().value());
  196. return;
  197. }
  198. auto result = maybe_result.release_value();
  199. // 11. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.
  200. if ((result->type() == Bindings::KeyType::Secret || result->type() == Bindings::KeyType::Private) && key_usages.is_empty()) {
  201. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  202. return;
  203. }
  204. // 12. Set the [[extractable]] internal slot of result to extractable.
  205. result->set_extractable(extractable);
  206. // 13. Set the [[usages]] internal slot of result to the normalized value of usages.
  207. // FIXME: result->set_usages(key_usages);
  208. // 14. Resolve promise with result.
  209. WebIDL::resolve_promise(realm, promise, result);
  210. });
  211. return verify_cast<JS::Promise>(*promise->promise());
  212. }
  213. SubtleCrypto::SupportedAlgorithmsMap& SubtleCrypto::supported_algorithms_internal()
  214. {
  215. static SubtleCrypto::SupportedAlgorithmsMap s_supported_algorithms;
  216. return s_supported_algorithms;
  217. }
  218. // https://w3c.github.io/webcrypto/#algorithm-normalization-internalS
  219. SubtleCrypto::SupportedAlgorithmsMap SubtleCrypto::supported_algorithms()
  220. {
  221. auto& internal_object = supported_algorithms_internal();
  222. if (!internal_object.is_empty()) {
  223. return internal_object;
  224. }
  225. // 1. For each value, v in the List of supported operations,
  226. // set the v key of the internal object supportedAlgorithms to a new associative container.
  227. auto supported_operations = Vector {
  228. "encrypt"_string,
  229. "decrypt"_string,
  230. "sign"_string,
  231. "verify"_string,
  232. "digest"_string,
  233. "deriveBits"_string,
  234. "wrapKey"_string,
  235. "unwrapKey"_string,
  236. "generateKey"_string,
  237. "importKey"_string,
  238. "exportKey"_string,
  239. "get key length"_string,
  240. };
  241. for (auto& operation : supported_operations) {
  242. internal_object.set(operation, {});
  243. }
  244. // https://w3c.github.io/webcrypto/#algorithm-conventions
  245. // https://w3c.github.io/webcrypto/#sha
  246. define_an_algorithm("digest"_string, "SHA1"_string, ""_string);
  247. define_an_algorithm("digest"_string, "SHA-256"_string, ""_string);
  248. define_an_algorithm("digest"_string, "SHA-384"_string, ""_string);
  249. define_an_algorithm("digest"_string, "SHA-512"_string, ""_string);
  250. // https://w3c.github.io/webcrypto/#pbkdf2
  251. define_an_algorithm("importKey"_string, "PBKDF2"_string, ""_string);
  252. // FIXME: define_an_algorithm("deriveBits"_string, "PBKDF2"_string, "Pbkdf2Params"_string);
  253. // FIXME: define_an_algorithm("get key length"_string, "PBKDF2"_string, ""_string);
  254. return internal_object;
  255. }
  256. // https://w3c.github.io/webcrypto/#concept-define-an-algorithm
  257. void SubtleCrypto::define_an_algorithm(String op, String algorithm, String type)
  258. {
  259. auto& internal_object = supported_algorithms_internal();
  260. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  261. // NOTE: There should always be a container at the op key.
  262. auto maybe_registered_algorithms = internal_object.get(op);
  263. auto registered_algorithms = maybe_registered_algorithms.value();
  264. // 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.
  265. registered_algorithms.set(algorithm, type);
  266. internal_object.set(op, registered_algorithms);
  267. }
  268. // https://w3c.github.io/webcrypto/#pbkdf2-operations
  269. WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> SubtleCrypto::pbkdf2_import_key([[maybe_unused]] Variant<ByteBuffer, Bindings::JsonWebKey, Empty> key_data, [[maybe_unused]] AlgorithmIdentifier algorithm_parameter, Bindings::KeyFormat format, bool extractable, Vector<Bindings::KeyUsage> key_usages)
  270. {
  271. auto& realm = this->realm();
  272. // 1. If format is not "raw", throw a NotSupportedError
  273. if (format != Bindings::KeyFormat::Raw) {
  274. return WebIDL::NotSupportedError::create(realm, "Only raw format is supported"_fly_string);
  275. }
  276. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  277. for (auto& usage : key_usages) {
  278. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  279. return WebIDL::SyntaxError::create(realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  280. }
  281. }
  282. // 3. If extractable is not false, then throw a SyntaxError.
  283. if (extractable)
  284. return WebIDL::SyntaxError::create(realm, "extractable must be false"_fly_string);
  285. // 4. Let key be a new CryptoKey representing keyData.
  286. auto key = CryptoKey::create(realm);
  287. // 5. Set the [[type]] internal slot of key to "secret".
  288. key->set_type(Bindings::KeyType::Secret);
  289. // 6. Set the [[extractable]] internal slot of key to false.
  290. key->set_extractable(false);
  291. // 7. Let algorithm be a new KeyAlgorithm object.
  292. auto algorithm = Bindings::KeyAlgorithm::create(realm);
  293. // 8. Set the name attribute of algorithm to "PBKDF2".
  294. algorithm->set_name("PBKDF2"_string);
  295. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  296. key->set_algorithm(algorithm);
  297. // 10. Return key.
  298. return key;
  299. }
  300. }