2 * QEMU Crypto random number provider
4 * Copyright (c) 2015-2016 Red Hat, Inc.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "qemu/osdep.h"
23 #include "crypto/random.h"
24 #include "qapi/error.h"
28 static HCRYPTPROV hCryptProv
;
30 # ifdef CONFIG_GETRANDOM
31 # include <sys/random.h>
33 /* This is -1 for getrandom(), or a file handle for /dev/{u,}random. */
37 int qcrypto_random_init(Error
**errp
)
40 if (!CryptAcquireContext(&hCryptProv
, NULL
, NULL
, PROV_RSA_FULL
,
41 CRYPT_SILENT
| CRYPT_VERIFYCONTEXT
)) {
42 error_setg_win32(errp
, GetLastError(),
43 "Unable to create cryptographic provider");
47 # ifdef CONFIG_GETRANDOM
48 if (getrandom(NULL
, 0, 0) == 0) {
53 /* Fall through to /dev/urandom case. */
55 fd
= open("/dev/urandom", O_RDONLY
| O_CLOEXEC
);
56 if (fd
== -1 && errno
== ENOENT
) {
57 fd
= open("/dev/random", O_RDONLY
| O_CLOEXEC
);
60 error_setg_errno(errp
, errno
, "No /dev/urandom or /dev/random");
67 int qcrypto_random_bytes(void *buf
,
72 if (!CryptGenRandom(hCryptProv
, buflen
, buf
)) {
73 error_setg_win32(errp
, GetLastError(),
74 "Unable to read random bytes");
78 # ifdef CONFIG_GETRANDOM
81 ssize_t got
= getrandom(buf
, buflen
, 0);
82 if (likely(got
== buflen
)) {
88 } else if (errno
!= EINTR
) {
89 error_setg_errno(errp
, errno
, "getrandom");
94 /* Fall through to /dev/urandom case. */
97 ssize_t got
= read(fd
, buf
, buflen
);
98 if (likely(got
== buflen
)) {
104 } else if (got
== 0) {
105 error_setg(errp
, "Unexpected EOF reading random bytes");
107 } else if (errno
!= EINTR
) {
108 error_setg_errno(errp
, errno
, "Unable to read random bytes");