mpunsafe.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <assert.h>
  2. #include <limits.h>
  3. #include <stdio.h>
  4. #include "defs.h"
  5. #include "misc.h"
  6. #include "puttymem.h"
  7. #include "mpint.h"
  8. #include "mpint_i.h"
  9. /*
  10. * This global symbol is also defined in ssh2kex-client.c, to ensure
  11. * that these unsafe non-constant-time mp_int functions can't end up
  12. * accidentally linked in to any PuTTY tool that actually makes an SSH
  13. * client connection.
  14. *
  15. * (Only _client_ connections, however. Uppity, being a test server
  16. * only, is exempt.)
  17. */
  18. const int deliberate_symbol_clash = 12345;
  19. static size_t mp_unsafe_words_needed(mp_int *x)
  20. {
  21. size_t words = x->nw;
  22. while (words > 1 && !x->w[words-1])
  23. words--;
  24. return words;
  25. }
  26. mp_int *mp_unsafe_shrink(mp_int *x)
  27. {
  28. x->nw = mp_unsafe_words_needed(x);
  29. /* This potentially leaves some allocated words between the new
  30. * and old values of x->nw, which won't be wiped by mp_free now
  31. * that x->nw doesn't mention that they exist. But we've just
  32. * checked they're all zero, so we don't need to wipe them now
  33. * either. */
  34. return x;
  35. }
  36. mp_int *mp_unsafe_copy(mp_int *x)
  37. {
  38. mp_int *copy = mp_make_sized(mp_unsafe_words_needed(x));
  39. mp_copy_into(copy, x);
  40. return copy;
  41. }
  42. uint32_t mp_unsafe_mod_integer(mp_int *x, uint32_t modulus)
  43. {
  44. uint64_t accumulator = 0;
  45. for (size_t i = mp_max_bytes(x); i-- > 0 ;) {
  46. accumulator = 0x100 * accumulator + mp_get_byte(x, i);
  47. accumulator %= modulus;
  48. }
  49. return accumulator;
  50. }