ProcSysKernelRandomUuidRandomSeed.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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/ProcSysKernelRandomUuidRandomSeed.h"
  16. #include "util/Hex.h"
  17. #include <sys/types.h>
  18. #include <sys/stat.h>
  19. #include <fcntl.h>
  20. #include <unistd.h>
  21. #include <errno.h>
  22. /** Number of times to try each operation. */
  23. #define MAX_TRIES 10
  24. static int getUUID(uint64_t output[2])
  25. {
  26. uint8_t buffer[40] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
  27. {
  28. int fd = -1;
  29. int tries = 0;
  30. while ((fd = open("/proc/sys/kernel/random/uuid", O_RDONLY, 0)) < 0) {
  31. if (++tries > MAX_TRIES || errno != EINTR) {
  32. return -1;
  33. }
  34. sleep(1);
  35. }
  36. tries = 0;
  37. uint8_t* buff = (uint8_t*) buffer;
  38. int count = 37;
  39. while (count > 0) {
  40. int r = read(fd, buff, count);
  41. if (r < 1) {
  42. if (++tries > MAX_TRIES) {
  43. break;
  44. }
  45. sleep(1);
  46. continue;
  47. }
  48. buff += r;
  49. count -= r;
  50. }
  51. close(fd);
  52. if (count != 0) {
  53. return -1;
  54. }
  55. }
  56. // If it isn't in perfect form, fail.
  57. if (!(buffer[8] == '-'
  58. && buffer[13] == '-'
  59. && buffer[18] == '-'
  60. && buffer[23] == '-'
  61. && buffer[36] == '\n'))
  62. {
  63. return -1;
  64. }
  65. // fold back the last 4 characters into the locations of the dashes.
  66. buffer[8] = buffer[35];
  67. buffer[13] = buffer[34];
  68. buffer[18] = buffer[33];
  69. buffer[23] = buffer[32];
  70. buffer[32] = '\0';
  71. if (Hex_decode((uint8_t*)output, 16, buffer, 32) != 16) {
  72. return -1;
  73. }
  74. return 0;
  75. }
  76. static int get(RandomSeed_t* randomSeed, uint64_t output[8])
  77. {
  78. if (getUUID(output) || getUUID(output+2) || getUUID(output+4) || getUUID(output+6)) {
  79. return -1;
  80. }
  81. return 0;
  82. }
  83. RandomSeed_t* ProcSysKernelRandomUuidRandomSeed_new(struct Allocator* alloc)
  84. {
  85. return Allocator_clone(alloc, (&(RandomSeed_t) {
  86. .get = get,
  87. .name = "/proc/sys/kernel/random/uuid (Linux)"
  88. }));
  89. }