xref: /qemu/crypto/random-platform.c (revision 14a356f47560c8275b8e04fbee484a617fc45f80)
1 /*
2  * QEMU Crypto random number provider
3  *
4  * Copyright (c) 2015-2016 Red Hat, Inc.
5  *
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 of the License, or (at your option) any later version.
10  *
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.
15  *
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/>.
18  *
19  */
20 
21 #include "qemu/osdep.h"
22 
23 #include "crypto/random.h"
24 #include "qapi/error.h"
25 
26 #ifdef _WIN32
27 #include <wincrypt.h>
28 static HCRYPTPROV hCryptProv;
29 #else
30 static int fd; /* a file handle to either /dev/urandom or /dev/random */
31 #endif
32 
33 int qcrypto_random_init(Error **errp)
34 {
35 #ifdef _WIN32
36     if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
37                              CRYPT_SILENT | CRYPT_VERIFYCONTEXT)) {
38         error_setg_win32(errp, GetLastError(),
39                          "Unable to create cryptographic provider");
40         return -1;
41     }
42 #else
43     /* TBD perhaps also add support for BSD getentropy / Linux
44      * getrandom syscalls directly */
45     fd = open("/dev/urandom", O_RDONLY);
46     if (fd == -1 && errno == ENOENT) {
47         fd = open("/dev/random", O_RDONLY);
48     }
49 
50     if (fd < 0) {
51         error_setg(errp, "No /dev/urandom or /dev/random found");
52         return -1;
53     }
54 #endif
55     return 0;
56 }
57 
58 int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
59                          size_t buflen G_GNUC_UNUSED,
60                          Error **errp)
61 {
62 #ifdef _WIN32
63     if (!CryptGenRandom(hCryptProv, buflen, buf)) {
64         error_setg_win32(errp, GetLastError(),
65                          "Unable to read random bytes");
66         return -1;
67     }
68 
69     return 0;
70 #else
71     int ret = -1;
72     int got;
73 
74     while (buflen > 0) {
75         got = read(fd, buf, buflen);
76         if (got < 0) {
77             error_setg_errno(errp, errno,
78                              "Unable to read random bytes");
79             goto cleanup;
80         } else if (!got) {
81             error_setg(errp,
82                        "Unexpected EOF reading random bytes");
83             goto cleanup;
84         }
85         buflen -= got;
86         buf += got;
87     }
88 
89     ret = 0;
90  cleanup:
91     return ret;
92 #endif
93 }
94