1 // SPDX-License-Identifier: GPL-2.0 OR MIT
3 * Copyright (C) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
10 #include <sys/types.h>
15 #include <sys/syscall.h>
18 #include <AvailabilityMacros.h>
19 #ifndef MAC_OS_X_VERSION_10_12
20 #define MAC_OS_X_VERSION_10_12 101200
22 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12
23 #include <sys/random.h>
27 #include "curve25519.h"
29 #include "subcommands.h"
32 static inline bool __attribute__((__warn_unused_result__)) get_random_bytes(uint8_t *out, size_t len)
43 #if defined(__OpenBSD__) || (defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12) || (defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 25)))
44 if (!getentropy(out, len))
48 #if defined(__NR_getrandom) && defined(__linux__)
49 if (syscall(__NR_getrandom, out, len, 0) == (ssize_t)len)
53 fd = open("/dev/urandom", O_RDONLY);
56 for (errno = 0, i = 0; i < len; i += ret, ret = 0) {
57 ret = read(fd, out + i, len - i);
59 ret = errno ? -errno : -EIO;
69 static inline bool __attribute__((__warn_unused_result__)) get_random_bytes(uint8_t *out, size_t len)
71 return RtlGenRandom(out, len);
75 int genkey_main(int argc, const char *argv[])
77 uint8_t key[WG_KEY_LEN];
78 char base64[WG_KEY_LEN_BASE64];
82 fprintf(stderr, "Usage: %s %s\n", PROG_NAME, argv[0]);
86 if (!fstat(STDOUT_FILENO, &stat) && S_ISREG(stat.st_mode) && stat.st_mode & S_IRWXO)
87 fputs("Warning: writing to world accessible file.\nConsider setting the umask to 077 and trying again.\n", stderr);
89 if (!get_random_bytes(key, WG_KEY_LEN)) {
93 if (!strcmp(argv[0], "genkey"))
94 curve25519_clamp_secret(key);
96 key_to_base64(base64, key);