File: CryptoRandom.cs

package info (click to toggle)
keepass2 2.57%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 14,520 kB
  • sloc: cs: 120,930; xml: 6,271; cpp: 322; sh: 53; makefile: 42
file content (385 lines) | stat: -rw-r--r-- 10,199 bytes parent folder | download | duplicates (3)
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2024 Dominik Reichl <dominik.reichl@t-online.de>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;

#if !KeePassUAP
using System.Drawing;
using System.Security.Cryptography;
using System.Windows.Forms;
#endif

using KeePassLib.Delegates;
using KeePassLib.Native;
using KeePassLib.Security;
using KeePassLib.Utility;

namespace KeePassLib.Cryptography
{
	/// <summary>
	/// Cryptographically secure pseudo-random number generator.
	/// The returned values are unpredictable and cannot be reproduced.
	/// <c>CryptoRandom</c> is a singleton class.
	/// </summary>
	public sealed class CryptoRandom
	{
		private readonly RNGCryptoServiceProvider m_rng = new RNGCryptoServiceProvider();
		private ProtectedBinary m_pbEntropyPool;
		private ulong m_uCounter;
		private ulong m_uGeneratedBytesCount = 0;

		private static readonly object g_oSyncRoot = new object();
		private readonly object m_oSyncRoot = new object();

		private static CryptoRandom g_pInstance = null;
		public static CryptoRandom Instance
		{
			get
			{
				CryptoRandom cr;
				lock(g_oSyncRoot)
				{
					cr = g_pInstance;
					if(cr == null)
					{
						cr = new CryptoRandom();
						g_pInstance = cr;
					}
				}

				return cr;
			}
		}

		/// <summary>
		/// Get the number of random bytes that this instance generated so far.
		/// Note that this number can be higher than the number of random bytes
		/// actually requested using the <c>GetRandomBytes</c> method.
		/// </summary>
		public ulong GeneratedBytesCount
		{
			get
			{
				ulong u;
				lock(m_oSyncRoot) { u = m_uGeneratedBytesCount; }
				return u;
			}
		}

		/// <summary>
		/// Event that is triggered whenever the internal <c>GenerateRandom256</c>
		/// method is called to generate random bytes.
		/// </summary>
		public event EventHandler GenerateRandom256Pre;

		private CryptoRandom()
		{
			byte[] pb = GetSystemEntropy();
			Debug.Assert(pb.Length == 64);
			m_pbEntropyPool = new ProtectedBinary(true, pb);
			MemUtil.ZeroByteArray(pb);

			m_uCounter = (ulong)DateTime.UtcNow.ToBinary();
		}

		/// <summary>
		/// Update the internal seed of the random number generator based
		/// on entropy data.
		/// This method is thread-safe.
		/// </summary>
		/// <param name="pbEntropy">Entropy bytes.</param>
		public void AddEntropy(byte[] pbEntropy)
		{
			if(pbEntropy == null) { Debug.Assert(false); return; }
			if(pbEntropy.Length == 0) { Debug.Assert(false); return; }

			byte[] pbNewData = pbEntropy;
			if(pbEntropy.Length > 64)
			{
#if KeePassLibSD
				using(SHA256Managed hNew = new SHA256Managed())
#else
				using(SHA512Managed hNew = new SHA512Managed())
#endif
				{
					pbNewData = hNew.ComputeHash(pbEntropy);
				}
			}

			lock(m_oSyncRoot)
			{
				byte[] pbPool = m_pbEntropyPool.ReadData();
				int cbPool = pbPool.Length;
				int cbNew = pbNewData.Length;

				byte[] pbCmp = new byte[cbPool + cbNew];
				Array.Copy(pbPool, pbCmp, cbPool);
				Array.Copy(pbNewData, 0, pbCmp, cbPool, cbNew);

#if KeePassLibSD
				using(SHA256Managed hPool = new SHA256Managed())
#else
				using(SHA512Managed hPool = new SHA512Managed())
#endif
				{
					byte[] pbNewPool = hPool.ComputeHash(pbCmp);
					m_pbEntropyPool = new ProtectedBinary(true, pbNewPool);
					MemUtil.ZeroByteArray(pbNewPool);
				}

				MemUtil.ZeroByteArray(pbCmp);
				MemUtil.ZeroByteArray(pbPool);
			}

			if(pbNewData != pbEntropy) MemUtil.ZeroByteArray(pbNewData);
		}

