1
0

BsdKernArndSysctlRandomSeed.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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/Bits.h"
  17. #include <unistd.h>
  18. #include <errno.h>
  19. #include <sys/types.h>
  20. #include <sys/sysctl.h>
  21. /** Number of times to try each operation. */
  22. #define MAX_TRIES 10
  23. static int get(RandomSeed_t* randomSeed, uint64_t output[8])
  24. {
  25. int mib[] = { CTL_KERN, KERN_ARND };
  26. Bits_memset(output, 0, 64);
  27. size_t len = 64;
  28. if (sysctl(mib, 2, output, &len, NULL, 0) == -1) {
  29. // TOR/Libevent retry this 4 bytes at a time if it fails initially.
  30. size_t four = 4;
  31. int tries = 0;
  32. union {
  33. uint64_t longs[8];
  34. uint32_t ints[16];
  35. } num;
  36. for (int i = 0; i < 16; i++) {
  37. if (sysctl(mib, 2, &num.ints[i], &four, NULL, 0) == -1) {
  38. return -1;
  39. }
  40. if (num.ints[i] == 0) {
  41. i--;
  42. if (++tries > MAX_TRIES) {
  43. return -1;
  44. }
  45. }
  46. }
  47. }
  48. return Bits_isZero(output, 64) ? -1 : 0;
  49. }
  50. RandomSeed_t* BsdKernArndSysctlRandomSeed_new(struct Allocator* alloc)
  51. {
  52. return Allocator_clone(alloc, (&(RandomSeed_t) {
  53. .get = get,
  54. .name = "sysctl(KERN_ARND) (BSD)"
  55. }));
  56. }