CryptoAlgorithms.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. /*
  2. * Copyright (c) 2024, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Base64.h>
  7. #include <AK/QuickSort.h>
  8. #include <LibCrypto/ASN1/DER.h>
  9. #include <LibCrypto/Curves/SECPxxxr1.h>
  10. #include <LibCrypto/Hash/HashManager.h>
  11. #include <LibCrypto/PK/RSA.h>
  12. #include <LibJS/Runtime/ArrayBuffer.h>
  13. #include <LibJS/Runtime/DataView.h>
  14. #include <LibJS/Runtime/TypedArray.h>
  15. #include <LibTLS/Certificate.h>
  16. #include <LibWeb/Crypto/CryptoAlgorithms.h>
  17. #include <LibWeb/Crypto/KeyAlgorithms.h>
  18. #include <LibWeb/Crypto/SubtleCrypto.h>
  19. #include <LibWeb/WebIDL/AbstractOperations.h>
  20. namespace Web::Crypto {
  21. // https://w3c.github.io/webcrypto/#concept-usage-intersection
  22. static Vector<Bindings::KeyUsage> usage_intersection(ReadonlySpan<Bindings::KeyUsage> a, ReadonlySpan<Bindings::KeyUsage> b)
  23. {
  24. Vector<Bindings::KeyUsage> result;
  25. for (auto const& usage : a) {
  26. if (b.contains_slow(usage))
  27. result.append(usage);
  28. }
  29. quick_sort(result);
  30. return result;
  31. }
  32. // Out of line to ensure this class has a key function
  33. AlgorithmMethods::~AlgorithmMethods() = default;
  34. // https://w3c.github.io/webcrypto/#big-integer
  35. static ::Crypto::UnsignedBigInteger big_integer_from_api_big_integer(JS::GCPtr<JS::Uint8Array> const& big_integer)
  36. {
  37. static_assert(AK::HostIsLittleEndian, "This method needs special treatment for BE");
  38. // The BigInteger typedef is a Uint8Array that holds an arbitrary magnitude unsigned integer
  39. // **in big-endian order**. Values read from the API SHALL have minimal typed array length
  40. // (that is, at most 7 leading zero bits, except the value 0 which shall have length 8 bits).
  41. // The API SHALL accept values with any number of leading zero bits, including the empty array, which represents zero.
  42. auto const& buffer = big_integer->viewed_array_buffer()->buffer();
  43. ::Crypto::UnsignedBigInteger result(0);
  44. if (buffer.size() > 0) {
  45. // We need to reverse the buffer to get it into little-endian order
  46. Vector<u8, 32> reversed_buffer;
  47. reversed_buffer.resize(buffer.size());
  48. for (size_t i = 0; i < buffer.size(); ++i) {
  49. reversed_buffer[buffer.size() - i - 1] = buffer[i];
  50. }
  51. result = ::Crypto::UnsignedBigInteger::import_data(reversed_buffer.data(), reversed_buffer.size());
  52. }
  53. return result;
  54. }
  55. // https://www.rfc-editor.org/rfc/rfc7518#section-2
  56. ErrorOr<String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integer)
  57. {
  58. static_assert(AK::HostIsLittleEndian, "This code assumes little-endian");
  59. // The representation of a positive or zero integer value as the
  60. // base64url encoding of the value's unsigned big-endian
  61. // representation as an octet sequence. The octet sequence MUST
  62. // utilize the minimum number of octets needed to represent the
  63. // value. Zero is represented as BASE64URL(single zero-valued
  64. // octet), which is "AA".
  65. auto bytes = TRY(ByteBuffer::create_uninitialized(integer.trimmed_byte_length()));
  66. bool const remove_leading_zeroes = true;
  67. auto data_size = integer.export_data(bytes.span(), remove_leading_zeroes);
  68. auto data_slice = bytes.bytes().slice(bytes.size() - data_size, data_size);
  69. // We need to encode the integer's big endian representation as a base64 string
  70. Vector<u8, 32> byte_swapped_data;
  71. byte_swapped_data.ensure_capacity(data_size);
  72. for (size_t i = 0; i < data_size; ++i)
  73. byte_swapped_data.append(data_slice[data_size - i - 1]);
  74. auto encoded = TRY(encode_base64url(byte_swapped_data));
  75. // FIXME: create a version of encode_base64url that omits padding bytes
  76. if (auto first_padding_byte = encoded.find_byte_offset('='); first_padding_byte.has_value())
  77. return encoded.substring_from_byte_offset(0, first_padding_byte.value());
  78. return encoded;
  79. }
  80. WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> base64_url_uint_decode(JS::Realm& realm, String const& base64_url_string)
  81. {
  82. auto& vm = realm.vm();
  83. static_assert(AK::HostIsLittleEndian, "This code assumes little-endian");
  84. // FIXME: Create a version of decode_base64url that ignores padding inconsistencies
  85. auto padded_string = base64_url_string;
  86. if (padded_string.byte_count() % 4 != 0) {
  87. padded_string = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", padded_string, TRY_OR_THROW_OOM(vm, String::repeated('=', 4 - (padded_string.byte_count() % 4)))));
  88. }
  89. auto base64_bytes_or_error = decode_base64url(padded_string);
  90. if (base64_bytes_or_error.is_error()) {
  91. if (base64_bytes_or_error.error().code() == ENOMEM)
  92. return vm.throw_completion<JS::InternalError>(vm.error_message(::JS::VM::ErrorMessage::OutOfMemory));
  93. return WebIDL::DataError::create(realm, MUST(String::formatted("base64 decode: {}", base64_bytes_or_error.release_error())));
  94. }
  95. auto base64_bytes = base64_bytes_or_error.release_value();
  96. // We need to swap the integer's big-endian representation to little endian in order to import it
  97. Vector<u8, 32> byte_swapped_data;
  98. byte_swapped_data.ensure_capacity(base64_bytes.size());
  99. for (size_t i = 0; i < base64_bytes.size(); ++i)
  100. byte_swapped_data.append(base64_bytes[base64_bytes.size() - i - 1]);
  101. return ::Crypto::UnsignedBigInteger::import_data(byte_swapped_data.data(), byte_swapped_data.size());
  102. }
  103. // https://w3c.github.io/webcrypto/#concept-parse-an-asn1-structure
  104. template<typename Structure>
  105. static WebIDL::ExceptionOr<Structure> parse_an_ASN1_structure(JS::Realm& realm, ReadonlyBytes data, bool exact_data = true)
  106. {
  107. // 1. Let data be a sequence of bytes to be parsed.
  108. // 2. Let structure be the ASN.1 structure to be parsed.
  109. // 3. Let exactData be an optional boolean value. If it is not supplied, let it be initialized to true.
  110. // 4. Parse data according to the Distinguished Encoding Rules of [X690], using structure as the ASN.1 structure to be decoded.
  111. ::Crypto::ASN1::Decoder decoder(data);
  112. Structure structure;
  113. if constexpr (IsSame<Structure, TLS::SubjectPublicKey>) {
  114. auto maybe_subject_public_key = TLS::parse_subject_public_key_info(decoder);
  115. if (maybe_subject_public_key.is_error())
  116. return WebIDL::DataError::create(realm, MUST(String::formatted("Error parsing subjectPublicKeyInfo: {}", maybe_subject_public_key.release_error())));
  117. structure = maybe_subject_public_key.release_value();
  118. } else if constexpr (IsSame<Structure, TLS::PrivateKey>) {
  119. auto maybe_private_key = TLS::parse_private_key_info(decoder);
  120. if (maybe_private_key.is_error())
  121. return WebIDL::DataError::create(realm, MUST(String::formatted("Error parsing privateKeyInfo: {}", maybe_private_key.release_error())));
  122. structure = maybe_private_key.release_value();
  123. } else {
  124. static_assert(DependentFalse<Structure>, "Don't know how to parse ASN.1 structure type");
  125. }
  126. // 5. If exactData was specified, and all of the bytes of data were not consumed during the parsing phase, then throw a DataError.
  127. if (exact_data && !decoder.eof())
  128. return WebIDL::DataError::create(realm, "Not all bytes were consumed during the parsing phase"_fly_string);
  129. // 6. Return the parsed ASN.1 structure.
  130. return structure;
  131. }
  132. // https://w3c.github.io/webcrypto/#concept-parse-a-spki
  133. static WebIDL::ExceptionOr<TLS::SubjectPublicKey> parse_a_subject_public_key_info(JS::Realm& realm, ReadonlyBytes bytes)
  134. {
  135. // When this specification says to parse a subjectPublicKeyInfo, the user agent must parse an ASN.1 structure,
  136. // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of subjectPublicKeyInfo,
  137. // as specified in [RFC5280], and exactData set to true.
  138. return parse_an_ASN1_structure<TLS::SubjectPublicKey>(realm, bytes, true);
  139. }
  140. // https://w3c.github.io/webcrypto/#concept-parse-a-privateKeyInfo
  141. static WebIDL::ExceptionOr<TLS::PrivateKey> parse_a_private_key_info(JS::Realm& realm, ReadonlyBytes bytes)
  142. {
  143. // When this specification says to parse a PrivateKeyInfo, the user agent must parse an ASN.1 structure
  144. // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of PrivateKeyInfo,
  145. // as specified in [RFC5208], and exactData set to true.
  146. return parse_an_ASN1_structure<TLS::PrivateKey>(realm, bytes, true);
  147. }
  148. static WebIDL::ExceptionOr<::Crypto::PK::RSAPrivateKey<>> parse_jwk_rsa_private_key(JS::Realm& realm, Bindings::JsonWebKey const& jwk)
  149. {
  150. auto n = TRY(base64_url_uint_decode(realm, *jwk.n));
  151. auto d = TRY(base64_url_uint_decode(realm, *jwk.d));
  152. auto e = TRY(base64_url_uint_decode(realm, *jwk.e));
  153. // We know that if any of the extra parameters are provided, all of them must be
  154. if (!jwk.p.has_value())
  155. return ::Crypto::PK::RSAPrivateKey<>(move(n), move(d), move(e), 0, 0);
  156. auto p = TRY(base64_url_uint_decode(realm, *jwk.p));
  157. auto q = TRY(base64_url_uint_decode(realm, *jwk.q));
  158. auto dp = TRY(base64_url_uint_decode(realm, *jwk.dp));
  159. auto dq = TRY(base64_url_uint_decode(realm, *jwk.dq));
  160. auto qi = TRY(base64_url_uint_decode(realm, *jwk.qi));
  161. return ::Crypto::PK::RSAPrivateKey<>(move(n), move(d), move(e), move(p), move(q), move(dp), move(dq), move(qi));
  162. }
  163. static WebIDL::ExceptionOr<::Crypto::PK::RSAPublicKey<>> parse_jwk_rsa_public_key(JS::Realm& realm, Bindings::JsonWebKey const& jwk)
  164. {
  165. auto e = TRY(base64_url_uint_decode(realm, *jwk.e));
  166. auto n = TRY(base64_url_uint_decode(realm, *jwk.n));
  167. return ::Crypto::PK::RSAPublicKey<>(move(n), move(e));
  168. }
  169. AlgorithmParams::~AlgorithmParams() = default;
  170. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AlgorithmParams::from_value(JS::VM& vm, JS::Value value)
  171. {
  172. auto& object = value.as_object();
  173. auto name = TRY(object.get("name"));
  174. auto name_string = TRY(name.to_string(vm));
  175. return adopt_own(*new AlgorithmParams { name_string });
  176. }
  177. PBKDF2Params::~PBKDF2Params() = default;
  178. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> PBKDF2Params::from_value(JS::VM& vm, JS::Value value)
  179. {
  180. auto& object = value.as_object();
  181. auto name_value = TRY(object.get("name"));
  182. auto name = TRY(name_value.to_string(vm));
  183. auto salt_value = TRY(object.get("salt"));
  184. if (!salt_value.is_object() || !(is<JS::TypedArrayBase>(salt_value.as_object()) || is<JS::ArrayBuffer>(salt_value.as_object()) || is<JS::DataView>(salt_value.as_object())))
  185. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  186. auto salt = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(salt_value.as_object()));
  187. auto iterations_value = TRY(object.get("iterations"));
  188. auto iterations = TRY(iterations_value.to_u32(vm));
  189. auto hash_value = TRY(object.get("hash"));
  190. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  191. if (hash_value.is_string()) {
  192. auto hash_string = TRY(hash_value.to_string(vm));
  193. hash = HashAlgorithmIdentifier { hash_string };
  194. } else {
  195. auto hash_object = TRY(hash_value.to_object(vm));
  196. hash = HashAlgorithmIdentifier { hash_object };
  197. }
  198. return adopt_own<AlgorithmParams>(*new PBKDF2Params { name, salt, iterations, hash.downcast<HashAlgorithmIdentifier>() });
  199. }
  200. RsaKeyGenParams::~RsaKeyGenParams() = default;
  201. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  202. {
  203. auto& object = value.as_object();
  204. auto name_value = TRY(object.get("name"));
  205. auto name = TRY(name_value.to_string(vm));
  206. auto modulus_length_value = TRY(object.get("modulusLength"));
  207. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  208. auto public_exponent_value = TRY(object.get("publicExponent"));
  209. JS::GCPtr<JS::Uint8Array> public_exponent;
  210. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  211. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  212. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  213. return adopt_own<AlgorithmParams>(*new RsaKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent) });
  214. }
  215. RsaHashedKeyGenParams::~RsaHashedKeyGenParams() = default;
  216. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  217. {
  218. auto& object = value.as_object();
  219. auto name_value = TRY(object.get("name"));
  220. auto name = TRY(name_value.to_string(vm));
  221. auto modulus_length_value = TRY(object.get("modulusLength"));
  222. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  223. auto public_exponent_value = TRY(object.get("publicExponent"));
  224. JS::GCPtr<JS::Uint8Array> public_exponent;
  225. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  226. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  227. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  228. auto hash_value = TRY(object.get("hash"));
  229. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  230. if (hash_value.is_string()) {
  231. auto hash_string = TRY(hash_value.to_string(vm));
  232. hash = HashAlgorithmIdentifier { hash_string };
  233. } else {
  234. auto hash_object = TRY(hash_value.to_object(vm));
  235. hash = HashAlgorithmIdentifier { hash_object };
  236. }
  237. return adopt_own<AlgorithmParams>(*new RsaHashedKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent), hash.get<HashAlgorithmIdentifier>() });
  238. }
  239. RsaHashedImportParams::~RsaHashedImportParams() = default;
  240. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedImportParams::from_value(JS::VM& vm, JS::Value value)
  241. {
  242. auto& object = value.as_object();
  243. auto name_value = TRY(object.get("name"));
  244. auto name = TRY(name_value.to_string(vm));
  245. auto hash_value = TRY(object.get("hash"));
  246. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  247. if (hash_value.is_string()) {
  248. auto hash_string = TRY(hash_value.to_string(vm));
  249. hash = HashAlgorithmIdentifier { hash_string };
  250. } else {
  251. auto hash_object = TRY(hash_value.to_object(vm));
  252. hash = HashAlgorithmIdentifier { hash_object };
  253. }
  254. return adopt_own<AlgorithmParams>(*new RsaHashedImportParams { name, hash.get<HashAlgorithmIdentifier>() });
  255. }
  256. RsaOaepParams::~RsaOaepParams() = default;
  257. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaOaepParams::from_value(JS::VM& vm, JS::Value value)
  258. {
  259. auto& object = value.as_object();
  260. auto name_value = TRY(object.get("name"));
  261. auto name = TRY(name_value.to_string(vm));
  262. auto label_value = TRY(object.get("label"));
  263. ByteBuffer label;
  264. if (!label_value.is_nullish()) {
  265. if (!label_value.is_object() || !(is<JS::TypedArrayBase>(label_value.as_object()) || is<JS::ArrayBuffer>(label_value.as_object()) || is<JS::DataView>(label_value.as_object())))
  266. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  267. label = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(label_value.as_object()));
  268. }
  269. return adopt_own<AlgorithmParams>(*new RsaOaepParams { name, move(label) });
  270. }
  271. EcdsaParams::~EcdsaParams() = default;
  272. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> EcdsaParams::from_value(JS::VM& vm, JS::Value value)
  273. {
  274. auto& object = value.as_object();
  275. auto name_value = TRY(object.get("name"));
  276. auto name = TRY(name_value.to_string(vm));
  277. auto hash_value = TRY(object.get("hash"));
  278. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  279. if (hash_value.is_string()) {
  280. auto hash_string = TRY(hash_value.to_string(vm));
  281. hash = HashAlgorithmIdentifier { hash_string };
  282. } else {
  283. auto hash_object = TRY(hash_value.to_object(vm));
  284. hash = HashAlgorithmIdentifier { hash_object };
  285. }
  286. return adopt_own<AlgorithmParams>(*new EcdsaParams { name, hash.get<HashAlgorithmIdentifier>() });
  287. }
  288. EcKeyGenParams::~EcKeyGenParams() = default;
  289. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> EcKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  290. {
  291. auto& object = value.as_object();
  292. auto name_value = TRY(object.get("name"));
  293. auto name = TRY(name_value.to_string(vm));
  294. auto curve_value = TRY(object.get("namedCurve"));
  295. auto curve = TRY(curve_value.to_string(vm));
  296. return adopt_own<AlgorithmParams>(*new EcKeyGenParams { name, curve });
  297. }
  298. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  299. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> RSAOAEP::encrypt(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& plaintext)
  300. {
  301. auto& realm = m_realm;
  302. auto& vm = realm.vm();
  303. auto const& normalized_algorithm = static_cast<RsaOaepParams const&>(params);
  304. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  305. if (key->type() != Bindings::KeyType::Public)
  306. return WebIDL::InvalidAccessError::create(realm, "Key is not a public key"_fly_string);
  307. // 2. Let label be the contents of the label member of normalizedAlgorithm or the empty octet string if the label member of normalizedAlgorithm is not present.
  308. [[maybe_unused]] auto const& label = normalized_algorithm.label;
  309. // 3. Perform the encryption operation defined in Section 7.1 of [RFC3447] with the key represented by key as the recipient's RSA public key,
  310. // the contents of plaintext as the message to be encrypted, M and label as the label, L, and with the hash function specified by the hash attribute
  311. // of the [[algorithm]] internal slot of key as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.
  312. // 4. If performing the operation results in an error, then throw an OperationError.
  313. // 5. Let ciphertext be the value C that results from performing the operation.
  314. // FIXME: Actually encrypt the data
  315. auto ciphertext = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(plaintext));
  316. // 6. Return the result of creating an ArrayBuffer containing ciphertext.
  317. return JS::ArrayBuffer::create(realm, move(ciphertext));
  318. }
  319. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  320. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> RSAOAEP::decrypt(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, AK::ByteBuffer const& ciphertext)
  321. {
  322. auto& realm = m_realm;
  323. auto& vm = realm.vm();
  324. auto const& normalized_algorithm = static_cast<RsaOaepParams const&>(params);
  325. // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
  326. if (key->type() != Bindings::KeyType::Private)
  327. return WebIDL::InvalidAccessError::create(realm, "Key is not a private key"_fly_string);
  328. // 2. Let label be the contents of the label member of normalizedAlgorithm or the empty octet string if the label member of normalizedAlgorithm is not present.
  329. [[maybe_unused]] auto const& label = normalized_algorithm.label;
  330. // 3. Perform the decryption operation defined in Section 7.1 of [RFC3447] with the key represented by key as the recipient's RSA private key,
  331. // the contents of ciphertext as the ciphertext to be decrypted, C, and label as the label, L, and with the hash function specified by the hash attribute
  332. // of the [[algorithm]] internal slot of key as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.
  333. // 4. If performing the operation results in an error, then throw an OperationError.
  334. // 5. Let plaintext the value M that results from performing the operation.
  335. // FIXME: Actually decrypt the data
  336. auto plaintext = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(ciphertext));
  337. // 6. Return the result of creating an ArrayBuffer containing plaintext.
  338. return JS::ArrayBuffer::create(realm, move(plaintext));
  339. }
  340. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  341. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> RSAOAEP::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  342. {
  343. // 1. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", then throw a SyntaxError.
  344. for (auto const& usage : key_usages) {
  345. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Wrapkey && usage != Bindings::KeyUsage::Unwrapkey) {
  346. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  347. }
  348. }
  349. // 2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm
  350. // and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.
  351. // 3. If performing the operation results in an error, then throw an OperationError.
  352. auto const& normalized_algorithm = static_cast<RsaHashedKeyGenParams const&>(params);
  353. auto key_pair = ::Crypto::PK::RSA::generate_key_pair(normalized_algorithm.modulus_length, normalized_algorithm.public_exponent);
  354. // 4. Let algorithm be a new RsaHashedKeyAlgorithm object.
  355. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  356. // 5. Set the name attribute of algorithm to "RSA-OAEP".
  357. algorithm->set_name("RSA-OAEP"_string);
  358. // 6. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.
  359. algorithm->set_modulus_length(normalized_algorithm.modulus_length);
  360. // 7. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.
  361. TRY(algorithm->set_public_exponent(normalized_algorithm.public_exponent));
  362. // 8. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.
  363. algorithm->set_hash(normalized_algorithm.hash);
  364. // 9. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  365. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.public_key });
  366. // 10. Set the [[type]] internal slot of publicKey to "public"
  367. public_key->set_type(Bindings::KeyType::Public);
  368. // 11. Set the [[algorithm]] internal slot of publicKey to algorithm.
  369. public_key->set_algorithm(algorithm);
  370. // 12. Set the [[extractable]] internal slot of publicKey to true.
  371. public_key->set_extractable(true);
  372. // 13. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].
  373. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Encrypt, Bindings::KeyUsage::Wrapkey } }));
  374. // 14. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  375. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.private_key });
  376. // 15. Set the [[type]] internal slot of privateKey to "private"
  377. private_key->set_type(Bindings::KeyType::Private);
  378. // 16. Set the [[algorithm]] internal slot of privateKey to algorithm.
  379. private_key->set_algorithm(algorithm);
  380. // 17. Set the [[extractable]] internal slot of privateKey to extractable.
  381. private_key->set_extractable(extractable);
  382. // 18. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].
  383. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Decrypt, Bindings::KeyUsage::Unwrapkey } }));
  384. // 19. Let result be a new CryptoKeyPair dictionary.
  385. // 20. Set the publicKey attribute of result to be publicKey.
  386. // 21. Set the privateKey attribute of result to be privateKey.
  387. // 22. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  388. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  389. }
  390. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  391. WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> RSAOAEP::import_key(Web::Crypto::AlgorithmParams const& params, Bindings::KeyFormat key_format, CryptoKey::InternalKeyData key_data, bool extractable, Vector<Bindings::KeyUsage> const& usages)
  392. {
  393. auto& realm = m_realm;
  394. // 1. Let keyData be the key data to be imported.
  395. JS::GCPtr<CryptoKey> key = nullptr;
  396. auto const& normalized_algorithm = static_cast<RsaHashedImportParams const&>(params);
  397. // 2. -> If format is "spki":
  398. if (key_format == Bindings::KeyFormat::Spki) {
  399. // 1. If usages contains an entry which is not "encrypt" or "wrapKey", then throw a SyntaxError.
  400. for (auto const& usage : usages) {
  401. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Wrapkey) {
  402. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  403. }
  404. }
  405. VERIFY(key_data.has<ByteBuffer>());
  406. // 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
  407. // 3. If an error occurred while parsing, then throw a DataError.
  408. auto spki = TRY(parse_a_subject_public_key_info(m_realm, key_data.get<ByteBuffer>()));
  409. // 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
  410. // is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
  411. if (spki.algorithm.identifier != TLS::rsa_encryption_oid)
  412. return WebIDL::DataError::create(m_realm, "Algorithm object identifier is not the rsaEncryption object identifier"_fly_string);
  413. // 5. Let publicKey be the result of performing the parse an ASN.1 structure algorithm,
  414. // with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure
  415. // specified in Section A.1.1 of [RFC3447], and exactData set to true.
  416. // NOTE: We already did this in parse_a_subject_public_key_info
  417. auto& public_key = spki.rsa;
  418. // 6. If an error occurred while parsing, or it can be determined that publicKey is not
  419. // a valid public key according to [RFC3447], then throw a DataError.
  420. // FIXME: Validate the public key
  421. // 7. Let key be a new CryptoKey that represents the RSA public key identified by publicKey.
  422. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key });
  423. // 8. Set the [[type]] internal slot of key to "public"
  424. key->set_type(Bindings::KeyType::Public);
  425. }
  426. // -> If format is "pkcs8":
  427. else if (key_format == Bindings::KeyFormat::Pkcs8) {
  428. // 1. If usages contains an entry which is not "decrypt" or "unwrapKey", then throw a SyntaxError.
  429. for (auto const& usage : usages) {
  430. if (usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Unwrapkey) {
  431. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  432. }
  433. }
  434. VERIFY(key_data.has<ByteBuffer>());
  435. // 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
  436. // 3. If an error occurred while parsing, then throw a DataError.
  437. auto private_key_info = TRY(parse_a_private_key_info(m_realm, key_data.get<ByteBuffer>()));
  438. // 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
  439. // is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
  440. if (private_key_info.algorithm.identifier != TLS::rsa_encryption_oid)
  441. return WebIDL::DataError::create(m_realm, "Algorithm object identifier is not the rsaEncryption object identifier"_fly_string);
  442. // 5. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure algorithm,
  443. // with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure
  444. // specified in Section A.1.2 of [RFC3447], and exactData set to true.
  445. // NOTE: We already did this in parse_a_private_key_info
  446. auto& rsa_private_key = private_key_info.rsa;
  447. // 6. If an error occurred while parsing, or if rsaPrivateKey is not
  448. // a valid RSA private key according to [RFC3447], then throw a DataError.
  449. // FIXME: Validate the private key
  450. // 7. Let key be a new CryptoKey that represents the RSA private key identified by rsaPrivateKey.
  451. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { rsa_private_key });
  452. // 8. Set the [[type]] internal slot of key to "private"
  453. key->set_type(Bindings::KeyType::Private);
  454. }
  455. // -> If format is "jwk":
  456. else if (key_format == Bindings::KeyFormat::Jwk) {
  457. // 1. -> If keyData is a JsonWebKey dictionary:
  458. // Let jwk equal keyData.
  459. // -> Otherwise:
  460. // Throw a DataError.
  461. if (!key_data.has<Bindings::JsonWebKey>())
  462. return WebIDL::DataError::create(m_realm, "keyData is not a JsonWebKey dictionary"_fly_string);
  463. auto& jwk = key_data.get<Bindings::JsonWebKey>();
  464. // 2. If the d field of jwk is present and usages contains an entry which is not "decrypt" or "unwrapKey", then throw a SyntaxError.
  465. if (jwk.d.has_value()) {
  466. for (auto const& usage : usages) {
  467. if (usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Unwrapkey) {
  468. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", Bindings::idl_enum_to_string(usage))));
  469. }
  470. }
  471. }
  472. // 3. If the d field of jwk is not present and usages contains an entry which is not "encrypt" or "wrapKey", then throw a SyntaxError.
  473. if (!jwk.d.has_value()) {
  474. for (auto const& usage : usages) {
  475. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Wrapkey) {
  476. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", Bindings::idl_enum_to_string(usage))));
  477. }
  478. }
  479. }
  480. // 4. If the kty field of jwk is not a case-sensitive string match to "RSA", then throw a DataError.
  481. if (jwk.kty != "RSA"_string)
  482. return WebIDL::DataError::create(m_realm, "Invalid key type"_fly_string);
  483. // 5. If usages is non-empty and the use field of jwk is present and is not a case-sensitive string match to "enc", then throw a DataError.
  484. if (!usages.is_empty() && jwk.use.has_value() && *jwk.use != "enc"_string)
  485. return WebIDL::DataError::create(m_realm, "Invalid use field"_fly_string);
  486. // 6. If the key_ops field of jwk is present, and is invalid according to the requirements of JSON Web Key [JWK]
  487. // or does not contain all of the specified usages values, then throw a DataError.
  488. for (auto const& usage : usages) {
  489. if (!jwk.key_ops->contains_slow(Bindings::idl_enum_to_string(usage)))
  490. return WebIDL::DataError::create(m_realm, MUST(String::formatted("Missing key_ops field: {}", Bindings::idl_enum_to_string(usage))));
  491. }
  492. // FIXME: Validate jwk.key_ops against requirements in https://www.rfc-editor.org/rfc/rfc7517#section-4.3
  493. // 7. If the ext field of jwk is present and has the value false and extractable is true, then throw a DataError.
  494. if (jwk.ext.has_value() && !*jwk.ext && extractable)
  495. return WebIDL::DataError::create(m_realm, "Invalid ext field"_fly_string);
  496. Optional<String> hash = {};
  497. // 8. -> If the alg field of jwk is not present:
  498. if (!jwk.alg.has_value()) {
  499. // Let hash be undefined.
  500. }
  501. // -> If the alg field of jwk is equal to "RSA-OAEP":
  502. if (jwk.alg == "RSA-OAEP"sv) {
  503. // Let hash be the string "SHA-1".
  504. hash = "SHA-1"_string;
  505. }
  506. // -> If the alg field of jwk is equal to "RSA-OAEP-256":
  507. else if (jwk.alg == "RSA-OAEP-256"sv) {
  508. // Let hash be the string "SHA-256".
  509. hash = "SHA-256"_string;
  510. }
  511. // -> If the alg field of jwk is equal to "RSA-OAEP-384":
  512. else if (jwk.alg == "RSA-OAEP-384"sv) {
  513. // Let hash be the string "SHA-384".
  514. hash = "SHA-384"_string;
  515. }
  516. // -> If the alg field of jwk is equal to "RSA-OAEP-512":
  517. else if (jwk.alg == "RSA-OAEP-512"sv) {
  518. // Let hash be the string "SHA-512".
  519. hash = "SHA-512"_string;
  520. }
  521. // -> Otherwise:
  522. else {
  523. // FIXME: Support 'other applicable specifications'
  524. // 1. Perform any key import steps defined by other applicable specifications, passing format, jwk and obtaining hash.
  525. // 2. If an error occurred or there are no applicable specifications, throw a DataError.
  526. return WebIDL::DataError::create(m_realm, "Invalid alg field"_fly_string);
  527. }
  528. // 9. If hash is not undefined:
  529. if (hash.has_value()) {
  530. // 1. Let normalizedHash be the result of normalize an algorithm with alg set to hash and op set to digest.
  531. auto normalized_hash = TRY(normalize_an_algorithm(m_realm, AlgorithmIdentifier { *hash }, "digest"_string));
  532. // 2. If normalizedHash is not equal to the hash member of normalizedAlgorithm, throw a DataError.
  533. if (normalized_hash.parameter->name != TRY(normalized_algorithm.hash.visit([](String const& name) -> JS::ThrowCompletionOr<String> { return name; }, [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
  534. auto name_property = TRY(obj->get("name"));
  535. return name_property.to_string(m_realm.vm()); })))
  536. return WebIDL::DataError::create(m_realm, "Invalid hash"_fly_string);
  537. }
  538. // 10. -> If the d field of jwk is present:
  539. if (jwk.d.has_value()) {
  540. // 1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms [JWA], then throw a DataError.
  541. bool meets_requirements = jwk.e.has_value() && jwk.n.has_value() && jwk.d.has_value();
  542. if (jwk.p.has_value() || jwk.q.has_value() || jwk.dp.has_value() || jwk.dq.has_value() || jwk.qi.has_value())
  543. meets_requirements |= jwk.p.has_value() && jwk.q.has_value() && jwk.dp.has_value() && jwk.dq.has_value() && jwk.qi.has_value();
  544. if (jwk.oth.has_value()) {
  545. // FIXME: We don't support > 2 primes in RSA keys
  546. meets_requirements = false;
  547. }
  548. if (!meets_requirements)
  549. return WebIDL::DataError::create(m_realm, "Invalid JWK private key"_fly_string);
  550. // FIXME: Spec error, it should say 'the RSA private key identified by interpreting jwk according to section 6.3.2'
  551. // 2. Let privateKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
  552. auto private_key = TRY(parse_jwk_rsa_private_key(realm, jwk));
  553. // FIXME: Spec error, it should say 'not to be a valid RSA private key'
  554. // 3. If privateKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.
  555. // FIXME: Validate the private key
  556. // 4. Let key be a new CryptoKey representing privateKey.
  557. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key });
  558. // 5. Set the [[type]] internal slot of key to "private"
  559. key->set_type(Bindings::KeyType::Private);
  560. }
  561. // -> Otherwise:
  562. else {
  563. // 1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms [JWA], then throw a DataError.
  564. if (!jwk.e.has_value() || !jwk.n.has_value())
  565. return WebIDL::DataError::create(m_realm, "Invalid JWK public key"_fly_string);
  566. // 2. Let publicKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
  567. auto public_key = TRY(parse_jwk_rsa_public_key(realm, jwk));
  568. // 3. If publicKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.
  569. // FIXME: Validate the public key
  570. // 4. Let key be a new CryptoKey representing publicKey.
  571. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key });
  572. // 5. Set the [[type]] internal slot of key to "public"
  573. key->set_type(Bindings::KeyType::Public);
  574. }
  575. }
  576. // -> Otherwise: throw a NotSupportedError.
  577. else {
  578. return WebIDL::NotSupportedError::create(m_realm, "Unsupported key format"_fly_string);
  579. }
  580. // 3. Let algorithm be a new RsaHashedKeyAlgorithm.
  581. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  582. // 4. Set the name attribute of algorithm to "RSA-OAEP"
  583. algorithm->set_name("RSA-OAEP"_string);
  584. // 5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.
  585. // 6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.
  586. TRY(key->handle().visit(
  587. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> WebIDL::ExceptionOr<void> {
  588. algorithm->set_modulus_length(public_key.length());
  589. TRY(algorithm->set_public_exponent(public_key.public_exponent()));
  590. return {};
  591. },
  592. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> WebIDL::ExceptionOr<void> {
  593. algorithm->set_modulus_length(private_key.length());
  594. TRY(algorithm->set_public_exponent(private_key.public_exponent()));
  595. return {};
  596. },
  597. [](auto) -> WebIDL::ExceptionOr<void> { VERIFY_NOT_REACHED(); }));
  598. // 7. Set the hash attribute of algorithm to the hash member of normalizedAlgorithm.
  599. algorithm->set_hash(normalized_algorithm.hash);
  600. // 8. Set the [[algorithm]] internal slot of key to algorithm
  601. key->set_algorithm(algorithm);
  602. // 9. Return key.
  603. return JS::NonnullGCPtr { *key };
  604. }
  605. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  606. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> RSAOAEP::export_key(Bindings::KeyFormat format, JS::NonnullGCPtr<CryptoKey> key)
  607. {
  608. auto& realm = m_realm;
  609. auto& vm = realm.vm();
  610. // 1. Let key be the key to be exported.
  611. // 2. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be accessed, then throw an OperationError.
  612. // Note: In our impl this is always accessible
  613. auto const& handle = key->handle();
  614. JS::GCPtr<JS::Object> result = nullptr;
  615. // 3. If format is "spki"
  616. if (format == Bindings::KeyFormat::Spki) {
  617. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  618. if (key->type() != Bindings::KeyType::Public)
  619. return WebIDL::InvalidAccessError::create(realm, "Key is not public"_fly_string);
  620. // FIXME: 2. Let data be an instance of the subjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:
  621. // - Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
  622. // - Set the algorithm field to the OID rsaEncryption defined in [RFC3447].
  623. // - Set the params field to the ASN.1 type NULL.
  624. // - Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in [RFC3447], Appendix A.1.1,
  625. // that represents the RSA public key represented by the [[handle]] internal slot of key
  626. // FIXME: 3. Let result be the result of creating an ArrayBuffer containing data.
  627. result = JS::ArrayBuffer::create(realm, TRY_OR_THROW_OOM(vm, ByteBuffer::copy(("FIXME"sv).bytes())));
  628. }
  629. // FIXME: If format is "pkcs8"
  630. // If format is "jwk"
  631. else if (format == Bindings::KeyFormat::Jwk) {
  632. // 1. Let jwk be a new JsonWebKey dictionary.
  633. Bindings::JsonWebKey jwk = {};
  634. // 2. Set the kty attribute of jwk to the string "RSA".
  635. jwk.kty = "RSA"_string;
  636. // 4. Let hash be the name attribute of the hash attribute of the [[algorithm]] internal slot of key.
  637. auto hash = TRY(verify_cast<RsaHashedKeyAlgorithm>(*key->algorithm()).hash().visit([](String const& name) -> JS::ThrowCompletionOr<String> { return name; }, [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
  638. auto name_property = TRY(obj->get("name"));
  639. return name_property.to_string(realm.vm()); }));
  640. // 4. If hash is "SHA-1":
  641. // - Set the alg attribute of jwk to the string "RSA-OAEP".
  642. if (hash == "SHA-1"sv) {
  643. jwk.alg = "RSA-OAEP"_string;
  644. }
  645. // If hash is "SHA-256":
  646. // - Set the alg attribute of jwk to the string "RSA-OAEP-256".
  647. else if (hash == "SHA-256"sv) {
  648. jwk.alg = "RSA-OAEP-256"_string;
  649. }
  650. // If hash is "SHA-384":
  651. // - Set the alg attribute of jwk to the string "RSA-OAEP-384".
  652. else if (hash == "SHA-384"sv) {
  653. jwk.alg = "RSA-OAEP-384"_string;
  654. }
  655. // If hash is "SHA-512":
  656. // - Set the alg attribute of jwk to the string "RSA-OAEP-512".
  657. else if (hash == "SHA-512"sv) {
  658. jwk.alg = "RSA-OAEP-512"_string;
  659. } else {
  660. // FIXME: Support 'other applicable specifications'
  661. // - Perform any key export steps defined by other applicable specifications,
  662. // passing format and the hash attribute of the [[algorithm]] internal slot of key and obtaining alg.
  663. // - Set the alg attribute of jwk to alg.
  664. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Unsupported hash algorithm '{}'", hash)));
  665. }
  666. // 10. Set the attributes n and e of jwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.
  667. auto maybe_error = handle.visit(
  668. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> ErrorOr<void> {
  669. jwk.n = TRY(base64_url_uint_encode(public_key.modulus()));
  670. jwk.e = TRY(base64_url_uint_encode(public_key.public_exponent()));
  671. return {};
  672. },
  673. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> ErrorOr<void> {
  674. jwk.n = TRY(base64_url_uint_encode(private_key.modulus()));
  675. jwk.e = TRY(base64_url_uint_encode(private_key.public_exponent()));
  676. // 11. If the [[type]] internal slot of key is "private":
  677. // 1. Set the attributes named d, p, q, dp, dq, and qi of jwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.2.
  678. jwk.d = TRY(base64_url_uint_encode(private_key.private_exponent()));
  679. jwk.p = TRY(base64_url_uint_encode(private_key.prime1()));
  680. jwk.q = TRY(base64_url_uint_encode(private_key.prime2()));
  681. jwk.dp = TRY(base64_url_uint_encode(private_key.exponent1()));
  682. jwk.dq = TRY(base64_url_uint_encode(private_key.exponent2()));
  683. jwk.qi = TRY(base64_url_uint_encode(private_key.coefficient()));
  684. // 12. If the underlying RSA private key represented by the [[handle]] internal slot of key is represented by more than two primes,
  685. // set the attribute named oth of jwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7
  686. // FIXME: We don't support more than 2 primes on RSA keys
  687. return {};
  688. },
  689. [](auto) -> ErrorOr<void> {
  690. VERIFY_NOT_REACHED();
  691. });
  692. // FIXME: clang-format butchers the visit if we do the TRY inline
  693. TRY_OR_THROW_OOM(vm, maybe_error);
  694. // 13. Set the key_ops attribute of jwk to the usages attribute of key.
  695. jwk.key_ops = Vector<String> {};
  696. jwk.key_ops->ensure_capacity(key->internal_usages().size());
  697. for (auto const& usage : key->internal_usages()) {
  698. jwk.key_ops->append(Bindings::idl_enum_to_string(usage));
  699. }
  700. // 14. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
  701. jwk.ext = key->extractable();
  702. // 15. Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL].
  703. result = TRY(jwk.to_object(realm));
  704. }
  705. // Otherwise throw a NotSupportedError.
  706. else {
  707. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Exporting to format {} is not supported", Bindings::idl_enum_to_string(format))));
  708. }
  709. // 8. Return result
  710. return JS::NonnullGCPtr { *result };
  711. }
  712. WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> PBKDF2::import_key(AlgorithmParams const&, Bindings::KeyFormat format, CryptoKey::InternalKeyData key_data, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  713. {
  714. // 1. If format is not "raw", throw a NotSupportedError
  715. if (format != Bindings::KeyFormat::Raw) {
  716. return WebIDL::NotSupportedError::create(m_realm, "Only raw format is supported"_fly_string);
  717. }
  718. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  719. for (auto& usage : key_usages) {
  720. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  721. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  722. }
  723. }
  724. // 3. If extractable is not false, then throw a SyntaxError.
  725. if (extractable)
  726. return WebIDL::SyntaxError::create(m_realm, "extractable must be false"_fly_string);
  727. // 4. Let key be a new CryptoKey representing keyData.
  728. auto key = CryptoKey::create(m_realm, move(key_data));
  729. // 5. Set the [[type]] internal slot of key to "secret".
  730. key->set_type(Bindings::KeyType::Secret);
  731. // 6. Set the [[extractable]] internal slot of key to false.
  732. key->set_extractable(false);
  733. // 7. Let algorithm be a new KeyAlgorithm object.
  734. auto algorithm = KeyAlgorithm::create(m_realm);
  735. // 8. Set the name attribute of algorithm to "PBKDF2".
  736. algorithm->set_name("PBKDF2"_string);
  737. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  738. key->set_algorithm(algorithm);
  739. // 10. Return key.
  740. return key;
  741. }
  742. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> SHA::digest(AlgorithmParams const& algorithm, ByteBuffer const& data)
  743. {
  744. auto& algorithm_name = algorithm.name;
  745. ::Crypto::Hash::HashKind hash_kind;
  746. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  747. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  748. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  749. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  750. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  751. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  752. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  753. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  754. } else {
  755. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  756. }
  757. ::Crypto::Hash::Manager hash { hash_kind };
  758. hash.update(data);
  759. auto digest = hash.digest();
  760. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  761. if (result_buffer.is_error())
  762. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  763. return JS::ArrayBuffer::create(m_realm, result_buffer.release_value());
  764. }
  765. // https://w3c.github.io/webcrypto/#ecdsa-operations
  766. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> ECDSA::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  767. {
  768. // 1. If usages contains a value which is not one of "sign" or "verify", then throw a SyntaxError.
  769. for (auto const& usage : key_usages) {
  770. if (usage != Bindings::KeyUsage::Sign && usage != Bindings::KeyUsage::Verify) {
  771. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  772. }
  773. }
  774. auto const& normalized_algorithm = static_cast<EcKeyGenParams const&>(params);
  775. // 2. If the namedCurve member of normalizedAlgorithm is "P-256", "P-384" or "P-521":
  776. // Generate an Elliptic Curve key pair, as defined in [RFC6090]
  777. // with domain parameters for the curve identified by the namedCurve member of normalizedAlgorithm.
  778. Variant<Empty, ::Crypto::Curves::SECP256r1, ::Crypto::Curves::SECP384r1> curve;
  779. if (normalized_algorithm.named_curve.is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {
  780. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-256"sv))
  781. curve = ::Crypto::Curves::SECP256r1 {};
  782. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-384"sv))
  783. curve = ::Crypto::Curves::SECP384r1 {};
  784. // FIXME: Support P-521
  785. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-521"sv))
  786. return WebIDL::NotSupportedError::create(m_realm, "'P-521' is not supported yet"_fly_string);
  787. } else {
  788. // If the namedCurve member of normalizedAlgorithm is a value specified in an applicable specification:
  789. // Perform the ECDSA generation steps specified in that specification,
  790. // passing in normalizedAlgorithm and resulting in an elliptic curve key pair.
  791. // Otherwise: throw a NotSupportedError
  792. return WebIDL::NotSupportedError::create(m_realm, "Only 'P-256', 'P-384' and 'P-521' is supported"_fly_string);
  793. }
  794. // NOTE: Spec jumps to 6 here for some reason
  795. // 6. If performing the key generation operation results in an error, then throw an OperationError.
  796. auto maybe_private_key_data = curve.visit(
  797. [](Empty const&) -> ErrorOr<ByteBuffer> { return Error::from_string_view("noop error"sv); },
  798. [](auto instance) { return instance.generate_private_key(); });
  799. if (maybe_private_key_data.is_error())
  800. return WebIDL::OperationError::create(m_realm, "Failed to create valid crypto instance"_fly_string);
  801. auto private_key_data = maybe_private_key_data.release_value();
  802. auto maybe_public_key_data = curve.visit(
  803. [](Empty const&) -> ErrorOr<ByteBuffer> { return Error::from_string_view("noop error"sv); },
  804. [&](auto instance) { return instance.generate_public_key(private_key_data); });
  805. if (maybe_public_key_data.is_error())
  806. return WebIDL::OperationError::create(m_realm, "Failed to create valid crypto instance"_fly_string);
  807. auto public_key_data = maybe_public_key_data.release_value();
  808. // 7. Let algorithm be a new EcKeyAlgorithm object.
  809. auto algorithm = EcKeyAlgorithm::create(m_realm);
  810. // 8. Set the name attribute of algorithm to "ECDSA".
  811. algorithm->set_name("ECDSA"_string);
  812. // 9. Set the namedCurve attribute of algorithm to equal the namedCurve member of normalizedAlgorithm.
  813. algorithm->set_named_curve(normalized_algorithm.named_curve);
  814. // 10. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  815. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key_data });
  816. // 11. Set the [[type]] internal slot of publicKey to "public"
  817. public_key->set_type(Bindings::KeyType::Public);
  818. // 12. Set the [[algorithm]] internal slot of publicKey to algorithm.
  819. public_key->set_algorithm(algorithm);
  820. // 13. Set the [[extractable]] internal slot of publicKey to true.
  821. public_key->set_extractable(true);
  822. // 14. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "verify" ].
  823. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Verify } }));
  824. // 15. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  825. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key_data });
  826. // 16. Set the [[type]] internal slot of privateKey to "private"
  827. private_key->set_type(Bindings::KeyType::Private);
  828. // 17. Set the [[algorithm]] internal slot of privateKey to algorithm.
  829. private_key->set_algorithm(algorithm);
  830. // 18. Set the [[extractable]] internal slot of privateKey to extractable.
  831. private_key->set_extractable(extractable);
  832. // 19. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "sign" ].
  833. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Sign } }));
  834. // 20. Let result be a new CryptoKeyPair dictionary.
  835. // 21. Set the publicKey attribute of result to be publicKey.
  836. // 22. Set the privateKey attribute of result to be privateKey.
  837. // 23. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  838. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  839. }
  840. // https://w3c.github.io/webcrypto/#ecdsa-operations
  841. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> ECDSA::sign(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& message)
  842. {
  843. auto& realm = m_realm;
  844. auto& vm = realm.vm();
  845. auto const& normalized_algorithm = static_cast<EcdsaParams const&>(params);
  846. (void)vm;
  847. (void)message;
  848. // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
  849. if (key->type() != Bindings::KeyType::Private)
  850. return WebIDL::InvalidAccessError::create(realm, "Key is not a private key"_fly_string);
  851. // 2. Let hashAlgorithm be the hash member of normalizedAlgorithm.
  852. [[maybe_unused]] auto const& hash_algorithm = normalized_algorithm.hash;
  853. // NOTE: We dont have sign() on the SECPxxxr1 curves, so we can't implement this yet
  854. // FIXME: 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message.
  855. // FIXME: 4. Let d be the ECDSA private key associated with key.
  856. // FIXME: 5. Let params be the EC domain parameters associated with key.
  857. // FIXME: 6. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":
  858. // FIXME: 1. Perform the ECDSA signing process, as specified in [RFC6090], Section 5.4, with M as the message, using params as the EC domain parameters, and with d as the private key.
  859. // FIXME: 2. Let r and s be the pair of integers resulting from performing the ECDSA signing process.
  860. // FIXME: 3. Let result be an empty byte sequence.
  861. // FIXME: 4. Let n be the smallest integer such that n * 8 is greater than the logarithm to base 2 of the order of the base point of the elliptic curve identified by params.
  862. // FIXME: 5. Convert r to an octet string of length n and append this sequence of bytes to result.
  863. // FIXME: 6. Convert s to an octet string of length n and append this sequence of bytes to result.
  864. // FIXME: Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification:
  865. // FIXME: Perform the ECDSA signature steps specified in that specification, passing in M, params and d and resulting in result.
  866. // NOTE: The spec jumps to 9 here for some reason
  867. // FIXME: 9. Return the result of creating an ArrayBuffer containing result.
  868. return WebIDL::NotSupportedError::create(realm, "ECDSA signing is not supported yet"_fly_string);
  869. }
  870. // https://w3c.github.io/webcrypto/#ecdsa-operations
  871. WebIDL::ExceptionOr<JS::Value> ECDSA::verify(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& signature, ByteBuffer const& message)
  872. {
  873. auto& realm = m_realm;
  874. auto const& normalized_algorithm = static_cast<EcdsaParams const&>(params);
  875. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  876. if (key->type() != Bindings::KeyType::Public)
  877. return WebIDL::InvalidAccessError::create(realm, "Key is not a public key"_fly_string);
  878. // 2. Let hashAlgorithm be the hash member of normalizedAlgorithm.
  879. [[maybe_unused]] auto const& hash_algorithm = TRY(normalized_algorithm.hash.visit(
  880. [](String const& name) -> JS::ThrowCompletionOr<String> { return name; },
  881. [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
  882. auto name_property = TRY(obj->get("name"));
  883. return name_property.to_string(m_realm.vm()); }));
  884. // 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message.
  885. ::Crypto::Hash::HashKind hash_kind;
  886. if (hash_algorithm.equals_ignoring_ascii_case("SHA-1"sv)) {
  887. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  888. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-256"sv)) {
  889. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  890. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-384"sv)) {
  891. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  892. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-512"sv)) {
  893. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  894. } else {
  895. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", hash_algorithm)));
  896. }
  897. ::Crypto::Hash::Manager hash { hash_kind };
  898. hash.update(message);
  899. auto digest = hash.digest();
  900. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  901. if (result_buffer.is_error())
  902. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  903. auto M = result_buffer.release_value();
  904. // 4. Let Q be the ECDSA public key associated with key.
  905. auto Q = key->handle().visit(
  906. [](ByteBuffer data) -> ByteBuffer {
  907. return data;
  908. },
  909. [](auto) -> ByteBuffer { VERIFY_NOT_REACHED(); });
  910. // FIXME: 5. Let params be the EC domain parameters associated with key.
  911. // 6. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":
  912. auto const& internal_algorithm = static_cast<EcKeyAlgorithm const&>(*key->algorithm());
  913. auto const& named_curve = internal_algorithm.named_curve();
  914. auto result = false;
  915. Variant<Empty, ::Crypto::Curves::SECP256r1, ::Crypto::Curves::SECP384r1> curve;
  916. if (named_curve.is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {
  917. if (named_curve.equals_ignoring_ascii_case("P-256"sv))
  918. curve = ::Crypto::Curves::SECP256r1 {};
  919. if (named_curve.equals_ignoring_ascii_case("P-384"sv))
  920. curve = ::Crypto::Curves::SECP384r1 {};
  921. // FIXME: Support P-521
  922. if (named_curve.equals_ignoring_ascii_case("P-521"sv))
  923. return WebIDL::NotSupportedError::create(m_realm, "'P-521' is not supported yet"_fly_string);
  924. // Perform the ECDSA verifying process, as specified in [RFC6090], Section 5.3,
  925. // with M as the received message,
  926. // signature as the received signature
  927. // and using params as the EC domain parameters,
  928. // and Q as the public key.
  929. // NOTE: verify() takes the signature in X.509 format but JS uses IEEE P1363 format, so we need to convert it
  930. // FIXME: Dont construct an ASN1 object here just to pass it to verify
  931. auto half_size = signature.size() / 2;
  932. auto r = ::Crypto::UnsignedBigInteger::import_data(signature.data(), half_size);
  933. auto s = ::Crypto::UnsignedBigInteger::import_data(signature.data() + half_size, half_size);
  934. ::Crypto::ASN1::Encoder encoder;
  935. (void)encoder.write_constructed(::Crypto::ASN1::Class::Universal, ::Crypto::ASN1::Kind::Sequence, [&] {
  936. (void)encoder.write(r);
  937. (void)encoder.write(s);
  938. });
  939. auto encoded_signature = encoder.finish();
  940. auto maybe_result = curve.visit(
  941. [](Empty const&) -> ErrorOr<bool> { return Error::from_string_view("Failed to create valid crypto instance"sv); },
  942. [&](auto instance) { return instance.verify(M, Q, encoded_signature); });
  943. if (maybe_result.is_error()) {
  944. auto error_message = MUST(FlyString::from_utf8(maybe_result.error().string_literal()));
  945. return WebIDL::OperationError::create(m_realm, error_message);
  946. }
  947. result = maybe_result.release_value();
  948. } else {
  949. // FIXME: Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification:
  950. // FIXME: Perform the ECDSA verification steps specified in that specification passing in M, signature, params and Q and resulting in an indication of whether or not the purported signature is valid.
  951. }
  952. // 9. Let result be a boolean with the value true if the signature is valid and the value false otherwise.
  953. // 10. Return result.
  954. return JS::Value(result);
  955. }
  956. }