RSA.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Random.h>
  27. #include <LibCrypto/ASN1/ASN1.h>
  28. #include <LibCrypto/ASN1/DER.h>
  29. #include <LibCrypto/ASN1/PEM.h>
  30. #include <LibCrypto/PK/RSA.h>
  31. namespace Crypto {
  32. namespace PK {
  33. RSA::KeyPairType RSA::parse_rsa_key(ReadonlyBytes in)
  34. {
  35. // we are going to assign to at least one of these
  36. KeyPairType keypair;
  37. // TODO: move ASN parsing logic out
  38. u64 t, x, y, z, tmp_oid[16];
  39. u8 tmp_buf[4096] { 0 };
  40. UnsignedBigInteger n, e, d;
  41. ASN1::List pubkey_hash_oid[2], pubkey[2];
  42. ASN1::set(pubkey_hash_oid[0], ASN1::Kind::ObjectIdentifier, tmp_oid, sizeof(tmp_oid) / sizeof(tmp_oid[0]));
  43. ASN1::set(pubkey_hash_oid[1], ASN1::Kind::Null, nullptr, 0);
  44. // DER is weird in that it stores pubkeys as bitstrings
  45. // we must first extract that crap
  46. ASN1::set(pubkey[0], ASN1::Kind::Sequence, &pubkey_hash_oid, 2);
  47. ASN1::set(pubkey[1], ASN1::Kind::Null, nullptr, 0);
  48. dbg() << "we were offered " << in.size() << " bytes of input";
  49. if (der_decode_sequence(in.data(), in.size(), pubkey, 2)) {
  50. // yay, now we have to reassemble the bitstring to a bytestring
  51. t = 0;
  52. y = 0;
  53. z = 0;
  54. x = 0;
  55. for (; x < pubkey[1].size; ++x) {
  56. y = (y << 1) | tmp_buf[x];
  57. if (++z == 8) {
  58. tmp_buf[t++] = (u8)y;
  59. y = 0;
  60. z = 0;
  61. }
  62. }
  63. // now the buffer is correct (Sequence { Integer, Integer })
  64. if (!der_decode_sequence_many<2>(tmp_buf, t,
  65. ASN1::Kind::Integer, 1, &n,
  66. ASN1::Kind::Integer, 1, &e)) {
  67. // something was fucked up
  68. dbg() << "bad pubkey: " << e << " in " << n;
  69. return keypair;
  70. }
  71. // correct public key
  72. keypair.public_key.set(n, e);
  73. return keypair;
  74. }
  75. // could be a private key
  76. if (!der_decode_sequence_many<1>(in.data(), in.size(),
  77. ASN1::Kind::Integer, 1, &n)) {
  78. // that's no key
  79. // that's a death star
  80. dbg() << "that's a death star";
  81. return keypair;
  82. }
  83. if (n == 0) {
  84. // it is a private key
  85. UnsignedBigInteger zero;
  86. if (!der_decode_sequence_many<4>(in.data(), in.size(),
  87. ASN1::Kind::Integer, 1, &zero,
  88. ASN1::Kind::Integer, 1, &n,
  89. ASN1::Kind::Integer, 1, &e,
  90. ASN1::Kind::Integer, 1, &d)) {
  91. dbg() << "bad privkey " << n << " " << e << " " << d;
  92. return keypair;
  93. }
  94. keypair.private_key.set(n, d, e);
  95. return keypair;
  96. }
  97. if (n == 1) {
  98. // multiprime key, we don't know how to deal with this
  99. dbg() << "Unsupported key type";
  100. return keypair;
  101. }
  102. // it's a broken public key
  103. keypair.public_key.set(n, 65537);
  104. return keypair;
  105. }
  106. void RSA::encrypt(ReadonlyBytes in, Bytes& out)
  107. {
  108. #ifdef CRYPTO_DEBUG
  109. dbg() << "in size: " << in.size();
  110. #endif
  111. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  112. if (!(in_integer < m_public_key.modulus())) {
  113. dbg() << "value too large for key";
  114. out = {};
  115. return;
  116. }
  117. auto exp = NumberTheory::ModularPower(in_integer, m_public_key.public_exponent(), m_public_key.modulus());
  118. auto size = exp.export_data(out);
  119. auto outsize = out.size();
  120. if (size != outsize) {
  121. dbg() << "POSSIBLE RSA BUG!!! Size mismatch: " << outsize << " requested but " << size << " bytes generated";
  122. out = out.slice(outsize - size, size);
  123. }
  124. }
  125. void RSA::decrypt(ReadonlyBytes in, Bytes& out)
  126. {
  127. // FIXME: Actually use the private key properly
  128. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  129. auto exp = NumberTheory::ModularPower(in_integer, m_private_key.private_exponent(), m_private_key.modulus());
  130. auto size = exp.export_data(out);
  131. auto align = m_private_key.length();
  132. auto aligned_size = (size + align - 1) / align * align;
  133. for (auto i = size; i < aligned_size; ++i)
  134. out[out.size() - i - 1] = 0; // zero the non-aligned values
  135. out = out.slice(out.size() - aligned_size, aligned_size);
  136. }
  137. void RSA::sign(ReadonlyBytes in, Bytes& out)
  138. {
  139. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  140. auto exp = NumberTheory::ModularPower(in_integer, m_private_key.private_exponent(), m_private_key.modulus());
  141. auto size = exp.export_data(out);
  142. out = out.slice(out.size() - size, size);
  143. }
  144. void RSA::verify(ReadonlyBytes in, Bytes& out)
  145. {
  146. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  147. auto exp = NumberTheory::ModularPower(in_integer, m_public_key.public_exponent(), m_public_key.modulus());
  148. auto size = exp.export_data(out);
  149. out = out.slice(out.size() - size, size);
  150. }
  151. void RSA::import_private_key(ReadonlyBytes bytes, bool pem)
  152. {
  153. ByteBuffer buffer;
  154. if (pem) {
  155. buffer = decode_pem(bytes);
  156. bytes = buffer;
  157. }
  158. auto key = parse_rsa_key(bytes);
  159. if (!key.private_key.length()) {
  160. dbg() << "We expected to see a private key, but we found none";
  161. ASSERT_NOT_REACHED();
  162. }
  163. m_private_key = key.private_key;
  164. }
  165. void RSA::import_public_key(ReadonlyBytes bytes, bool pem)
  166. {
  167. ByteBuffer buffer;
  168. if (pem) {
  169. buffer = decode_pem(bytes);
  170. bytes = buffer;
  171. }
  172. auto key = parse_rsa_key(bytes);
  173. if (!key.public_key.length()) {
  174. dbg() << "We expected to see a public key, but we found none";
  175. ASSERT_NOT_REACHED();
  176. }
  177. m_public_key = key.public_key;
  178. }
  179. template<typename HashFunction>
  180. void RSA_EMSA_PSS<HashFunction>::sign(ReadonlyBytes in, Bytes& out)
  181. {
  182. // -- encode via EMSA_PSS
  183. auto mod_bits = m_rsa.private_key().modulus().trimmed_length() * sizeof(u32) * 8;
  184. u8 EM[mod_bits];
  185. auto EM_buf = Bytes { EM, mod_bits };
  186. m_emsa_pss.encode(in, EM_buf, mod_bits - 1);
  187. // -- sign via RSA
  188. m_rsa.sign(EM_buf, out);
  189. }
  190. template<typename HashFunction>
  191. VerificationConsistency RSA_EMSA_PSS<HashFunction>::verify(ReadonlyBytes in)
  192. {
  193. auto mod_bytes = m_rsa.public_key().modulus().trimmed_length() * sizeof(u32);
  194. if (in.size() != mod_bytes)
  195. return VerificationConsistency::Inconsistent;
  196. u8 EM[mod_bytes];
  197. auto EM_buf = Bytes { EM, mod_bytes };
  198. // -- verify via RSA
  199. m_rsa.verify(in, EM_buf);
  200. // -- verify via EMSA_PSS
  201. return m_emsa_pss.verify(in, EM, mod_bytes * 8 - 1);
  202. }
  203. void RSA_PKCS1_EME::encrypt(ReadonlyBytes in, Bytes& out)
  204. {
  205. auto mod_len = (m_public_key.modulus().trimmed_length() * sizeof(u32) * 8 + 7) / 8;
  206. #ifdef CRYPTO_DEBUG
  207. dbg() << "key size: " << mod_len;
  208. #endif
  209. if (in.size() > mod_len - 11) {
  210. dbg() << "message too long :(";
  211. out = out.trim(0);
  212. return;
  213. }
  214. if (out.size() < mod_len) {
  215. dbg() << "output buffer too small";
  216. return;
  217. }
  218. auto ps_length = mod_len - in.size() - 3;
  219. u8 ps[ps_length];
  220. // FIXME: Without this assertion, GCC refuses to compile due to a memcpy overflow(!?)
  221. ASSERT(ps_length < 16384);
  222. AK::fill_with_random(ps, ps_length);
  223. // since arc4random can create zeros (shocking!)
  224. // we have to go through and un-zero the zeros
  225. for (size_t i = 0; i < ps_length; ++i)
  226. while (!ps[i])
  227. AK::fill_with_random(ps + i, 1);
  228. u8 paddings[] { 0x00, 0x02 };
  229. out.overwrite(0, paddings, 2);
  230. out.overwrite(2, ps, ps_length);
  231. out.overwrite(2 + ps_length, paddings, 1);
  232. out.overwrite(3 + ps_length, in.data(), in.size());
  233. out = out.trim(3 + ps_length + in.size()); // should be a single block
  234. #ifdef CRYPTO_DEBUG
  235. dbg() << "padded output size: " << 3 + ps_length + in.size() << " buffer size: " << out.size();
  236. #endif
  237. RSA::encrypt(out, out);
  238. }
  239. void RSA_PKCS1_EME::decrypt(ReadonlyBytes in, Bytes& out)
  240. {
  241. auto mod_len = (m_public_key.modulus().trimmed_length() * sizeof(u32) * 8 + 7) / 8;
  242. if (in.size() != mod_len) {
  243. dbg() << "decryption error: wrong amount of data: " << in.size();
  244. out = out.trim(0);
  245. return;
  246. }
  247. RSA::decrypt(in, out);
  248. if (out.size() < RSA::output_size()) {
  249. dbg() << "decryption error: not enough data after decryption: " << out.size();
  250. out = out.trim(0);
  251. return;
  252. }
  253. if (out[0] != 0x00) {
  254. dbg() << "invalid padding byte 0 : " << out[0];
  255. return;
  256. }
  257. if (out[1] != 0x02) {
  258. dbg() << "invalid padding byte 1" << out[1];
  259. return;
  260. }
  261. size_t offset = 2;
  262. while (offset < out.size() && out[offset])
  263. ++offset;
  264. if (offset == out.size()) {
  265. dbg() << "garbage data, no zero to split padding";
  266. return;
  267. }
  268. ++offset;
  269. if (offset - 3 < 8) {
  270. dbg() << "PS too small";
  271. return;
  272. }
  273. out = out.slice(offset, out.size() - offset);
  274. }
  275. void RSA_PKCS1_EME::sign(ReadonlyBytes, Bytes&)
  276. {
  277. dbg() << "FIXME: RSA_PKCS_EME::sign";
  278. }
  279. void RSA_PKCS1_EME::verify(ReadonlyBytes, Bytes&)
  280. {
  281. dbg() << "FIXME: RSA_PKCS_EME::verify";
  282. }
  283. }
  284. }