BsdKernArndSysctlRandomSeed.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/random/seed/BsdKernArndSysctlRandomSeed.h"
  16. #include "util/Identity.h"
  17. #include "util/Bits.h"
  18. #include <unistd.h>
  19. #include <errno.h>
  20. #include <sys/types.h>
  21. #include <sys/sysctl.h>
  22. /** Number of times to try each operation. */
  23. #define MAX_TRIES 10
  24. static int get(RandomSeed_t* randomSeed, uint64_t output[8])
  25. {
  26. int mib[] = { CTL_KERN, KERN_ARND };
  27. Bits_memset(output, 0, 64);
  28. size_t len = 64;
  29. if (sysctl(mib, 2, output, &len, NULL, 0) == -1) {
  30. // TOR/Libevent retry this 4 bytes at a time if it fails initially.
  31. size_t four = 4;
  32. int tries = 0;
  33. union {
  34. uint64_t longs[8];
  35. uint32_t ints[16];
  36. } num;
  37. for (int i = 0; i < 16; i++) {
  38. if (sysctl(mib, 2, &num.ints[i], &four, NULL, 0) == -1) {
  39. return -1;
  40. }
  41. if (num.ints[i] == 0) {
  42. i--;
  43. if (++tries > MAX_TRIES) {
  44. return -1;
  45. }
  46. }
  47. }
  48. }
  49. return Bits_isZero(output, 64) ? -1 : 0;
  50. }
  51. RandomSeed_t* BsdKernArndSysctlRandomSeed_new(struct Allocator* alloc)
  52. {
  53. return Allocator_clone(alloc, (&(RandomSeed_t) {
  54. .get = get,
  55. .name = "sysctl(KERN_ARND) (BSD)"
  56. }));
  57. }