File: EntryUtil.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 (575 lines) | stat: -rw-r--r-- 17,442 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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*
  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.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;

using KeePass.Forms;
using KeePass.Resources;
using KeePass.UI;
using KeePass.Util.Spr;

using KeePassLib;
using KeePassLib.Collections;
using KeePassLib.Cryptography;
using KeePassLib.Cryptography.PasswordGenerator;
using KeePassLib.Delegates;
using KeePassLib.Security;
using KeePassLib.Utility;
using KeePassLib.Serialization;

namespace KeePass.Util
{
	/// <summary>
	/// This class contains various static functions for entry operations.
	/// </summary>
	public static class EntryUtil
	{
		/// <summary>
		/// Save all attachments of an array of entries to a directory.
		/// </summary>
		/// <param name="vEntries">Array of entries whose attachments are extracted and saved.</param>
		/// <param name="strBasePath">Directory in which the attachments are stored.</param>
		public static void SaveEntryAttachments(PwEntry[] vEntries, string strBasePath)
		{
			Debug.Assert(vEntries != null); if(vEntries == null) return;
			Debug.Assert(strBasePath != null); if(strBasePath == null) return;

			string strPath = UrlUtil.EnsureTerminatingSeparator(strBasePath, false);
			bool bCancel = false;

			foreach(PwEntry pe in vEntries)
			{
				foreach(KeyValuePair<string, ProtectedBinary> kvp in pe.Binaries)
				{
					string strFile = strPath + kvp.Key;

					if(File.Exists(strFile))
					{
						string strMsg = KPRes.FileExistsAlready + MessageService.NewLine;
						strMsg += strFile + MessageService.NewParagraph;
						strMsg += KPRes.OverwriteExistingFileQuestion;

						DialogResult dr = MessageService.Ask(strMsg, null,
							MessageBoxButtons.YesNoCancel);

						if(dr == DialogResult.Cancel)
						{
							bCancel = true;
							break;
						}
						else if(dr == DialogResult.Yes)
						{
							try { File.Delete(strFile); }
							catch(Exception exDel)
							{
								MessageService.ShowWarning(strFile, exDel);
								continue;
							}
						}
						else continue; // DialogResult.No
					}

					byte[] pbData = kvp.Value.ReadData();
					try { File.WriteAllBytes(strFile, pbData); }
					catch(Exception exWrite)
					{
						MessageService.ShowWarning(strFile, exWrite);
					}
					MemUtil.ZeroByteArray(pbData);
				}
				if(bCancel) break;
			}
		}

		// Old format name (<= 2.14): "KeePassEntriesCF",
		// old format name (<= 2.22): "KeePassEntriesCX"
		public const string ClipFormatEntries = "KeePassEntries";
		private static byte[] AdditionalEntropy = { 0xF8, 0x03, 0xFA, 0x51, 0x87, 0x18, 0x49, 0x5D };

		[Obsolete]
		public static void CopyEntriesToClipboard(PwDatabase pwDatabase, PwEntry[] vEntries)
		{
			CopyEntriesToClipboard(pwDatabase, vEntries, IntPtr.Zero);
		}

		public static void CopyEntriesToClipboard(PwDatabase pwDatabase, PwEntry[] vEntries,
			IntPtr hOwner)
		{
			using(MemoryStream ms = new MemoryStream())
			{
				using(GZipStream gz = new GZipStream(ms, CompressionMode.Compress))
				{
					KdbxFile.WriteEntries(gz, pwDatabase, vEntries);

					byte[] pbFinal;
					if(WinUtil.IsWindows9x) pbFinal = ms.ToArray();
					else pbFinal = ProtectedData.Protect(ms.ToArray(), AdditionalEntropy,
						DataProtectionScope.CurrentUser);

					ClipboardUtil.Copy(pbFinal, ClipFormatEntries, true, true, hOwner);
				}
			}
		}

