xref: /qemu/crypto/random-platform.c (revision 25fb26e4)
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 #else
69     while (1) {
70         ssize_t got = read(fd, buf, buflen);
71         if (likely(got == buflen)) {
72             return 0;
73         }
74         if (got > 0) {
75             buflen -= got;
76             buf += got;
77         } else if (got == 0) {
78             error_setg(errp, "Unexpected EOF reading random bytes");
79             return -1;
80         } else if (errno != EINTR) {
81             error_setg_errno(errp, errno, "Unable to read random bytes");
82             return -1;
83         }
84     }
85 #endif
86     return 0;
87 }
88