SubtleCrypto.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. 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 algorithm_name = algorithm_object.name;
  118. ::Crypto::Hash::HashKind hash_kind;
  119. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  120. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  121. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  122. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  123. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  124. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  125. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  126. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  127. } else {
  128. WebIDL::reject_promise(realm, promise, WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name))));
  129. return;
  130. }
  131. ::Crypto::Hash::Manager hash { hash_kind };
  132. hash.update(data_buffer);
  133. auto digest = hash.digest();
  134. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  135. if (result_buffer.is_error()) {
  136. WebIDL::reject_promise(realm, promise, WebIDL::OperationError::create(realm, "Failed to create result buffer"_fly_string));
  137. return;
  138. }
  139. auto result = JS::ArrayBuffer::create(realm, result_buffer.release_value());
  140. // 9. Resolve promise with result.
  141. WebIDL::resolve_promise(realm, promise, result);
  142. });
  143. return verify_cast<JS::Promise>(*promise->promise());
  144. }
  145. // https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey
  146. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Promise>> SubtleCrypto::import_key(Bindings::KeyFormat format, KeyDataType key_data, AlgorithmIdentifier algorithm, bool extractable, Vector<Bindings::KeyUsage> key_usages)
  147. {
  148. auto& realm = this->realm();
  149. // 1. Let format, algorithm, extractable and usages, be the format, algorithm, extractable
  150. // and key_usages parameters passed to the importKey() method, respectively.
  151. Variant<ByteBuffer, Bindings::JsonWebKey, Empty> real_key_data;
  152. // 2. If format is equal to the string "raw", "pkcs8", or "spki":
  153. if (format == Bindings::KeyFormat::Raw || format == Bindings::KeyFormat::Pkcs8 || format == Bindings::KeyFormat::Spki) {
  154. // 1. If the keyData parameter passed to the importKey() method is a JsonWebKey dictionary, throw a TypeError.
  155. if (key_data.has<Bindings::JsonWebKey>()) {
  156. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  157. }
  158. // 2. Let keyData be the result of getting a copy of the bytes held by the keyData parameter passed to the importKey() method.
  159. real_key_data = MUST(WebIDL::get_buffer_source_copy(*key_data.get<JS::Handle<WebIDL::BufferSource>>()->raw_object()));
  160. }
  161. if (format == Bindings::KeyFormat::Jwk) {
  162. // 1. If the keyData parameter passed to the importKey() method is not a JsonWebKey dictionary, throw a TypeError.
  163. if (!key_data.has<Bindings::JsonWebKey>()) {
  164. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "JsonWebKey");
  165. }
  166. // 2. Let keyData be the keyData parameter passed to the importKey() method.
  167. real_key_data = key_data.get<Bindings::JsonWebKey>();
  168. }
  169. // NOTE: The spec jumps to 5 here for some reason?
  170. // 5. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "importKey".
  171. auto normalized_algorithm = normalize_an_algorithm(algorithm, "importKey"_string);
  172. // 6. If an error occurred, return a Promise rejected with normalizedAlgorithm.
  173. if (normalized_algorithm.is_error())
  174. return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());
  175. // 7. Let promise be a new Promise.
  176. auto promise = WebIDL::create_promise(realm);
  177. // 8. Return promise and perform the remaining steps in parallel.
  178. 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 {
  179. HTML::TemporaryExecutionContext context(Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  180. // 9. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  181. // 10. Let result be the CryptoKey object that results from performing the import key operation
  182. // specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.
  183. if (normalized_algorithm.name != "PBKDF2"sv) {
  184. WebIDL::reject_promise(realm, promise, WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Invalid algorithm '{}'", normalized_algorithm.name))));
  185. return;
  186. }
  187. auto maybe_result = pbkdf2_import_key(real_key_data, algorithm, format, extractable, key_usages);
  188. if (maybe_result.is_error()) {
  189. WebIDL::reject_promise(realm, promise, Bindings::dom_exception_to_throw_completion(realm.vm(), maybe_result.release_error()).release_value().value());
  190. return;
  191. }
  192. auto result = maybe_result.release_value();
  193. // 11. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.
  194. if ((result->type() == Bindings::KeyType::Secret || result->type() == Bindings::KeyType::Private) && key_usages.is_empty()) {
  195. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "usages must not be empty"_fly_string));
  196. return;
  197. }
  198. // 12. Set the [[extractable]] internal slot of result to extractable.
  199. result->set_extractable(extractable);
  200. // 13. Set the [[usages]] internal slot of result to the normalized value of usages.
  201. // FIXME: result->set_usages(key_usages);
  202. // 14. Resolve promise with result.
  203. WebIDL::resolve_promise(realm, promise, result);
  204. });
  205. return verify_cast<JS::Promise>(*promise->promise());
  206. }
  207. SubtleCrypto::SupportedAlgorithmsMap& SubtleCrypto::supported_algorithms_internal()
  208. {
  209. static SubtleCrypto::SupportedAlgorithmsMap s_supported_algorithms;
  210. return s_supported_algorithms;
  211. }
  212. // https://w3c.github.io/webcrypto/#algorithm-normalization-internalS
  213. SubtleCrypto::SupportedAlgorithmsMap SubtleCrypto::supported_algorithms()
  214. {
  215. auto& internal_object = supported_algorithms_internal();
  216. if (!internal_object.is_empty()) {
  217. return internal_object;
  218. }
  219. // 1. For each value, v in the List of supported operations,
  220. // set the v key of the internal object supportedAlgorithms to a new associative container.
  221. auto supported_operations = Vector {
  222. "encrypt"_string,
  223. "decrypt"_string,
  224. "sign"_string,
  225. "verify"_string,
  226. "digest"_string,
  227. "deriveBits"_string,
  228. "wrapKey"_string,
  229. "unwrapKey"_string,
  230. "generateKey"_string,
  231. "importKey"_string,
  232. "exportKey"_string,
  233. "get key length"_string,
  234. };
  235. for (auto& operation : supported_operations) {
  236. internal_object.set(operation, {});
  237. }
  238. // https://w3c.github.io/webcrypto/#algorithm-conventions
  239. // https://w3c.github.io/webcrypto/#sha
  240. define_an_algorithm("digest"_string, "SHA-1"_string, ""_string);
  241. define_an_algorithm("digest"_string, "SHA-256"_string, ""_string);
  242. define_an_algorithm("digest"_string, "SHA-384"_string, ""_string);
  243. define_an_algorithm("digest"_string, "SHA-512"_string, ""_string);
  244. // https://w3c.github.io/webcrypto/#pbkdf2
  245. define_an_algorithm("importKey"_string, "PBKDF2"_string, ""_string);
  246. // FIXME: define_an_algorithm("deriveBits"_string, "PBKDF2"_string, "Pbkdf2Params"_string);
  247. // FIXME: define_an_algorithm("get key length"_string, "PBKDF2"_string, ""_string);
  248. return internal_object;
  249. }
  250. // https://w3c.github.io/webcrypto/#concept-define-an-algorithm
  251. void SubtleCrypto::define_an_algorithm(String op, String algorithm, String type)
  252. {
  253. auto& internal_object = supported_algorithms_internal();
  254. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  255. // NOTE: There should always be a container at the op key.
  256. auto maybe_registered_algorithms = internal_object.get(op);
  257. auto registered_algorithms = maybe_registered_algorithms.value();
  258. // 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.
  259. registered_algorithms.set(algorithm, type);
  260. internal_object.set(op, registered_algorithms);
  261. }
  262. // https://w3c.github.io/webcrypto/#pbkdf2-operations
  263. 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)
  264. {
  265. auto& realm = this->realm();
  266. // 1. If format is not "raw", throw a NotSupportedError
  267. if (format != Bindings::KeyFormat::Raw) {
  268. return WebIDL::NotSupportedError::create(realm, "Only raw format is supported"_fly_string);
  269. }
  270. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  271. for (auto& usage : key_usages) {
  272. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  273. return WebIDL::SyntaxError::create(realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  274. }
  275. }
  276. // 3. If extractable is not false, then throw a SyntaxError.
  277. if (extractable)
  278. return WebIDL::SyntaxError::create(realm, "extractable must be false"_fly_string);
  279. // 4. Let key be a new CryptoKey representing keyData.
  280. auto key = CryptoKey::create(realm);
  281. // 5. Set the [[type]] internal slot of key to "secret".
  282. key->set_type(Bindings::KeyType::Secret);
  283. // 6. Set the [[extractable]] internal slot of key to false.
  284. key->set_extractable(false);
  285. // 7. Let algorithm be a new KeyAlgorithm object.
  286. auto algorithm = Bindings::KeyAlgorithm::create(realm);
  287. // 8. Set the name attribute of algorithm to "PBKDF2".
  288. algorithm->set_name("PBKDF2"_string);
  289. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  290. key->set_algorithm(algorithm);
  291. // 10. Return key.
  292. return key;
  293. }
  294. }