		public static void PasteEntriesFromClipboard(PwDatabase pwDatabase,
			PwGroup pgStorage)
		{
			try { PasteEntriesFromClipboardPriv(pwDatabase, pgStorage); }
			catch(Exception) { Debug.Assert(false); }
		}

		private static void PasteEntriesFromClipboardPriv(PwDatabase pwDatabase,
			PwGroup pgStorage)
		{
			if(!ClipboardUtil.ContainsData(ClipFormatEntries)) return;

			byte[] pbEnc = ClipboardUtil.GetEncodedData(ClipFormatEntries, IntPtr.Zero);
			if(pbEnc == null) { Debug.Assert(false); return; }

			byte[] pbPlain;
			if(WinUtil.IsWindows9x) pbPlain = pbEnc;
			else pbPlain = ProtectedData.Unprotect(pbEnc, AdditionalEntropy,
				DataProtectionScope.CurrentUser);

			using(MemoryStream ms = new MemoryStream(pbPlain, false))
			{
				using(GZipStream gz = new GZipStream(ms, CompressionMode.Decompress))
				{
					List<PwEntry> vEntries = KdbxFile.ReadEntries(gz, pwDatabase, true);

					// Adjust protection settings and add entries
					foreach(PwEntry pe in vEntries)
					{
						pe.Strings.EnableProtection(PwDefs.TitleField,
							pwDatabase.MemoryProtection.ProtectTitle);
						pe.Strings.EnableProtection(PwDefs.UserNameField,
							pwDatabase.MemoryProtection.ProtectUserName);
						pe.Strings.EnableProtection(PwDefs.PasswordField,
							pwDatabase.MemoryProtection.ProtectPassword);
						pe.Strings.EnableProtection(PwDefs.UrlField,
							pwDatabase.MemoryProtection.ProtectUrl);
						pe.Strings.EnableProtection(PwDefs.NotesField,
							pwDatabase.MemoryProtection.ProtectNotes);

						pe.SetCreatedNow();

						pgStorage.AddEntry(pe, true, true);
					}
				}
			}
		}

		[Obsolete]
		public static string FillPlaceholders(string strText, SprContext ctx)
		{
			return FillPlaceholders(strText, ctx, 0);
		}

		public static string FillPlaceholders(string strText, SprContext ctx,
			uint uRecursionLevel)
		{
			if((ctx == null) || (ctx.Entry == null)) return strText;

			string str = strText;

			if((ctx.Flags & SprCompileFlags.NewPassword) != SprCompileFlags.None)
				str = ReplaceNewPasswordPlaceholder(str, ctx, uRecursionLevel);

			if((ctx.Flags & SprCompileFlags.HmacOtp) != SprCompileFlags.None)
				str = ReplaceHmacOtpPlaceholder(str, ctx);

			if((ctx.Flags & SprCompileFlags.PickChars) != SprCompileFlags.None)
				str = ReplacePickField(str, ctx);

			return str;
		}

		private static string ReplaceNewPasswordPlaceholder(string strText,
			SprContext ctx, uint uRecursionLevel)
		{
			PwEntry pe = ctx.Entry;
			PwDatabase pd = ctx.Database;
			if((pe == null) || (pd == null)) return strText;

			string str = strText;

			const string strNewPwStart = @"{NEWPASSWORD";
			if(str.IndexOf(strNewPwStart, StrUtil.CaseIgnoreCmp) < 0) return str;

			string strGen = null;

			int iStart;
			List<string> lParams;
			while(SprEngine.ParseAndRemovePlhWithParams(ref str, ctx, uRecursionLevel,
				strNewPwStart + ":", out iStart, out lParams, true))
			{
				if(strGen == null)
					strGen = GeneratePassword((((lParams != null) &&
						(lParams.Count > 0)) ? lParams[0] : string.Empty), ctx);

				string strIns = SprEngine.TransformContent(strGen, ctx);
				str = str.Insert(iStart, strIns);
			}

			const string strNewPwPlh = strNewPwStart + @"}";
			if(str.IndexOf(strNewPwPlh, StrUtil.CaseIgnoreCmp) >= 0)
			{
				if(strGen == null) strGen = GeneratePassword(null, ctx);

				string strIns = SprEngine.TransformContent(strGen, ctx);
				str = StrUtil.ReplaceCaseInsensitive(str, strNewPwPlh, strIns);
			}

			if(strGen != null)
			{
				pe.CreateBackup(pd);

				ProtectedString psGen = new ProtectedString(
					pd.MemoryProtection.ProtectPassword, strGen);
				pe.Strings.Set(PwDefs.PasswordField, psGen);

				pe.Touch(true, false);
				pd.Modified = true;
			}
			else { Debug.Assert(false); }

			return str;
		}

