File: HmacBlockStream.cs

package info (click to toggle)
keepass2 2.35%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 13,756 kB
  • ctags: 16,254
  • sloc: cs: 97,622; xml: 5,686; cpp: 311; makefile: 53; sh: 11
file content (324 lines) | stat: -rw-r--r-- 8,884 bytes parent folder | download
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
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2017 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.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

#if !KeePassUAP
using System.Security.Cryptography;
#endif

using KeePassLib.Resources;
using KeePassLib.Utility;

namespace KeePassLib.Serialization
{
	public sealed class HmacBlockStream : Stream
	{
		private const int NbDefaultBufferSize = 1024 * 1024; // 1 MB

		private Stream m_sBase;
		private readonly bool m_bWriting;
		private readonly bool m_bVerify;
		private byte[] m_pbKey;

		private bool m_bEos = false;
		private byte[] m_pbBuffer;
		private int m_iBufferPos = 0;

		private ulong m_uBlockIndex = 0;

		public override bool CanRead
		{
			get { return !m_bWriting; }
		}

		public override bool CanSeek
		{
			get { return false; }
		}

		public override bool CanWrite
		{
			get { return m_bWriting; }
		}

		public override long Length
		{
			get { Debug.Assert(false); throw new NotSupportedException(); }
		}

		public override long Position
		{
			get { Debug.Assert(false); throw new NotSupportedException(); }
			set { Debug.Assert(false); throw new NotSupportedException(); }
		}

		public HmacBlockStream(Stream sBase, bool bWriting, bool bVerify,
			byte[] pbKey)
		{
			if(sBase == null) throw new ArgumentNullException("sBase");
			if(pbKey == null) throw new ArgumentNullException("pbKey");

			m_sBase = sBase;
			m_bWriting = bWriting;
			m_bVerify = bVerify;
			m_pbKey = pbKey;

			if(!m_bWriting) // Reading mode
			{
				if(!m_sBase.CanRead) throw new InvalidOperationException();

				m_pbBuffer = MemUtil.EmptyByteArray;
			}
			else // Writing mode
			{
				if(!m_sBase.CanWrite) throw new InvalidOperationException();

				m_pbBuffer = new byte[NbDefaultBufferSize];
			}
		}

		protected override void Dispose(bool disposing)
		{
			if(disposing && (m_sBase != null))
			{
				if(m_bWriting)
				{
					if(m_iBufferPos == 0) // No data left in buffer
						WriteSafeBlock(); // Write terminating block
					else
					{
						WriteSafeBlock(); // Write remaining buffered data
						WriteSafeBlock(); // Write terminating block
					}

					Flush();
				}

				m_sBase.Close();
				m_sBase = null;
			}

			base.Dispose(disposing);
		}

		public override void Flush()
		{
			Debug.Assert(m_sBase != null); // Object should not be disposed
			if(m_bWriting && (m_sBase != null)) m_sBase.Flush();
		}

		public override long Seek(long lOffset, SeekOrigin soOrigin)
		{
			Debug.Assert(false);
			throw new NotSupportedException();
		}

		public override void SetLength(long lValue)
		{
			Debug.Assert(false);
			throw new NotSupportedException();
		}

		internal static byte[] GetHmacKey64(byte[] pbKey, ulong uBlockIndex)
		{
			if(pbKey == null) throw new ArgumentNullException("pbKey");
			Debug.Assert(pbKey.Length == 64);

			// We are computing the HMAC using SHA-256, whose internal
			// block size is 512 bits; thus create a key that is 512
			// bits long (using SHA-512)

			byte[] pbBlockKey;
			using(SHA512Managed h = new SHA512Managed())
			{
				byte[] pbIndex = MemUtil.UInt64ToBytes(uBlockIndex);

				h.TransformBlock(pbIndex, 0, pbIndex.Length, pbIndex, 0);
				h.TransformBlock(pbKey, 0, pbKey.Length, pbKey, 0);
				h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

				pbBlockKey = h.Hash;
			}

#if DEBUG
			byte[] pbZero = new byte[64];
			Debug.Assert((pbBlockKey.Length == 64) && !MemUtil.ArraysEqual(
				pbBlockKey, pbZero)); // Ensure we own pbBlockKey
#endif
			return pbBlockKey;
		}

		public override int Read(byte[] pbBuffer, int iOffset, int nCount)
		{
			if(m_bWriting) throw new InvalidOperationException();

			int nRemaining = nCount;
			while(nRemaining > 0)
			{
				if(m_iBufferPos == m_pbBuffer.Length)
				{
					if(!ReadSafeBlock())
						return (nCount - nRemaining); // Bytes actually read
				}

				int nCopy = Math.Min(m_pbBuffer.Length - m_iBufferPos, nRemaining);
				Debug.Assert(nCopy > 0);

				Array.Copy(m_pbBuffer, m_iBufferPos, pbBuffer, iOffset, nCopy);

				iOffset += nCopy;
				m_iBufferPos += nCopy;

				nRemaining -= nCopy;
			}

			return nCount;
		}

