RSA.cpp 14 KB

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