VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Core/RandomNumberGenerator.cpp
blob: 6ad46605e8194304220e86cc99c4ac310ede7ea8 (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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
 Derived from source code of TrueCrypt 7.1a, which is
 Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
 by the TrueCrypt License 3.0.

 Modifications and additions to the original source code (contained in this file)
 and all other portions of this file are Copyright (c) 2013-2017 IDRIX
 and are governed by the Apache License 2.0 the full text of which is
 contained in the file License.txt included in VeraCrypt binary and source
 code distribution packages.
*/

#ifndef TC_WINDOWS
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#endif

#include "RandomNumberGenerator.h"
#include "Volume/Crc32.h"

namespace VeraCrypt
{
	void RandomNumberGenerator::AddSystemDataToPool (bool fast)
	{
		SecureBuffer buffer (PoolSize);

#ifdef TC_WINDOWS
#ifndef DEBUG
		throw NotImplemented (SRC_POS);
#endif
#else
		int urandom = open ("/dev/urandom", O_RDONLY);
		throw_sys_sub_if (urandom == -1, L"/dev/urandom");
		finally_do_arg (int, urandom, { close (finally_arg); });

		throw_sys_sub_if (read (urandom, buffer, buffer.Size()) == -1, L"/dev/urandom");
		AddToPool (buffer);

		if (!fast)
		{
			// Read all bytes available in /dev/random up to buffer size
			int random = open ("/dev/random", O_RDONLY | O_NONBLOCK);
			throw_sys_sub_if (random == -1, L"/dev/random");
			finally_do_arg (int, random, { close (finally_arg); });

			// ensure that we have read /dev/random successfully at least once before continuing
			while (true)
			{
				int rndCount = read (random, buffer, buffer.Size());
				throw_sys_sub_if ((rndCount == -1) && errno != EAGAIN, L"/dev/random");
				if (rndCount == -1 && !DevRandomSucceeded)
				{
					// wait 250ms before querying /dev/random again
					::usleep (250 * 1000);
				}
				else
				{
					if (rndCount != -1)
						DevRandomSucceeded = true;
					break;
				}
			}
			
			AddToPool (buffer);
			
			/* use JitterEntropy library to get good quality random bytes based on CPU timing jitter */
			if (JitterRngCtx)
			{
				ssize_t rndLen = jent_read_entropy (JitterRngCtx, (char*) buffer.Ptr(), buffer.Size());
				if (rndLen > 0)
				{
					AddToPool (buffer);
				}
			}
		}
#endif
	}

	void RandomNumberGenerator::AddToPool (const ConstBufferPtr &data)
	{
		if (!Running)
			throw NotInitialized (SRC_POS);

		ScopeLock lock (AccessMutex);

		for (size_t i = 0; i < data.Size(); ++i)
		{
			Pool[WriteOffset++] += data[i];

			if (WriteOffset >= PoolSize)
				WriteOffset = 0;

			if (++BytesAddedSincePoolHashMix >= MaxBytesAddedBeforePoolHashMix)
				HashMixPool();
		}
	}

	void RandomNumberGenerator::GetData (const BufferPtr &buffer, bool fast, bool allowAnyLength)
	{
		if (!Running)
			throw NotInitialized (SRC_POS);

		if (!allowAnyLength && (buffer.Size() > PoolSize))
			throw ParameterIncorrect (SRC_POS);

		ScopeLock lock (AccessMutex);
		size_t bufferLen = buffer.Size(), loopLen;
		byte* pbBuffer = buffer.Get();
		
		// Initialize JitterEntropy RNG for this call
		if (0 == jent_entropy_init ())
		{
			JitterRngCtx = jent_entropy_collector_alloc (1, 0);
		}

		// Poll system for data
		AddSystemDataToPool (fast);
		HashMixPool();

		while (bufferLen > 0)
		{
			if (bufferLen > PoolSize)
			{
				loopLen = PoolSize;
				bufferLen -= PoolSize;
			}
			else
			{
				loopLen = bufferLen;
				bufferLen = 0;
			}

			// Transfer bytes from pool to output buffer
			for (size_t i = 0; i < loopLen; ++i)
			{
				pbBuffer[i] += Pool[ReadOffset++];

				if (ReadOffset >= PoolSize)
					ReadOffset = 0;
			}

			// Invert and mix the pool
			for (size_t i = 0; i < Pool.Size(); ++i)
			{
				Pool[i] = ~Pool[i];
			}

			AddSystemDataToPool (true);
			HashMixPool();

			// XOR the current pool content into the output buffer to prevent pool state leaks
			for (size_t i = 0; i < loopLen; ++i)
			{
				pbBuffer[i] ^= Pool[ReadOffset++];

				if (ReadOffset >= PoolSize)
					ReadOffset = 0;
			}

			pbBuffer += loopLen;
		}
		
		if (JitterRngCtx)
		{
			jent_entropy_collector_free (JitterRngCtx);
			JitterRngCtx = NULL;
		}
	}

	shared_ptr <Hash> RandomNumberGenerator::GetHash ()
	{
		ScopeLock lock (AccessMutex);
		return PoolHash;
	}

	void RandomNumberGenerator::HashMixPool ()
	{
		BytesAddedSincePoolHashMix = 0;

		for (size_t poolPos = 0; poolPos < Pool.Size(); )
		{
			// Compute the message digest of the entire pool using the selected hash function
			SecureBuffer digest (PoolHash->GetDigestSize());
			PoolHash->ProcessData (Pool);
			PoolHash->GetDigest (digest);

			// Add the message digest to the pool
			for (size_t digestPos = 0; digestPos < digest.Size() && poolPos < Pool.Size(); ++digestPos)
			{
				Pool[poolPos++] += digest[digestPos];
			}
		}
	}

	void RandomNumberGenerator::SetHash (shared_ptr <Hash> hash)
	{
		ScopeLock lock (AccessMutex);
		PoolHash = hash;
	}

	void RandomNumberGenerator::Start ()
	{
		ScopeLock lock (AccessMutex);

		if (IsRunning())
			return;

		BytesAddedSincePoolHashMix = 0;
		ReadOffset = 0;
		WriteOffset = 0;
		Running = true;
		EnrichedByUser = false;

		Pool.Allocate (PoolSize, 16);
		Test();

		if (!PoolHash)
		{
			// First hash algorithm is the default one
			PoolHash = Hash::GetAvailableAlgorithms().front();
		}

		AddSystemDataToPool (true);
	}

	void RandomNumberGenerator::Stop ()
	{
		ScopeLock lock (AccessMutex);

		if (Pool.IsAllocated())
			Pool.Free ();

		PoolHash.reset();

		EnrichedByUser = false;
		Running = false;
		DevRandomSucceeded = false;
	}

	void RandomNumberGenerator::Test ()
	{
		shared_ptr <Hash> origPoolHash = PoolHash;
		PoolHash.reset (new Ripemd160());

		Pool.Zero();
		Buffer buffer (1);
		for (size_t i = 0; i < PoolSize * 10; ++i)
		{
			buffer[0] = (byte) i;
			AddToPool (buffer);
		}

		if (Crc32::ProcessBuffer (Pool) != 0x2de46d17)
			throw TestFailed (SRC_POS);

		buffer.Allocate (PoolSize);
		buffer.CopyFrom (PeekPool());
		AddToPool (buffer);

		if (Crc32::ProcessBuffer (Pool) != 0xcb88e019)
			throw TestFailed (SRC_POS);

		PoolHash = origPoolHash;
	}

	Mutex RandomNumberGenerator::AccessMutex;
	size_t RandomNumberGenerator::BytesAddedSincePoolHashMix;
	bool RandomNumberGenerator::EnrichedByUser;
	SecureBuffer RandomNumberGenerator::Pool;
	shared_ptr <Hash> RandomNumberGenerator::PoolHash;
	size_t RandomNumberGenerator::ReadOffset;
	bool RandomNumberGenerator::Running = false;
	size_t RandomNumberGenerator::WriteOffset;
	struct rand_data *RandomNumberGenerator::JitterRngCtx = NULL;
	bool RandomNumberGenerator::DevRandomSucceeded = false;
}