LinuxRandomUuidSysctlRandomSeed.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. #define _GNU_SOURCE
  16. #include "crypto/random/seed/LinuxRandomUuidSysctlRandomSeed.h"
  17. #include "util/Identity.h"
  18. #include "util/Bits.h"
  19. #include "util/Hex.h"
  20. #include <unistd.h>
  21. #include <sys/syscall.h>
  22. #ifndef SYS_getrandom
  23. #include <sys/sysctl.h>
  24. static int getUUID(uint64_t output[2])
  25. {
  26. int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
  27. size_t sixteen = 16;
  28. Bits_memset(output, 0, 16);
  29. if (sysctl(mib, 3, output, &sixteen, NULL, 0)
  30. || Bits_isZero(output, 16))
  31. {
  32. return -1;
  33. }
  34. return 0;
  35. }
  36. #endif
  37. static int get(RandomSeed_t* randomSeed, uint64_t output[8])
  38. {
  39. #ifdef SYS_getrandom
  40. // Try using getrandom instead sysctl as with systems with getrandom
  41. // sysctl is probably alrady deprecated and possibly disabled.
  42. Bits_memset(output, 0, 64); // Just make sure that it is zero all along.
  43. long ret = syscall(SYS_getrandom, output, 64, 0);
  44. if (ret == 64 && !Bits_isZero(output, 64)) {
  45. return 0;
  46. }
  47. return -1;
  48. #else
  49. if (getUUID(output) || getUUID(output+2) || getUUID(output+4) || getUUID(output+6)) {
  50. return -1;
  51. }
  52. return 0;
  53. #endif
  54. }
  55. RandomSeed_t* LinuxRandomUuidSysctlRandomSeed_new(struct Allocator* alloc)
  56. {
  57. return Allocator_clone(alloc, (&(RandomSeed_t) {
  58. .get = get,
  59. .name = "sysctl(RANDOM_UUID) (Linux)"
  60. }));
  61. }