SubtleCrypto.cpp 10 KB

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