		private static string GeneratePassword(string strProfile, SprContext ctx)
		{
			PwProfile prf = Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile;
			if(!string.IsNullOrEmpty(strProfile))
			{
				if(strProfile == @"~")
					prf = PwProfile.DeriveFromPassword(ctx.Entry.Strings.GetSafe(
						PwDefs.PasswordField));
				else
				{
					List<PwProfile> lPrf = PwGeneratorUtil.GetAllProfiles(false);
					foreach(PwProfile p in lPrf)
					{
						if(strProfile.Equals(p.Name, StrUtil.CaseIgnoreCmp))
						{
							prf = p;
							break;
						}
					}
				}
			}

			PwEntry peCtx = ((ctx != null) ? ctx.Entry : null);
			PwDatabase pdCtx = ((ctx != null) ? ctx.Database : null);
			ProtectedString ps = PwGeneratorUtil.GenerateAcceptable(
				prf, null, peCtx, pdCtx);
			return ps.ReadString();
		}

		private static string ReplaceHmacOtpPlaceholder(string strText,
			SprContext ctx)
		{
			PwEntry pe = ctx.Entry;
			PwDatabase pd = ctx.Database;
			if((pe == null) || (pd == null)) return strText;

			string str = strText;

			const string strHmacOtpPlh = @"{HMACOTP}";
			if(str.IndexOf(strHmacOtpPlh, StrUtil.CaseIgnoreCmp) >= 0)
			{
				const string strKeyFieldUtf8 = "HmacOtp-Secret";
				const string strKeyFieldHex = "HmacOtp-Secret-Hex";
				const string strKeyFieldBase32 = "HmacOtp-Secret-Base32";
				const string strKeyFieldBase64 = "HmacOtp-Secret-Base64";
				const string strCounterField = "HmacOtp-Counter";

				byte[] pbSecret = null;
				try
				{
					string strKey = pe.Strings.ReadSafe(strKeyFieldUtf8);
					if(strKey.Length > 0)
						pbSecret = StrUtil.Utf8.GetBytes(strKey);

					if(pbSecret == null)
					{
						strKey = pe.Strings.ReadSafe(strKeyFieldHex);
						if(strKey.Length > 0)
							pbSecret = MemUtil.HexStringToByteArray(strKey);
					}

					if(pbSecret == null)
					{
						strKey = pe.Strings.ReadSafe(strKeyFieldBase32);
						if(strKey.Length > 0)
							pbSecret = MemUtil.ParseBase32(strKey);
					}

					if(pbSecret == null)
					{
						strKey = pe.Strings.ReadSafe(strKeyFieldBase64);
						if(strKey.Length > 0)
							pbSecret = Convert.FromBase64String(strKey);
					}
				}
				catch(Exception) { Debug.Assert(false); }
				if(pbSecret == null) pbSecret = MemUtil.EmptyByteArray;

				string strCounter = pe.Strings.ReadSafe(strCounterField);
				ulong uCounter;
				ulong.TryParse(strCounter, out uCounter);

				string strValue = HmacOtp.Generate(pbSecret, uCounter, 6,
					false, -1);

				pe.Strings.Set(strCounterField, new ProtectedString(false,
					(uCounter + 1).ToString()));

				pe.Touch(true, false);
				pd.Modified = true;

				str = StrUtil.ReplaceCaseInsensitive(str, strHmacOtpPlh, strValue);
			}

			return str;
		}

