File: KcpKeyFile.Xml.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 (281 lines) | stat: -rw-r--r-- 7,141 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
/*
  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.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using KeePassLib.Cryptography;
using KeePassLib.Resources;
using KeePassLib.Serialization;
using KeePassLib.Utility;

namespace KeePassLib.Keys
{
	[XmlType("KeyFile")]
	public sealed class KfxFile
	{
		private const ulong KfxVersionCriticalMask = 0xFFFF000000000000UL;
		private const int KfxDataHashLength = 4;

		private KfxMeta m_meta = new KfxMeta();
		public KfxMeta Meta
		{
			get { return m_meta; }
			set
			{
				if(value == null) throw new ArgumentNullException("value");
				m_meta = value;
			}
		}

		private KfxKey m_key = new KfxKey();
		public KfxKey Key
		{
			get { return m_key; }
			set
			{
				if(value == null) throw new ArgumentNullException("value");
				m_key = value;
			}
		}

		public static KfxFile Create(ulong uVersion, byte[] pbKey, byte[] pbHash)
		{
			if(pbKey == null) throw new ArgumentNullException("pbKey");
			if(pbKey.Length == 0) throw new ArgumentOutOfRangeException("pbKey");

			if(uVersion == 0) uVersion = 0x0002000000000000;

			// Null hash: generate one, empty hash: store no hash
			if(pbHash == null) pbHash = HashData(pbKey);
			VerifyHash(pbKey, pbHash);

			KfxFile kf = new KfxFile();

			if(uVersion == 0x0001000000000000)
				kf.Meta.Version = "1.00"; // KeePass <= 2.46 used two zeros
			else kf.Meta.Version = StrUtil.VersionToString(uVersion, 2);

			if(uVersion == 0x0001000000000000)
				kf.Key.Data.Value = Convert.ToBase64String(pbKey);
			else if(uVersion == 0x0002000000000000)
			{
				kf.Key.Data.Value = FormatKeyHex(pbKey, 3);

				if(pbHash.Length != 0)
					kf.Key.Data.Hash = MemUtil.ByteArrayToHexString(pbHash);
			}
			else throw new NotSupportedException(KLRes.FileVersionUnsupported);

			return kf;
		}

		internal static KfxFile Create(ulong uVersion, string strKey, string strHash)
		{
			byte[] pbKey = ParseKey(uVersion, strKey);
			byte[] pbHash = ((strHash != null) ? ParseHash(strHash) : null);

			return Create(uVersion, pbKey, pbHash);
		}

		internal static bool CanLoad(string strFilePath)
		{
			if(string.IsNullOrEmpty(strFilePath)) { Debug.Assert(false); return false; }

			try
			{
				IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFilePath);
				using(Stream s = IOConnection.OpenRead(ioc))
				{
					return (Load(s) != null);
				}
			}
			catch(Exception) { }

			return false;
		}

		public static KfxFile Load(Stream s)
		{
			return XmlUtilEx.Deserialize<KfxFile>(s);
		}

		public void Save(Stream s)
		{
			XmlUtilEx.Serialize<KfxFile>(s, this, true);
		}

		private static string FormatKeyHex(byte[] pb, int cTabs)
		{
			StringBuilder sb = new StringBuilder();
			string str = MemUtil.ByteArrayToHexString(pb);

			for(int i = 0; i < str.Length; ++i)
			{
				if((i & 0x1F) == 0)
				{
					sb.AppendLine();
					sb.Append('\t', cTabs);
				}
				else if((i & 0x07) == 0) sb.Append(' ');

				sb.Append(str[i]);
			}

			sb.AppendLine();
			if(cTabs > 0) sb.Append('\t', cTabs - 1);
			return sb.ToString();
		}

		private ulong GetVersion()
		{
			string str = m_meta.Version;
			if(string.IsNullOrEmpty(str)) return 0;

			return StrUtil.ParseVersion(str);
		}

		public byte[] GetKey()
		{
			ulong uVersion = GetVersion();

			byte[] pbKey = ParseKey(uVersion, m_key.Data.Value);
			if((pbKey == null) || (pbKey.Length == 0))
				throw new FormatException(KLRes.FileCorrupted);

			byte[] pbHash = ParseHash(m_key.Data.Hash);
			VerifyHash(pbKey, pbHash);

			return pbKey;
		}

		private static byte[] HashData(byte[] pb)
		{
			return MemUtil.Mid(CryptoUtil.HashSha256(pb), 0, KfxDataHashLength);
		}

		private static void VerifyHash(byte[] pbKey, byte[] pbHash)
		{
			// The hash is optional; empty hash means success
			if((pbHash == null) || (pbHash.Length == 0)) return;

			byte[] pbHashCmp = HashData(pbKey);
			if(!MemUtil.ArraysEqual(pbHash, pbHashCmp))
				throw new InvalidDataException(KLRes.KeyHashMismatch);
		}

		private static byte[] ParseKey(ulong uVersion, string strKey)
		{
			if(strKey == null) throw new ArgumentNullException("strKey");

			strKey = StrUtil.RemoveWhiteSpace(strKey);
			if(string.IsNullOrEmpty(strKey)) return MemUtil.EmptyByteArray;

			uVersion &= KfxVersionCriticalMask;

			byte[] pbKey;
			if(uVersion == 0x0001000000000000)
				pbKey = Convert.FromBase64String(strKey);
			else if(uVersion == 0x0002000000000000)
				pbKey = ParseHex(strKey);
			else throw new NotSupportedException(KLRes.FileVersionUnsupported);

			return pbKey;
		}

		private static byte[] ParseHash(string strHash)
		{
			return ParseHex(strHash);
		}

		private static byte[] ParseHex(string str)
		{
			if(str == null) throw new ArgumentNullException("str");
			if(str.Length == 0) return MemUtil.EmptyByteArray;

			if(((str.Length & 1) != 0) || !StrUtil.IsHexString(str, true))
				throw new FormatException();

			return MemUtil.HexStringToByteArray(str);
		}
	}

	public sealed class KfxMeta
	{
		private string m_strVersion = string.Empty;
		[DefaultValue("")]
		public string Version
		{
			get { return m_strVersion; }
			set
			{
				if(value == null) throw new ArgumentNullException("value");
				m_strVersion = value;
			}
		}
	}

	public sealed class KfxKey
	{
		private KfxData m_data = new KfxData();
		public KfxData Data
		{
			get { return m_data; }
			set
			{
				if(value == null) throw new ArgumentNullException("value");
				m_data = value;
			}
		}
	}

	public sealed class KfxData
	{
		private string m_strHash = string.Empty;
		[DefaultValue("")]
		[XmlAttribute("Hash")]
		public string Hash
		{
			get { return m_strHash; }
			set
			{
				if(value == null) throw new ArgumentNullException("value");
				m_strHash = value;
			}
		}

		private string m_strValue = string.Empty;
		[DefaultValue("")]
		[XmlText]
		public string Value
		{
			get { return m_strValue; }
			set
			{
				if(value == null) throw new ArgumentNullException("value");
				m_strValue = value;
			}
		}
	}
}