RSA.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Random.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <LibCrypto/ASN1/ASN1.h>
  10. #include <LibCrypto/ASN1/DER.h>
  11. #include <LibCrypto/ASN1/PEM.h>
  12. #include <LibCrypto/PK/RSA.h>
  13. namespace Crypto::PK {
  14. static constexpr Array<int, 7> pkcs8_rsa_key_oid { 1, 2, 840, 113549, 1, 1, 1 };
  15. RSA::KeyPairType RSA::parse_rsa_key(ReadonlyBytes der)
  16. {
  17. // we are going to assign to at least one of these
  18. KeyPairType keypair;
  19. ASN1::Decoder decoder(der);
  20. // There are four possible (supported) formats:
  21. // PKCS#1 private key
  22. // PKCS#1 public key
  23. // PKCS#8 private key
  24. // PKCS#8 public key
  25. // They're all a single sequence, so let's check that first
  26. {
  27. auto result = decoder.peek();
  28. if (result.is_error()) {
  29. // Bad data.
  30. dbgln_if(RSA_PARSE_DEBUG, "RSA key parse failed: {}", result.error());
  31. return keypair;
  32. }
  33. auto tag = result.value();
  34. if (tag.kind != ASN1::Kind::Sequence) {
  35. dbgln_if(RSA_PARSE_DEBUG, "RSA key parse failed: Expected a Sequence but got {}", ASN1::kind_name(tag.kind));
  36. return keypair;
  37. }
  38. }
  39. // Then enter the sequence
  40. {
  41. auto error = decoder.enter();
  42. if (error.is_error()) {
  43. // Something was weird with the input.
  44. dbgln_if(RSA_PARSE_DEBUG, "RSA key parse failed: {}", error.error());
  45. return keypair;
  46. }
  47. }
  48. bool has_read_error = false;
  49. auto const check_if_pkcs8_rsa_key = [&] {
  50. // see if it's a sequence:
  51. auto tag_result = decoder.peek();
  52. if (tag_result.is_error()) {
  53. // Decode error :shrug:
  54. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#8 public key parse failed: {}", tag_result.error());
  55. return false;
  56. }
  57. auto tag = tag_result.value();
  58. if (tag.kind != ASN1::Kind::Sequence) {
  59. // We don't know what this is, but it sure isn't a PKCS#8 key.
  60. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#8 public key parse failed: Expected a Sequence but got {}", ASN1::kind_name(tag.kind));
  61. return false;
  62. }
  63. // It's a sequence, now let's see if it's actually an RSA key.
  64. auto error = decoder.enter();
  65. if (error.is_error()) {
  66. // Shenanigans!
  67. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#8 public key parse failed: {}", error.error());
  68. return false;
  69. }
  70. ScopeGuard leave { [&] {
  71. auto error = decoder.leave();
  72. if (error.is_error()) {
  73. dbgln_if(RSA_PARSE_DEBUG, "RSA key parse failed: {}", error.error());
  74. has_read_error = true;
  75. }
  76. } };
  77. // Now let's read the OID.
  78. auto oid_result = decoder.read<Vector<int>>();
  79. if (oid_result.is_error()) {
  80. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#8 public key parse failed: {}", oid_result.error());
  81. return false;
  82. }
  83. auto oid = oid_result.release_value();
  84. // Now let's check that the OID matches "RSA key"
  85. if (oid != pkcs8_rsa_key_oid) {
  86. // Oh well. not an RSA key at all.
  87. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#8 public key parse failed: Not an RSA key");
  88. return false;
  89. }
  90. return true;
  91. };
  92. auto integer_result = decoder.read<UnsignedBigInteger>();
  93. if (!integer_result.is_error()) {
  94. auto first_integer = integer_result.release_value();
  95. // It's either a PKCS#1 key, or a PKCS#8 private key.
  96. // Check for the PKCS#8 private key right away.
  97. if (check_if_pkcs8_rsa_key()) {
  98. if (has_read_error)
  99. return keypair;
  100. // Now read the private key, which is actually an octet string containing the PKCS#1 encoded private key.
  101. auto data_result = decoder.read<StringView>();
  102. if (data_result.is_error()) {
  103. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#8 private key parse failed: {}", data_result.error());
  104. return keypair;
  105. }
  106. return parse_rsa_key(data_result.value().bytes());
  107. }
  108. if (has_read_error)
  109. return keypair;
  110. // It's not a PKCS#8 key, so it's a PKCS#1 key (or something we don't support)
  111. // if the first integer is zero or one, it's a private key.
  112. if (first_integer == 0) {
  113. // This is a private key, parse the rest.
  114. auto modulus_result = decoder.read<UnsignedBigInteger>();
  115. auto public_exponent_result = decoder.read<UnsignedBigInteger>();
  116. auto private_exponent_result = decoder.read<UnsignedBigInteger>();
  117. auto prime1_result = decoder.read<UnsignedBigInteger>();
  118. auto prime2_result = decoder.read<UnsignedBigInteger>();
  119. auto exponent1_result = decoder.read<UnsignedBigInteger>();
  120. auto exponent2_result = decoder.read<UnsignedBigInteger>();
  121. auto coefficient_result = decoder.read<UnsignedBigInteger>();
  122. Array results = { &modulus_result, &public_exponent_result, &private_exponent_result, &prime1_result, &prime2_result, &exponent1_result, &exponent2_result, &coefficient_result };
  123. for (auto& result : results) {
  124. if (result->is_error()) {
  125. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#1 private key parse failed: {}", result->error());
  126. return keypair;
  127. }
  128. }
  129. keypair.private_key = {
  130. modulus_result.value(),
  131. private_exponent_result.release_value(),
  132. public_exponent_result.value(),
  133. prime1_result.release_value(),
  134. prime2_result.release_value(),
  135. exponent1_result.release_value(),
  136. exponent2_result.release_value(),
  137. coefficient_result.release_value(),
  138. };
  139. keypair.public_key = { modulus_result.release_value(), public_exponent_result.release_value() };
  140. return keypair;
  141. }
  142. if (first_integer == 1) {
  143. // This is a multi-prime key, we don't support that.
  144. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#1 private key parse failed: Multi-prime key not supported");
  145. return keypair;
  146. }
  147. auto&& modulus = move(first_integer);
  148. // Try reading a public key, `first_integer` is the modulus.
  149. auto public_exponent_result = decoder.read<UnsignedBigInteger>();
  150. if (public_exponent_result.is_error()) {
  151. // Bad public key.
  152. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#1 public key parse failed: {}", public_exponent_result.error());
  153. return keypair;
  154. }
  155. auto public_exponent = public_exponent_result.release_value();
  156. keypair.public_key.set(move(modulus), move(public_exponent));
  157. return keypair;
  158. }
  159. // It wasn't a PKCS#1 key, let's try our luck with PKCS#8.
  160. if (!check_if_pkcs8_rsa_key())
  161. return keypair;
  162. if (has_read_error)
  163. return keypair;
  164. // Now we have a bit string, which contains the PKCS#1 encoded public key.
  165. auto data_result = decoder.read<BitmapView>();
  166. if (data_result.is_error()) {
  167. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#8 public key parse failed: {}", data_result.error());
  168. return keypair;
  169. }
  170. // Now just read it as a PKCS#1 DER.
  171. auto data = data_result.release_value();
  172. // FIXME: This is pretty awkward, maybe just generate a zero'd out ByteBuffer from the parser instead?
  173. auto padded_data_result = ByteBuffer::create_zeroed(data.size_in_bytes());
  174. if (padded_data_result.is_error()) {
  175. dbgln_if(RSA_PARSE_DEBUG, "RSA PKCS#1 key parse failed: Not enough memory");
  176. return keypair;
  177. }
  178. auto padded_data = padded_data_result.release_value();
  179. padded_data.overwrite(0, data.data(), data.size_in_bytes());
  180. return parse_rsa_key(padded_data.bytes());
  181. }
  182. void RSA::encrypt(ReadonlyBytes in, Bytes& out)
  183. {
  184. dbgln_if(CRYPTO_DEBUG, "in size: {}", in.size());
  185. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  186. if (!(in_integer < m_public_key.modulus())) {
  187. dbgln("value too large for key");
  188. out = {};
  189. return;
  190. }
  191. auto exp = NumberTheory::ModularPower(in_integer, m_public_key.public_exponent(), m_public_key.modulus());
  192. auto size = exp.export_data(out);
  193. auto outsize = out.size();
  194. if (size != outsize) {
  195. dbgln("POSSIBLE RSA BUG!!! Size mismatch: {} requested but {} bytes generated", outsize, size);
  196. out = out.slice(outsize - size, size);
  197. }
  198. }
  199. void RSA::decrypt(ReadonlyBytes in, Bytes& out)
  200. {
  201. // FIXME: Actually use the private key properly
  202. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  203. auto exp = NumberTheory::ModularPower(in_integer, m_private_key.private_exponent(), m_private_key.modulus());
  204. auto size = exp.export_data(out);
  205. auto align = m_private_key.length();
  206. auto aligned_size = (size + align - 1) / align * align;
  207. for (auto i = size; i < aligned_size; ++i)
  208. out[out.size() - i - 1] = 0; // zero the non-aligned values
  209. out = out.slice(out.size() - aligned_size, aligned_size);
  210. }
  211. void RSA::sign(ReadonlyBytes in, Bytes& out)
  212. {
  213. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  214. auto exp = NumberTheory::ModularPower(in_integer, m_private_key.private_exponent(), m_private_key.modulus());
  215. auto size = exp.export_data(out);
  216. out = out.slice(out.size() - size, size);
  217. }
  218. void RSA::verify(ReadonlyBytes in, Bytes& out)
  219. {
  220. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  221. auto exp = NumberTheory::ModularPower(in_integer, m_public_key.public_exponent(), m_public_key.modulus());
  222. auto size = exp.export_data(out);
  223. out = out.slice(out.size() - size, size);
  224. }
  225. void RSA::import_private_key(ReadonlyBytes bytes, bool pem)
  226. {
  227. ByteBuffer buffer;
  228. if (pem) {
  229. buffer = decode_pem(bytes);
  230. bytes = buffer;
  231. }
  232. auto key = parse_rsa_key(bytes);
  233. if (!key.private_key.length()) {
  234. dbgln("We expected to see a private key, but we found none");
  235. VERIFY_NOT_REACHED();
  236. }
  237. m_private_key = key.private_key;
  238. }
  239. void RSA::import_public_key(ReadonlyBytes bytes, bool pem)
  240. {
  241. ByteBuffer buffer;
  242. if (pem) {
  243. buffer = decode_pem(bytes);
  244. bytes = buffer;
  245. }
  246. auto key = parse_rsa_key(bytes);
  247. if (!key.public_key.length()) {
  248. dbgln("We expected to see a public key, but we found none");
  249. VERIFY_NOT_REACHED();
  250. }
  251. m_public_key = key.public_key;
  252. }
  253. void RSA_PKCS1_EME::encrypt(ReadonlyBytes in, Bytes& out)
  254. {
  255. auto mod_len = (m_public_key.modulus().trimmed_length() * sizeof(u32) * 8 + 7) / 8;
  256. dbgln_if(CRYPTO_DEBUG, "key size: {}", mod_len);
  257. if (in.size() > mod_len - 11) {
  258. dbgln("message too long :(");
  259. out = out.trim(0);
  260. return;
  261. }
  262. if (out.size() < mod_len) {
  263. dbgln("output buffer too small");
  264. return;
  265. }
  266. auto ps_length = mod_len - in.size() - 3;
  267. Vector<u8, 8096> ps;
  268. ps.resize(ps_length);
  269. fill_with_random(ps);
  270. // since fill_with_random can create zeros (shocking!)
  271. // we have to go through and un-zero the zeros
  272. for (size_t i = 0; i < ps_length; ++i) {
  273. while (!ps[i])
  274. ps[i] = get_random<u8>();
  275. }
  276. u8 paddings[] { 0x00, 0x02 };
  277. out.overwrite(0, paddings, 2);
  278. out.overwrite(2, ps.data(), ps_length);
  279. out.overwrite(2 + ps_length, paddings, 1);
  280. out.overwrite(3 + ps_length, in.data(), in.size());
  281. out = out.trim(3 + ps_length + in.size()); // should be a single block
  282. dbgln_if(CRYPTO_DEBUG, "padded output size: {} buffer size: {}", 3 + ps_length + in.size(), out.size());
  283. RSA::encrypt(out, out);
  284. }
  285. void RSA_PKCS1_EME::decrypt(ReadonlyBytes in, Bytes& out)
  286. {
  287. auto mod_len = (m_public_key.modulus().trimmed_length() * sizeof(u32) * 8 + 7) / 8;
  288. if (in.size() != mod_len) {
  289. dbgln("decryption error: wrong amount of data: {}", in.size());
  290. out = out.trim(0);
  291. return;
  292. }
  293. RSA::decrypt(in, out);
  294. if (out.size() < RSA::output_size()) {
  295. dbgln("decryption error: not enough data after decryption: {}", out.size());
  296. out = out.trim(0);
  297. return;
  298. }
  299. if (out[0] != 0x00) {
  300. dbgln("invalid padding byte 0 : {}", out[0]);
  301. return;
  302. }
  303. if (out[1] != 0x02) {
  304. dbgln("invalid padding byte 1 : {}", out[1]);
  305. return;
  306. }
  307. size_t offset = 2;
  308. while (offset < out.size() && out[offset])
  309. ++offset;
  310. if (offset == out.size()) {
  311. dbgln("garbage data, no zero to split padding");
  312. return;
  313. }
  314. ++offset;
  315. if (offset - 3 < 8) {
  316. dbgln("PS too small");
  317. return;
  318. }
  319. out = out.slice(offset, out.size() - offset);
  320. }
  321. void RSA_PKCS1_EME::sign(ReadonlyBytes, Bytes&)
  322. {
  323. dbgln("FIXME: RSA_PKCS_EME::sign");
  324. }
  325. void RSA_PKCS1_EME::verify(ReadonlyBytes, Bytes&)
  326. {
  327. dbgln("FIXME: RSA_PKCS_EME::verify");
  328. }
  329. }