		private static string ReplacePickField(string strText, SprContext ctx)
		{
			string str = strText;
			PwEntry pe = ((ctx != null) ? ctx.Entry : null);
			PwDatabase pd = ((ctx != null) ? ctx.Database : null);

			while(true)
			{
				const string strPlh = @"{PICKFIELD}";
				int p = str.IndexOf(strPlh, StrUtil.CaseIgnoreCmp);
				if(p < 0) break;

				string strRep = string.Empty;

				List<FpField> l = new List<FpField>();
				string strGroup;

				if(pe != null)
				{
					strGroup = KPRes.Entry + " - " + KPRes.StandardFields;

					Debug.Assert(PwDefs.GetStandardFields().Count == 5);
					l.Add(new FpField(KPRes.Title, pe.Strings.GetSafe(PwDefs.TitleField),
						strGroup));
					l.Add(new FpField(KPRes.UserName, pe.Strings.GetSafe(PwDefs.UserNameField),
						strGroup));
					l.Add(new FpField(KPRes.Password, pe.Strings.GetSafe(PwDefs.PasswordField),
						strGroup));
					l.Add(new FpField(KPRes.Url, pe.Strings.GetSafe(PwDefs.UrlField),
						strGroup));
					l.Add(new FpField(KPRes.Notes, pe.Strings.GetSafe(PwDefs.NotesField),
						strGroup));

					strGroup = KPRes.Entry + " - " + KPRes.CustomFields;
					foreach(KeyValuePair<string, ProtectedString> kvp in pe.Strings)
					{
						if(PwDefs.IsStandardField(kvp.Key)) continue;

						l.Add(new FpField(kvp.Key, kvp.Value, strGroup));
					}

					PwGroup pg = pe.ParentGroup;
					if(pg != null)
					{
						strGroup = KPRes.Group;

						l.Add(new FpField(KPRes.Name, new ProtectedString(
							false, pg.Name), strGroup));

						if(pg.Notes.Length > 0)
							l.Add(new FpField(KPRes.Notes, new ProtectedString(
								false, pg.Notes), strGroup));
					}
				}

				if(pd != null)
				{
					strGroup = KPRes.Database;

					if(pd.Name.Length > 0)
						l.Add(new FpField(KPRes.Name, new ProtectedString(
							false, pd.Name), strGroup));
					l.Add(new FpField(KPRes.FileOrUrl, new ProtectedString(
						false, pd.IOConnectionInfo.Path), strGroup));
				}

				FpField fpf = FieldPickerForm.ShowAndRestore(KPRes.PickField,
					KPRes.PickFieldDesc, l);
				if(fpf != null) strRep = fpf.Value.ReadString();

				strRep = SprEngine.Compile(strRep, ctx.WithoutContentTransformations());
				strRep = SprEngine.TransformContent(strRep, ctx);

				str = str.Remove(p, strPlh.Length);
				str = str.Insert(p, strRep);
			}

			return str;
		}

		public static bool EntriesHaveSameParent(PwObjectList<PwEntry> v)
		{
			if(v == null) { Debug.Assert(false); return true; }
			if(v.UCount == 0) return true;

			PwGroup pg = v.GetAt(0).ParentGroup;
			foreach(PwEntry pe in v)
			{
				if(pe.ParentGroup != pg) return false;
			}

			return true;
		}

		public static void ReorderEntriesAsInDatabase(PwObjectList<PwEntry> v,
			PwDatabase pd)
		{
			if((v == null) || (pd == null)) { Debug.Assert(false); return; }
			if(pd.RootGroup == null) { Debug.Assert(false); return; } // DB must be open

			PwObjectList<PwEntry> vRem = v.CloneShallow();
			v.Clear();

			EntryHandler eh = delegate(PwEntry pe)
			{
				int p = vRem.IndexOf(pe);
				if(p >= 0)
				{
					v.Add(pe);
					vRem.RemoveAt((uint)p);
				}

				return true;
			};

			pd.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, eh);

