RSA.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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(const ByteBuffer& in, ByteBuffer& 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.clear();
  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.span());
  119. // FIXME: We should probably not do this...
  120. if (size != out.size())
  121. out = out.slice(out.size() - size, size);
  122. }
  123. void RSA::decrypt(const ByteBuffer& in, ByteBuffer& out)
  124. {
  125. // FIXME: Actually use the private key properly
  126. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  127. auto exp = NumberTheory::ModularPower(in_integer, m_private_key.private_exponent(), m_private_key.modulus());
  128. auto size = exp.export_data(out.span());
  129. auto align = m_private_key.length();
  130. auto aligned_size = (size + align - 1) / align * align;
  131. for (auto i = size; i < aligned_size; ++i)
  132. out[out.size() - i - 1] = 0; // zero the non-aligned values
  133. out = out.slice(out.size() - aligned_size, aligned_size);
  134. }
  135. void RSA::sign(const ByteBuffer& in, ByteBuffer& out)
  136. {
  137. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  138. auto exp = NumberTheory::ModularPower(in_integer, m_private_key.private_exponent(), m_private_key.modulus());
  139. auto size = exp.export_data(out.span());
  140. out = out.slice(out.size() - size, size);
  141. }
  142. void RSA::verify(const ByteBuffer& in, ByteBuffer& out)
  143. {
  144. auto in_integer = UnsignedBigInteger::import_data(in.data(), in.size());
  145. auto exp = NumberTheory::ModularPower(in_integer, m_public_key.public_exponent(), m_public_key.modulus());
  146. auto size = exp.export_data(out.span());
  147. out = out.slice(out.size() - size, size);
  148. }
  149. void RSA::import_private_key(const ByteBuffer& buffer, bool pem)
  150. {
  151. // so gods help me, I hate DER
  152. auto decoded_buffer = pem ? decode_pem(buffer) : buffer;
  153. auto key = parse_rsa_key(decoded_buffer.span());
  154. if (!key.private_key.length()) {
  155. dbg() << "We expected to see a private key, but we found none";
  156. ASSERT_NOT_REACHED();
  157. }
  158. m_private_key = key.private_key;
  159. }
  160. void RSA::import_public_key(const ByteBuffer& buffer, bool pem)
  161. {
  162. // so gods help me, I hate DER
  163. auto decoded_buffer = pem ? decode_pem(buffer) : buffer;
  164. auto key = parse_rsa_key(decoded_buffer.span());
  165. if (!key.public_key.length()) {
  166. dbg() << "We expected to see a public key, but we found none";
  167. ASSERT_NOT_REACHED();
  168. }
  169. m_public_key = key.public_key;
  170. }
  171. template<typename HashFunction>
  172. void RSA_EMSA_PSS<HashFunction>::sign(const ByteBuffer& in, ByteBuffer& out)
  173. {
  174. // -- encode via EMSA_PSS
  175. auto mod_bits = m_rsa.private_key().modulus().trimmed_length() * sizeof(u32) * 8;
  176. u8 EM[mod_bits];
  177. auto EM_buf = ByteBuffer::wrap(EM, mod_bits);
  178. m_emsa_pss.encode(in, EM_buf, mod_bits - 1);
  179. // -- sign via RSA
  180. m_rsa.sign(EM_buf, out);
  181. }
  182. template<typename HashFunction>
  183. VerificationConsistency RSA_EMSA_PSS<HashFunction>::verify(const ByteBuffer& in)
  184. {
  185. auto mod_bytes = m_rsa.public_key().modulus().trimmed_length() * sizeof(u32);
  186. if (in.size() != mod_bytes)
  187. return VerificationConsistency::Inconsistent;
  188. u8 EM[mod_bytes];
  189. auto EM_buf = ByteBuffer::wrap(EM, mod_bytes);
  190. // -- verify via RSA
  191. m_rsa.verify(in, EM_buf);
  192. // -- verify via EMSA_PSS
  193. return m_emsa_pss.verify(in, EM, mod_bytes * 8 - 1);
  194. }
  195. void RSA_PKCS1_EME::encrypt(const ByteBuffer& in, ByteBuffer& out)
  196. {
  197. auto mod_len = (m_public_key.modulus().trimmed_length() * sizeof(u32) * 8 + 7) / 8;
  198. #ifdef CRYPTO_DEBUG
  199. dbg() << "key size: " << mod_len;
  200. #endif
  201. if (in.size() > mod_len - 11) {
  202. dbg() << "message too long :(";
  203. out.trim(0);
  204. return;
  205. }
  206. if (out.size() < mod_len) {
  207. dbg() << "output buffer too small";
  208. return;
  209. }
  210. auto ps_length = mod_len - in.size() - 3;
  211. u8 ps[ps_length];
  212. // FIXME: Without this assertion, GCC refuses to compile due to a memcpy overflow(!?)
  213. ASSERT(ps_length < 16384);
  214. AK::fill_with_random(ps, ps_length);
  215. // since arc4random can create zeros (shocking!)
  216. // we have to go through and un-zero the zeros
  217. for (size_t i = 0; i < ps_length; ++i)
  218. if (!ps[i])
  219. ps[i] = 0xfe;
  220. u8 paddings[] { 0x00, 0x02 };
  221. out.overwrite(0, paddings, 2);
  222. out.overwrite(2, ps, ps_length);
  223. out.overwrite(2 + ps_length, paddings, 1);
  224. out.overwrite(3 + ps_length, in.data(), in.size());
  225. out.trim(3 + ps_length + in.size()); // should be a single block
  226. #ifdef CRYPTO_DEBUG
  227. dbg() << "padded output size: " << 3 + ps_length + in.size() << " buffer size: " << out.size();
  228. #endif
  229. RSA::encrypt(out, out);
  230. }
  231. void RSA_PKCS1_EME::decrypt(const ByteBuffer& in, ByteBuffer& out)
  232. {
  233. auto mod_len = (m_public_key.modulus().trimmed_length() * sizeof(u32) * 8 + 7) / 8;
  234. if (in.size() != mod_len) {
  235. dbg() << "decryption error: wrong amount of data: " << in.size();
  236. out.trim(0);
  237. return;
  238. }
  239. RSA::decrypt(in, out);
  240. if (out.size() < RSA::output_size()) {
  241. dbg() << "decryption error: not enough data after decryption: " << out.size();
  242. out.trim(0);
  243. return;
  244. }
  245. if (out[0] != 0x00) {
  246. dbg() << "invalid padding byte 0 : " << out[0];
  247. return;
  248. }
  249. if (out[1] != 0x02) {
  250. dbg() << "invalid padding byte 1" << out[1];
  251. return;
  252. }
  253. size_t offset = 2;
  254. while (offset < out.size() && out[offset])
  255. ++offset;
  256. if (offset == out.size()) {
  257. dbg() << "garbage data, no zero to split padding";
  258. return;
  259. }
  260. ++offset;
  261. if (offset - 3 < 8) {
  262. dbg() << "PS too small";
  263. return;
  264. }
  265. out = out.slice(offset, out.size() - offset);
  266. }
  267. void RSA_PKCS1_EME::sign(const ByteBuffer&, ByteBuffer&)
  268. {
  269. dbg() << "FIXME: RSA_PKCS_EME::sign";
  270. }
  271. void RSA_PKCS1_EME::verify(const ByteBuffer&, ByteBuffer&)
  272. {
  273. dbg() << "FIXME: RSA_PKCS_EME::verify";
  274. }
  275. }
  276. }