		private byte[] GetSystemEntropy()
		{
			SHA512Managed h = new SHA512Managed();
			byte[] pb4 = new byte[4];
			byte[] pb8 = new byte[8];

			GAction<byte[], bool> f = delegate(byte[] pbValue, bool bClearValue)
			{
				if(pbValue == null) { Debug.Assert(false); return; }
				if(pbValue.Length == 0) return;
				h.TransformBlock(pbValue, 0, pbValue.Length, pbValue, 0);
				if(bClearValue) MemUtil.ZeroByteArray(pbValue);
			};
			Action<int> fI32 = delegate(int iValue)
			{
				MemUtil.Int32ToBytesEx(iValue, pb4, 0);
				f(pb4, false);
			};
			Action<long> fI64 = delegate(long lValue)
			{
				MemUtil.Int64ToBytesEx(lValue, pb8, 0);
				f(pb8, false);
			};
			Action<string> fStr = delegate(string strValue)
			{
				if(strValue == null) { Debug.Assert(false); return; }
				if(strValue.Length == 0) return;
				f(StrUtil.Utf8.GetBytes(strValue), false);
			};

			fI32(Environment.TickCount);
			fI64(DateTime.UtcNow.ToBinary());

#if !KeePassLibSD
			// In try-catch for systems without GUI;
			// https://sourceforge.net/p/keepass/discussion/329221/thread/20335b73/
			try
			{
				Point pt = Cursor.Position;
				fI32(pt.X);
				fI32(pt.Y);
			}
			catch(Exception) { Debug.Assert(NativeLib.IsUnix()); }
#endif

			try
			{
				fI32((int)NativeLib.GetPlatformID());
#if KeePassUAP
				fStr(EnvironmentExt.OSVersion.VersionString);
#else
				fStr(Environment.OSVersion.VersionString);
#endif

				fI32(Environment.ProcessorCount);

#if !KeePassUAP
				fStr(Environment.CommandLine);
				fI64(Environment.WorkingSet);
#endif
			}
			catch(Exception) { Debug.Assert(false); }

			try
			{
				foreach(DictionaryEntry de in Environment.GetEnvironmentVariables())
				{
					fStr(de.Key as string);
					fStr(de.Value as string);
				}
			}
			catch(Exception) { Debug.Assert(false); }

			try
			{
#if KeePassUAP
				f(DiagnosticsExt.GetProcessEntropy(), true);
#elif !KeePassLibSD
				using(Process p = Process.GetCurrentProcess())
				{
					fI64(p.Handle.ToInt64());
					fI32(p.HandleCount);
					fI32(p.Id);
					fI64(p.NonpagedSystemMemorySize64);
					fI64(p.PagedMemorySize64);
					fI64(p.PagedSystemMemorySize64);
					fI64(p.PeakPagedMemorySize64);
					fI64(p.PeakVirtualMemorySize64);
					fI64(p.PeakWorkingSet64);
					fI64(p.PrivateMemorySize64);
					fI64(p.StartTime.ToBinary());
					fI64(p.VirtualMemorySize64);
					fI64(p.WorkingSet64);

					// Not supported in Mono 1.2.6:
					// fI32(p.SessionId);
				}
#endif
			}
			catch(Exception) { Debug.Assert(NativeLib.IsUnix()); }

			try
			{
				CultureInfo ci = CultureInfo.CurrentCulture;
				if(ci != null) fI32(ci.GetHashCode());
				else { Debug.Assert(false); }
			}
			catch(Exception) { Debug.Assert(false); }

			f(Guid.NewGuid().ToByteArray(), false);
			f(GetCspRandom(), true);

			h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);
			byte[] pbHash = h.Hash;
			h.Clear();
			MemUtil.ZeroByteArray(pb4);
			MemUtil.ZeroByteArray(pb8);
			return pbHash;
		}

