safenonce.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include "crypto_uint64.h"
  6. #include "uint64_pack.h"
  7. #include "uint64_unpack.h"
  8. #include "savesync.h"
  9. #include "open.h"
  10. #include "load.h"
  11. #include "randombytes.h"
  12. #include "safenonce.h"
  13. #include "crypto_block.h"
  14. #if crypto_block_BYTES != 16
  15. error!
  16. #endif
  17. #if crypto_block_KEYBYTES != 32
  18. error!
  19. #endif
  20. /*
  21. Output: 128-bit nonce y[0],...,y[15].
  22. Reads and writes existing 8-byte file ".expertsonly/noncecounter",
  23. locked via existing 1-byte file ".expertsonly/lock".
  24. Also reads existing 32-byte file ".expertsonly/noncekey".
  25. Not thread-safe.
  26. Invariants:
  27. This process is free to use counters that are >=counterlow and <counterhigh.
  28. The 8-byte file contains a counter that is safe to use and >=counterhigh.
  29. XXX: should rewrite file in background, rather than briefly pausing
  30. */
  31. static crypto_uint64 counterlow = 0;
  32. static crypto_uint64 counterhigh = 0;
  33. static unsigned char flagkeyloaded = 0;
  34. static unsigned char noncekey[32];
  35. static unsigned char data[16];
  36. int safenonce(unsigned char *y,int flaglongterm)
  37. {
  38. if (!flagkeyloaded) {
  39. int fdlock;
  40. fdlock = open_lock(".expertsonly/lock");
  41. if (fdlock == -1) return -1;
  42. if (load(".expertsonly/noncekey",noncekey,sizeof noncekey) == -1) { close(fdlock); return -1; }
  43. close(fdlock);
  44. flagkeyloaded = 1;
  45. }
  46. if (counterlow >= counterhigh) {
  47. int fdlock;
  48. fdlock = open_lock(".expertsonly/lock");
  49. if (fdlock == -1) return -1;
  50. if (load(".expertsonly/noncecounter",data,8) == -1) { close(fdlock); return -1; }
  51. counterlow = uint64_unpack(data);
  52. if (flaglongterm)
  53. counterhigh = counterlow + 1048576;
  54. else
  55. counterhigh = counterlow + 1;
  56. uint64_pack(data,counterhigh);
  57. if (savesync(".expertsonly/noncecounter",data,8) == -1) { close(fdlock); return -1; }
  58. close(fdlock);
  59. }
  60. randombytes(data + 8,8);
  61. uint64_pack(data,counterlow++);
  62. crypto_block(y,data,noncekey);
  63. return 0;
  64. }