aboutsummaryrefslogtreecommitdiff
path: root/src/port/pg_strong_random.c
blob: 6d85f50b7c8dcd523862a94a5e0e8a3b54ff3ea7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*-------------------------------------------------------------------------
 *
 * pg_strong_random.c
 *	  generate a cryptographically secure random number
 *
 * Our definition of "strong" is that it's suitable for generating random
 * salts and query cancellation keys, during authentication.
 *
 * Note: this code is run quite early in postmaster and backend startup;
 * therefore, even when built for backend, it cannot rely on backend
 * infrastructure such as elog() or palloc().
 *
 * Copyright (c) 1996-2020, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
 *	  src/port/pg_strong_random.c
 *
 *-------------------------------------------------------------------------
 */

#include "c.h"

#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>

#ifdef USE_OPENSSL_RANDOM
#include <openssl/rand.h>
#endif
#ifdef USE_WIN32_RANDOM
#include <wincrypt.h>
#endif

#ifdef USE_WIN32_RANDOM
/*
 * Cache a global crypto provider that only gets freed when the process
 * exits, in case we need random numbers more than once.
 */
static HCRYPTPROV hProvider = 0;
#endif

#if defined(USE_DEV_URANDOM)
/*
 * Read (random) bytes from a file.
 */
static bool
random_from_file(const char *filename, void *buf, size_t len)
{
	int			f;
	char	   *p = buf;
	ssize_t		res;

	f = open(filename, O_RDONLY, 0);
	if (f == -1)
		return false;

	while (len)
	{
		res = read(f, p, len);
		if (res <= 0)
		{
			if (errno == EINTR)
				continue;		/* interrupted by signal, just retry */

			close(f);
			return false;
		}

		p += res;
		len -= res;
	}

	close(f);
	return true;
}
#endif

/*
 * pg_strong_random_init
 *
 * Initialize the randomness state of "strong" random numbers.  This is invoked
 * *after* forking a process, and should include initialization steps specific
 * to the chosen random source to prove fork-safety.
 */
void
pg_strong_random_init(void)
{
#if defined(USE_OPENSSL)
	/*
	 * Make sure processes do not share OpenSSL randomness state. We need to
	 * call this even if pg_strong_random is implemented using another source
	 * for random numbers to ensure fork-safety in our TLS backend.  This is no
	 * longer required in OpenSSL 1.1.1 and later versions, but until we drop
	 * support for version < 1.1.1 we need to do this.
	*/
	RAND_poll();
#endif

#if defined(USE_OPENSSL_RANDOM)
	/*
	 * In case the backend is using the PRNG from OpenSSL without being built
	 * with support for OpenSSL, make sure to perform post-fork initialization.
	 * If the backend is using OpenSSL then we have already performed this
	 * step. The same version caveat as discussed in the comment above applies
	 * here as well.
	 */
#ifndef USE_OPENSSL
	RAND_poll();
#endif

#elif defined(USE_WIN32_RANDOM)
	/* no initialization needed for WIN32 */

#elif defined(USE_DEV_URANDOM)
	/* no initialization needed for /dev/urandom */

#else
#error no source of random numbers configured
#endif
}

/*
 * pg_strong_random
 *
 * Generate requested number of random bytes. The returned bytes are
 * cryptographically secure, suitable for use e.g. in authentication.
 *
 * We rely on system facilities for actually generating the numbers.
 * We support a number of sources:
 *
 * 1. OpenSSL's RAND_bytes()
 * 2. Windows' CryptGenRandom() function
 * 3. /dev/urandom
 *
 * The configure script will choose which one to use, and set
 * a USE_*_RANDOM flag accordingly.
 *
 * Returns true on success, and false if none of the sources
 * were available. NB: It is important to check the return value!
 * Proceeding with key generation when no random data was available
 * would lead to predictable keys and security issues.
 */
bool
pg_strong_random(void *buf, size_t len)
{
	/*
	 * When built with OpenSSL, use OpenSSL's RAND_bytes function.
	 */
#if defined(USE_OPENSSL_RANDOM)
	int			i;

	/*
	 * Check that OpenSSL's CSPRNG has been sufficiently seeded, and if not
	 * add more seed data using RAND_poll().  With some older versions of
	 * OpenSSL, it may be necessary to call RAND_poll() a number of times.  If
	 * RAND_poll() fails to generate seed data within the given amount of
	 * retries, subsequent RAND_bytes() calls will fail, but we allow that to
	 * happen to let pg_strong_random() callers handle that with appropriate
	 * error handling.
	 */
#define NUM_RAND_POLL_RETRIES 8

	for (i = 0; i < NUM_RAND_POLL_RETRIES; i++)
	{
		if (RAND_status() == 1)
		{
			/* The CSPRNG is sufficiently seeded */
			break;
		}

		RAND_poll();
	}

	if (RAND_bytes(buf, len) == 1)
		return true;
	return false;

	/*
	 * Windows has CryptoAPI for strong cryptographic numbers.
	 */
#elif defined(USE_WIN32_RANDOM)
	if (hProvider == 0)
	{
		if (!CryptAcquireContext(&hProvider,
								 NULL,
								 MS_DEF_PROV,
								 PROV_RSA_FULL,
								 CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
		{
			/*
			 * On failure, set back to 0 in case the value was for some reason
			 * modified.
			 */
			hProvider = 0;
		}
	}
	/* Re-check in case we just retrieved the provider */
	if (hProvider != 0)
	{
		if (CryptGenRandom(hProvider, len, buf))
			return true;
	}
	return false;

	/*
	 * Read /dev/urandom ourselves.
	 */
#elif defined(USE_DEV_URANDOM)
	if (random_from_file("/dev/urandom", buf, len))
		return true;
	return false;

#else
	/* The autoconf script should not have allowed this */
#error no source of random numbers configured
#endif
}