		private byte[] GetCspRandom()
		{
			byte[] pb = new byte[32];

			try { m_rng.GetBytes(pb); }
			catch(Exception)
			{
				Debug.Assert(false);
				MemUtil.Int64ToBytesEx(DateTime.UtcNow.ToBinary(), pb, 0);
			}

			return pb;
		}

		private byte[] GenerateRandom256()
		{
			if(this.GenerateRandom256Pre != null)
				this.GenerateRandom256Pre(this, EventArgs.Empty);

			byte[] pbCmp;
			lock(m_oSyncRoot)
			{
				m_uCounter += 0x74D8B29E4D38E161UL;

				byte[] pbPool = m_pbEntropyPool.ReadData();
				byte[] pbCtr = MemUtil.UInt64ToBytes(m_uCounter);
				byte[] pbCsp = GetCspRandom();

				int cbPool = pbPool.Length;
				int cbCtr = pbCtr.Length;
				int cbCsp = pbCsp.Length;

				pbCmp = new byte[cbPool + cbCtr + cbCsp];
				Array.Copy(pbPool, pbCmp, cbPool);
				Array.Copy(pbCtr, 0, pbCmp, cbPool, cbCtr);
				Array.Copy(pbCsp, 0, pbCmp, cbPool + cbCtr, cbCsp);

				MemUtil.ZeroByteArray(pbPool);
				MemUtil.ZeroByteArray(pbCtr);
				MemUtil.ZeroByteArray(pbCsp);

				m_uGeneratedBytesCount += 32;
			}

			byte[] pbRet = CryptoUtil.HashSha256(pbCmp);
			MemUtil.ZeroByteArray(pbCmp);
			return pbRet;
		}

		/// <summary>
		/// Get a number of cryptographically strong random bytes.
		/// This method is thread-safe.
		/// </summary>
		/// <param name="uRequestedBytes">Number of requested random bytes.</param>
		/// <returns>A byte array consisting of <paramref name="uRequestedBytes" />
		/// random bytes.</returns>
		public byte[] GetRandomBytes(uint uRequestedBytes)
		{
			if(uRequestedBytes == 0) return MemUtil.EmptyByteArray;
			if(uRequestedBytes > (uint)int.MaxValue)
			{
				Debug.Assert(false);
				throw new ArgumentOutOfRangeException("uRequestedBytes");
			}

			int cbRem = (int)uRequestedBytes;
			byte[] pbRes = new byte[cbRem];
			int iPos = 0;

			while(cbRem != 0)
			{
				byte[] pbRandom256 = GenerateRandom256();
				Debug.Assert(pbRandom256.Length == 32);

				int cbCopy = Math.Min(cbRem, pbRandom256.Length);
				Array.Copy(pbRandom256, 0, pbRes, iPos, cbCopy);

				MemUtil.ZeroByteArray(pbRandom256);

				iPos += cbCopy;
				cbRem -= cbCopy;
			}

			Debug.Assert(iPos == pbRes.Length);
			return pbRes;
		}

		private static int g_iWeakSeed = 0;
		public static Random NewWeakRandom()
		{
			long s64 = DateTime.UtcNow.ToBinary();
			int s32 = (int)((s64 >> 32) ^ s64);

			lock(g_oSyncRoot)
			{
				unchecked
				{
					g_iWeakSeed += 0x78A8C4B7;
					s32 ^= g_iWeakSeed;
				}
			}

			// Prevent overflow in the Random constructor of .NET 2.0
			if(s32 == int.MinValue) s32 = int.MaxValue;

			return new Random(s32);
		}
	}
}