SubtleCrypto.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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/Intrinsics.h>
  11. #include <LibWeb/Crypto/SubtleCrypto.h>
  12. #include <LibWeb/WebIDL/AbstractOperations.h>
  13. #include <LibWeb/WebIDL/Buffers.h>
  14. #include <LibWeb/WebIDL/ExceptionOr.h>
  15. namespace Web::Crypto {
  16. JS_DEFINE_ALLOCATOR(SubtleCrypto);
  17. JS::NonnullGCPtr<SubtleCrypto> SubtleCrypto::create(JS::Realm& realm)
  18. {
  19. return realm.heap().allocate<SubtleCrypto>(realm, realm);
  20. }
  21. SubtleCrypto::SubtleCrypto(JS::Realm& realm)
  22. : PlatformObject(realm)
  23. {
  24. }
  25. SubtleCrypto::~SubtleCrypto() = default;
  26. void SubtleCrypto::initialize(JS::Realm& realm)
  27. {
  28. Base::initialize(realm);
  29. set_prototype(&Bindings::ensure_web_prototype<Bindings::SubtleCryptoPrototype>(realm, "SubtleCrypto"_fly_string));
  30. }
  31. // https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm
  32. JS::ThrowCompletionOr<Bindings::Algorithm> SubtleCrypto::normalize_an_algorithm(Variant<JS::Handle<JS::Object>, String> const& algorithm, String operation)
  33. {
  34. auto& realm = this->realm();
  35. // If alg is an instance of a DOMString:
  36. if (algorithm.has<String>()) {
  37. // Return the result of running the normalize an algorithm algorithm,
  38. // with the alg set to a new Algorithm dictionary whose name attribute is alg, and with the op set to op.
  39. auto dictionary = JS::make_handle(JS::Object::create(realm, realm.intrinsics().object_prototype()));
  40. TRY(dictionary->create_data_property("name", JS::PrimitiveString::create(realm.vm(), algorithm.get<String>())));
  41. TRY(dictionary->create_data_property("op", JS::PrimitiveString::create(realm.vm(), operation)));
  42. return normalize_an_algorithm(dictionary, operation);
  43. }
  44. // If alg is an object:
  45. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  46. // NOTE: There should always be a container at the op key.
  47. auto internal_object = supported_algorithms();
  48. auto maybe_registered_algorithms = internal_object.get(operation);
  49. auto registered_algorithms = maybe_registered_algorithms.value();
  50. // 2. Let initialAlg be the result of converting the ECMAScript object represented by alg to
  51. // the IDL dictionary type Algorithm, as defined by [WebIDL].
  52. // FIXME: How do we turn this into an "Algorithm" in a nice way?
  53. // NOTE: For now, we just use the object as-is.
  54. auto initial_algorithm = algorithm.get<JS::Handle<JS::Object>>();
  55. // 3. If an error occurred, return the error and terminate this algorithm.
  56. auto has_name = TRY(initial_algorithm->has_property("name"));
  57. if (!has_name) {
  58. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Algorithm");
  59. }
  60. // 4. Let algName be the value of the name attribute of initialAlg.
  61. auto algorithm_name = TRY(TRY(initial_algorithm->get("name")).to_string(realm.vm()));
  62. String desired_type;
  63. // 5. If registeredAlgorithms contains a key that is a case-insensitive string match for algName:
  64. if (registered_algorithms.contains(algorithm_name)) {
  65. // 1. Set algName to the value of the matching key.
  66. auto it = registered_algorithms.find(algorithm_name);
  67. algorithm_name = (*it).key;
  68. // 2. Let desiredType be the IDL dictionary type stored at algName in registeredAlgorithms.
  69. desired_type = (*it).value;
  70. } else {
  71. // Otherwise:
  72. // Return a new NotSupportedError and terminate this algorithm.
  73. // FIXME: This should be a DOMException
  74. return realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotImplemented, algorithm_name);
  75. }
  76. // 8. Let normalizedAlgorithm be the result of converting the ECMAScript object represented by alg
  77. // to the IDL dictionary type desiredType, as defined by [WebIDL].
  78. // FIXME: Should IDL generate a struct for each of these?
  79. Bindings::Algorithm normalized_algorithm;
  80. // 9. Set the name attribute of normalizedAlgorithm to algName.
  81. normalized_algorithm.name = algorithm_name;
  82. // 10. If an error occurred, return the error and terminate this algorithm.
  83. // FIXME: 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. // FIXME: 12. For each dictionary dictionary in dictionaries:
  86. // 13. Return normalizedAlgorithm.
  87. return normalized_algorithm;
  88. }
  89. // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-digest
  90. JS::NonnullGCPtr<JS::Promise> SubtleCrypto::digest(Variant<JS::Handle<JS::Object>, String> const& algorithm, JS::Handle<WebIDL::BufferSource> const& data)
  91. {
  92. auto& realm = this->realm();
  93. // 1. Let algorithm be the algorithm parameter passed to the digest() method.
  94. // 2. Let data be the result of getting a copy of the bytes held by the data parameter passed to the digest() method.
  95. auto data_buffer_or_error = WebIDL::get_buffer_source_copy(*data->raw_object());
  96. if (data_buffer_or_error.is_error()) {
  97. auto error = WebIDL::OperationError::create(realm, "Failed to copy bytes from ArrayBuffer"_fly_string);
  98. auto promise = JS::Promise::create(realm);
  99. promise->reject(error.ptr());
  100. return promise;
  101. }
  102. auto& data_buffer = data_buffer_or_error.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. if (normalized_algorithm.is_error()) {
  107. auto promise = JS::Promise::create(realm);
  108. auto error = normalized_algorithm.release_error();
  109. auto error_value = error.value().value();
  110. promise->reject(error_value);
  111. return promise;
  112. }
  113. // 5. Let promise be a new Promise.
  114. auto promise = JS::Promise::create(realm);
  115. // 6. Return promise and perform the remaining steps in parallel.
  116. // FIXME: We don't have a good abstraction for this yet, so we do it in sync.
  117. // 7. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.
  118. // 8. Let result be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.
  119. auto algorithm_object = normalized_algorithm.release_value();
  120. auto algorithm_name = algorithm_object.name;
  121. ::Crypto::Hash::HashKind hash_kind;
  122. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  123. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  124. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  125. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  126. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  127. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  128. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  129. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  130. } else {
  131. auto error = WebIDL::NotSupportedError::create(realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  132. promise->reject(error.ptr());
  133. return promise;
  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. auto error = WebIDL::OperationError::create(realm, "Failed to create result buffer"_fly_string);
  141. promise->reject(error.ptr());
  142. return promise;
  143. }
  144. auto result = JS::ArrayBuffer::create(realm, result_buffer.release_value());
  145. // 9. Resolve promise with result.
  146. promise->fulfill(result);
  147. return promise;
  148. }
  149. SubtleCrypto::SupportedAlgorithmsMap& SubtleCrypto::supported_algorithms_internal()
  150. {
  151. static SubtleCrypto::SupportedAlgorithmsMap s_supported_algorithms;
  152. return s_supported_algorithms;
  153. }
  154. // https://w3c.github.io/webcrypto/#algorithm-normalization-internal
  155. SubtleCrypto::SupportedAlgorithmsMap SubtleCrypto::supported_algorithms()
  156. {
  157. auto& internal_object = supported_algorithms_internal();
  158. if (!internal_object.is_empty()) {
  159. return internal_object;
  160. }
  161. // 1. For each value, v in the List of supported operations,
  162. // set the v key of the internal object supportedAlgorithms to a new associative container.
  163. auto supported_operations = Vector {
  164. "encrypt"_string,
  165. "decrypt"_string,
  166. "sign"_string,
  167. "verify"_string,
  168. "digest"_string,
  169. "deriveBits"_string,
  170. "wrapKey"_string,
  171. "unwrapKey"_string,
  172. "generateKey"_string,
  173. "importKey"_string,
  174. "exportKey"_string,
  175. "get key length"_string,
  176. };
  177. for (auto& operation : supported_operations) {
  178. internal_object.set(operation, {});
  179. }
  180. // https://w3c.github.io/webcrypto/#algorithm-conventions
  181. // https://w3c.github.io/webcrypto/#sha
  182. define_an_algorithm("digest"_string, "SHA1"_string, ""_string);
  183. define_an_algorithm("digest"_string, "SHA-256"_string, ""_string);
  184. define_an_algorithm("digest"_string, "SHA-384"_string, ""_string);
  185. define_an_algorithm("digest"_string, "SHA-512"_string, ""_string);
  186. return internal_object;
  187. }
  188. // https://w3c.github.io/webcrypto/#concept-define-an-algorithm
  189. void SubtleCrypto::define_an_algorithm(String op, String algorithm, String type)
  190. {
  191. auto& internal_object = supported_algorithms_internal();
  192. // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
  193. // NOTE: There should always be a container at the op key.
  194. auto maybe_registered_algorithms = internal_object.get(op);
  195. auto registered_algorithms = maybe_registered_algorithms.value();
  196. // 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.
  197. registered_algorithms.set(algorithm, type);
  198. internal_object.set(op, registered_algorithms);
  199. }
  200. }