1 /* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include <openssl/rand.h>
16
17 #if defined(OPENSSL_WINDOWS) && !defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
18
19 #include <limits.h>
20 #include <stdlib.h>
21
22 OPENSSL_MSVC_PRAGMA(warning(push, 3))
23
24 #include <windows.h>
25
26 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
27 !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
28 #include <bcrypt.h>
29 OPENSSL_MSVC_PRAGMA(comment(lib, "bcrypt.lib"))
30 #else
31 // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036. See the
32 // "Community Additions" comment on MSDN here:
33 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx
34 #define SystemFunction036 NTAPI SystemFunction036
35 #include <ntsecapi.h>
36 #undef SystemFunction036
37 #endif // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP
38
OPENSSL_MSVC_PRAGMA(warning (pop))39 OPENSSL_MSVC_PRAGMA(warning(pop))
40
41 #include "../fipsmodule/rand/internal.h"
42
43
44 void CRYPTO_sysrand(uint8_t *out, size_t requested) {
45 while (requested > 0) {
46 ULONG output_bytes_this_pass = ULONG_MAX;
47 if (requested < output_bytes_this_pass) {
48 output_bytes_this_pass = (ULONG)requested;
49 }
50 // On non-UWP configurations, use RtlGenRandom instead of BCryptGenRandom
51 // to avoid accessing resources that may be unavailable inside the
52 // Chromium sandbox. See https://crbug.com/boringssl/307
53 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
54 !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
55 if (!BCRYPT_SUCCESS(BCryptGenRandom(
56 /*hAlgorithm=*/NULL, out, output_bytes_this_pass,
57 BCRYPT_USE_SYSTEM_PREFERRED_RNG))) {
58 #else
59 if (RtlGenRandom(out, output_bytes_this_pass) == FALSE) {
60 #endif // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP
61 abort();
62 }
63 requested -= output_bytes_this_pass;
64 out += output_bytes_this_pass;
65 }
66 return;
67 }
68
69 #endif // OPENSSL_WINDOWS && !BORINGSSL_UNSAFE_DETERMINISTIC_MODE
70