		private bool ReadSafeBlock()
		{
			if(m_bEos) return false; // End of stream reached already

			byte[] pbStoredHmac = MemUtil.Read(m_sBase, 32);
			if((pbStoredHmac == null) || (pbStoredHmac.Length != 32))
				throw new EndOfStreamException(KLRes.FileCorrupted + " " +
					KLRes.FileIncomplete);

			// Block index is implicit: it's used in the HMAC computation,
			// but does not need to be stored
			// byte[] pbBlockIndex = MemUtil.Read(m_sBase, 8);
			// if((pbBlockIndex == null) || (pbBlockIndex.Length != 8))
			//	throw new EndOfStreamException();
			// ulong uBlockIndex = MemUtil.BytesToUInt64(pbBlockIndex);
			// if((uBlockIndex != m_uBlockIndex) && m_bVerify)
			//	throw new InvalidDataException();
			byte[] pbBlockIndex = MemUtil.UInt64ToBytes(m_uBlockIndex);

			byte[] pbBlockSize = MemUtil.Read(m_sBase, 4);
			if((pbBlockSize == null) || (pbBlockSize.Length != 4))
				throw new EndOfStreamException(KLRes.FileCorrupted + " " +
					KLRes.FileIncomplete);
			int nBlockSize = MemUtil.BytesToInt32(pbBlockSize);
			if(nBlockSize < 0)
				throw new InvalidDataException(KLRes.FileCorrupted);

			m_iBufferPos = 0;

			m_pbBuffer = MemUtil.Read(m_sBase, nBlockSize);
			if((m_pbBuffer == null) || ((m_pbBuffer.Length != nBlockSize) && m_bVerify))
				throw new EndOfStreamException(KLRes.FileCorrupted + " " +
					KLRes.FileIncompleteExpc);

			if(m_bVerify)
			{
				byte[] pbCmpHmac;
				byte[] pbBlockKey = GetHmacKey64(m_pbKey, m_uBlockIndex);
				using(HMACSHA256 h = new HMACSHA256(pbBlockKey))
				{
					h.TransformBlock(pbBlockIndex, 0, pbBlockIndex.Length,
						pbBlockIndex, 0);
					h.TransformBlock(pbBlockSize, 0, pbBlockSize.Length,
						pbBlockSize, 0);

					if(m_pbBuffer.Length > 0)
						h.TransformBlock(m_pbBuffer, 0, m_pbBuffer.Length,
							m_pbBuffer, 0);

					h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

					pbCmpHmac = h.Hash;
				}
				MemUtil.ZeroByteArray(pbBlockKey);

				if(!MemUtil.ArraysEqual(pbCmpHmac, pbStoredHmac))
					throw new InvalidDataException(KLRes.FileCorrupted);
			}

			++m_uBlockIndex;

			if(nBlockSize == 0)
			{
				m_bEos = true;
				return false; // No further data available
			}
			return true;
		}

		public override void Write(byte[] pbBuffer, int iOffset, int nCount)
		{
			if(!m_bWriting) throw new InvalidOperationException();

			while(nCount > 0)
			{
				if(m_iBufferPos == m_pbBuffer.Length)
					WriteSafeBlock();

				int nCopy = Math.Min(m_pbBuffer.Length - m_iBufferPos, nCount);
				Debug.Assert(nCopy > 0);

				Array.Copy(pbBuffer, iOffset, m_pbBuffer, m_iBufferPos, nCopy);

				iOffset += nCopy;
				m_iBufferPos += nCopy;

				nCount -= nCopy;
			}
		}

		private void WriteSafeBlock()
		{
			byte[] pbBlockIndex = MemUtil.UInt64ToBytes(m_uBlockIndex);

			int cbBlockSize = m_iBufferPos;
			byte[] pbBlockSize = MemUtil.Int32ToBytes(cbBlockSize);

			byte[] pbBlockHmac;
			byte[] pbBlockKey = GetHmacKey64(m_pbKey, m_uBlockIndex);
			using(HMACSHA256 h = new HMACSHA256(pbBlockKey))
			{
				h.TransformBlock(pbBlockIndex, 0, pbBlockIndex.Length,
					pbBlockIndex, 0);
				h.TransformBlock(pbBlockSize, 0, pbBlockSize.Length,
					pbBlockSize, 0);

				if(cbBlockSize > 0)
					h.TransformBlock(m_pbBuffer, 0, cbBlockSize, m_pbBuffer, 0);

				h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

				pbBlockHmac = h.Hash;
			}
			MemUtil.ZeroByteArray(pbBlockKey);

			MemUtil.Write(m_sBase, pbBlockHmac);
			// MemUtil.Write(m_sBase, pbBlockIndex); // Implicit
			MemUtil.Write(m_sBase, pbBlockSize);
			if(cbBlockSize > 0)
				m_sBase.Write(m_pbBuffer, 0, cbBlockSize);

			++m_uBlockIndex;
			m_iBufferPos = 0;
		}
	}
}