			foreach(PwEntry peRem in vRem) v.Add(peRem); // Entries not found
		}

		[Obsolete]
		public static void ExpireTanEntry(PwEntry pe)
		{
			ExpireTanEntryIfOption(pe, null);
		}

		[Obsolete]
		public static bool ExpireTanEntryIfOption(PwEntry pe)
		{
			return ExpireTanEntryIfOption(pe, null);
		}

		/// <summary>
		/// Test whether an entry is a TAN entry and if so, expire it, provided
		/// that the option for expiring TANs on use is enabled.
		/// </summary>
		/// <param name="pe">Entry.</param>
		/// <returns>If the entry has been modified, the return value is
		/// <c>true</c>, otherwise <c>false</c>.</returns>
		public static bool ExpireTanEntryIfOption(PwEntry pe, PwDatabase pdContext)
		{
			if(pe == null) throw new ArgumentNullException("pe");
			// pdContext may be null
			if(!PwDefs.IsTanEntry(pe)) return false; // No assert

			if(Program.Config.Defaults.TanExpiresOnUse)
			{
				pe.ExpiryTime = DateTime.UtcNow;
				pe.Expires = true;
				pe.Touch(true);
				if(pdContext != null) pdContext.Modified = true;
				return true;
			}

			return false;
		}

		public static string CreateSummaryList(PwGroup pgItems, bool bStartWithNewPar)
		{
			List<PwEntry> l = pgItems.GetEntries(true).CloneShallowToList();
			string str = CreateSummaryList(pgItems, l.ToArray());

			if((str.Length == 0) || !bStartWithNewPar) return str;
			return (MessageService.NewParagraph + str);
		}

		public static string CreateSummaryList(PwGroup pgSubGroups, PwEntry[] vEntries)
		{
			int nMaxEntries = 10;
			string strSummary = string.Empty;

			if(pgSubGroups != null)
			{
				PwObjectList<PwGroup> vGroups = pgSubGroups.GetGroups(true);
				if(vGroups.UCount > 0)
				{
					StringBuilder sbGroups = new StringBuilder();
					sbGroups.Append("- ");
					uint uToList = Math.Min(3U, vGroups.UCount);
					for(uint u = 0; u < uToList; ++u)
					{
						if(sbGroups.Length > 2) sbGroups.Append(", ");
						sbGroups.Append(vGroups.GetAt(u).Name);
					}
					if(uToList < vGroups.UCount) sbGroups.Append(", ...");
					strSummary += sbGroups.ToString(); // New line below

					nMaxEntries -= 2;
				}
			}

			int nSummaryShow = Math.Min(nMaxEntries, vEntries.Length);
			if(nSummaryShow == (vEntries.Length - 1)) --nSummaryShow; // Plural msg

			for(int iSumEnum = 0; iSumEnum < nSummaryShow; ++iSumEnum)
			{
				if(strSummary.Length > 0) strSummary += MessageService.NewLine;

				PwEntry pe = vEntries[iSumEnum];
				strSummary += ("- " + StrUtil.CompactString3Dots(
					pe.Strings.ReadSafe(PwDefs.TitleField), 39));
				if(PwDefs.IsTanEntry(pe))
				{
					string strTanIdx = pe.Strings.ReadSafe(PwDefs.UserNameField);
					if(!string.IsNullOrEmpty(strTanIdx))
						strSummary += (@" (#" + strTanIdx + @")");
				}
			}
			if(nSummaryShow != vEntries.Length)
				strSummary += (MessageService.NewLine + "- " +
					KPRes.MoreEntries.Replace(@"{PARAM}", (vEntries.Length -
					nSummaryShow).ToString()));

			return strSummary;
		}
	}
}