File: AppEnforcedConfig.cs

package info (click to toggle)
keepass2 2.60%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,892 kB
  • sloc: cs: 119,878; xml: 6,087; ansic: 2,033; cpp: 738; sh: 50; makefile: 42
file content (288 lines) | stat: -rw-r--r-- 9,065 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
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2025 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.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml;

using KeePass.Resources;
using KeePass.UI;
using KeePass.Util;
using KeePass.Util.XmlSerialization;

using KeePassLib;
using KeePassLib.Cryptography;
using KeePassLib.Native;
using KeePassLib.Utility;

namespace KeePass.App.Configuration
{
	internal sealed class AecItem
	{
		public readonly object Container;
		public readonly string PropertyName;
		public readonly bool Enforce;

		public AecItem(object oContainer, string strPropertyName, bool bEnforce)
		{
			this.Container = oContainer;
			this.PropertyName = strPropertyName;
			this.Enforce = bEnforce;
		}

#if DEBUG
		public override string ToString()
		{
			return string.Format("{0}, {1}, {2}", this.Container, this.PropertyName,
				this.Enforce);
		}
#endif
	}

	internal static class AppEnforcedConfig
	{
		public static bool Modify(List<AecItem> lItems, AppConfigEx cfgValues,
			bool bAllowElevate)
		{
			try
			{
				if(lItems == null) throw new ArgumentNullException("lItems");
				if(cfgValues == null) throw new ArgumentNullException("cfgValues");

				XmlDocument xdEnforced = (AppConfigSerializer.LoadEnforced(false) ??
					AppConfigEx.CreateEmptyXmlDocument());

				XmlDocument xdValues;
				using(MemoryStream msW = new MemoryStream())
				{
					AppConfigSerializer.SaveEx(cfgValues, msW);

					using(MemoryStream msR = new MemoryStream(msW.ToArray(), false))
					{
						xdValues = XmlUtilEx.LoadXmlDocument(msR, StrUtil.Utf8);
					}
				}

				foreach(AecItem it in lItems)
					Modify(xdEnforced, it, xdValues, cfgValues);

				using(MemoryStream msW = new MemoryStream())
				{
					using(XmlWriter xw = XmlUtilEx.CreateXmlWriter(msW))
					{
						xdEnforced.Save(xw);
					}

					if(Save(msW.ToArray(), bAllowElevate))
					{
						// Apply the modifications to the enforced configuration
						// of the current process, too; the enforced configuration
						// file on disk may contain additional settings that are
						// not loaded/enforced yet

						XmlDocument xdProcess = AppConfigSerializer.EnforcedConfigXml;
						if(xdProcess == null)
						{
							xdProcess = AppConfigEx.CreateEmptyXmlDocument();
							AppConfigSerializer.EnforcedConfigXml = xdProcess;
						}

						foreach(AecItem it in lItems)
							Modify(xdProcess, it, xdValues, cfgValues);

						return true;
					}
				}
			}
			catch(Exception ex) { MessageService.ShowWarning(ex); }

			return false;
		}

		private static void Modify(XmlDocument xdEnforced, AecItem it,
			XmlDocument xdValues, AppConfigEx cfgValues)
		{
			object oC = it.Container;
			PropertyInfo pi = oC.GetType().GetProperty(it.PropertyName);
			if((pi == null) || !pi.CanRead) throw new MemberAccessException();

			string strPath = XmlUtil.GetObjectXmlPath(cfgValues, oC);
			if(string.IsNullOrEmpty(strPath)) throw new KeyNotFoundException();
			strPath += "/" + XmlSerializerEx.GetXmlName(pi);

			const string strRoot = "/" + AppConfigEx.StrXmlTypeName + "/";
			if(!strPath.StartsWith(strRoot)) throw new InvalidOperationException();
			string strPathRel = strPath.Substring(strRoot.Length);

			XmlElement xe = XmlUtil.FindOrCreateElement(xdEnforced.DocumentElement,
				strPathRel, xdEnforced);
			if(xe == null) throw new InvalidOperationException();

			if(!it.Enforce)
			{
				xe.RemoveAll(); // Removes attributes and children

				while(xe != xdEnforced.DocumentElement)
				{
					XmlElement xeP = (xe.ParentNode as XmlElement);
					if(xeP == null) { Debug.Assert(false); break; }

					xeP.RemoveChild(xe);

					if(xeP.HasChildNodes || xeP.HasAttributes) break;
					xe = xeP;
				}

				return;
			}

			string strV;
			XmlNode xnV = xdValues.SelectSingleNode(strPath);

			if(xnV != null)
				strV = XmlUtil.SafeInnerXml(xnV);
			else
			{
				Type tV = pi.PropertyType;
				object oV = pi.GetValue(oC, null);
				Debug.Assert((oV == null) || (oV.GetType() == tV));

				// Cf. OptionsEnfForm.AddOption
				if(tV == typeof(bool))
					strV = XmlConvert.ToString((bool)oV);
				else if(tV == typeof(int))
					strV = XmlConvert.ToString((int)oV);
				else if(tV == typeof(uint))
					strV = XmlConvert.ToString((uint)oV);
				else if(tV == typeof(string))
				{
					strV = (oV as string);
					if(strV != string.Empty) throw new NotImplementedException();
				}
				else throw new NotImplementedException();
			}

			Debug.Assert(strV != null);
			if(string.IsNullOrEmpty(strV)) xe.IsEmpty = true;
			else xe.InnerXml = strV;

			// Fix merge attributes to ensure enforcement
			XmContext ctx = new XmContext(xdEnforced, AppConfigEx.GetNodeOptions,
				AppConfigEx.GetNodeKey);
			while(true)
			{
				string strXE = XmlUtil.GetPath(xe);
				XmNodeOptions xno = XmlUtil.GetNodeOptions(xe, strXE, ctx);

				if(xno.NodeMode != XmNodeMode.OpenOrCreate)
				{
					if(xe.HasAttribute(XmNodeOptions.AttribNodeMode))
						xe.RemoveAttribute(XmNodeOptions.AttribNodeMode);
					else { Debug.Assert(false); } // OpenOrCreate is not the default
				}

				if(xe == xdEnforced.DocumentElement) break;
				xe = (xe.ParentNode as XmlElement);
				if(xe == null) { Debug.Assert(false); break; }
			}
		}

		private static bool Save(byte[] pbXml, bool bAllowElevate)
		{
			string strFile = AppConfigSerializer.EnforcedConfigFile;
			if(string.IsNullOrEmpty(strFile)) throw new InvalidOperationException();

			try
			{
				File.WriteAllBytes(strFile, pbXml);
				return true;
			}
			catch(UnauthorizedAccessException) { }
			catch(Exception) { Debug.Assert(false); }

			if(!bAllowElevate) return false;

			string strTempFile = Program.TempFilesPool.GetTempFileName(true);
			File.WriteAllBytes(strTempFile, pbXml);

			string strHash = Convert.ToBase64String(CryptoUtil.HashSha256(pbXml));
			string strArgs = "-" + AppDefs.CommandLineOptions.ConfigEnfSetupFile +
				":\"" + NativeLib.EncodeDataToArgs(strTempFile) + "\" -" +
				AppDefs.CommandLineOptions.ConfigEnfSetupHash +
				":\"" + NativeLib.EncodeDataToArgs(strHash) + "\"";

			bool b = WinUtil.RunElevated(WinUtil.GetExecutable(), strArgs, true,
				(NativeLib.IsUnix() ? 5000 : -1));

			Program.TempFilesPool.Delete(strTempFile);

			if(!b || !File.Exists(strFile)) return false;
			byte[] pbStoredXml = File.ReadAllBytes(strFile);
			return MemUtil.ArraysEqual(pbStoredXml, pbXml);
		}

		internal static bool SetupAsChild()
		{
			string strTempFile = Program.CommandLineArgs[AppDefs.CommandLineOptions.ConfigEnfSetupFile];
			if(string.IsNullOrEmpty(strTempFile)) return false;

			string strContext = string.Empty;
			try
			{
				string strFile = AppConfigSerializer.EnforcedConfigFile;
				if(string.IsNullOrEmpty(strFile)) throw new InvalidOperationException();

				strContext = strTempFile;
				byte[] pbXml = File.ReadAllBytes(strTempFile);

				string strHashCmp = Convert.ToBase64String(CryptoUtil.HashSha256(pbXml));
				string strHashExp = Program.CommandLineArgs[AppDefs.CommandLineOptions.ConfigEnfSetupHash];
				if(strHashCmp != strHashExp) throw new InvalidDataException();

				strContext = strFile;
				File.WriteAllBytes(strFile, pbXml);
			}
			catch(Exception ex) { MessageService.ShowWarning(strContext, ex); }

			return true; // Handled command line option
		}

		internal static bool ConfirmSavingItems(Form fParent)
		{
			if(!Program.Config.Meta.PreferUserConfiguration) return true;

			string str = KPRes.ConfigEnfSaveItemsAbout + MessageService.NewParagraph +
				KPRes.ConfigEnfAdminUac + MessageService.NewParagraph +
				KPRes.ConfigEnfAllUsers + " " + KPRes.ItemsNoSensitiveEsp;

			int r = VistaTaskDialog.ShowMessageBoxEx(str, null, PwDefs.ShortProductName,
				VtdIcon.Shield, fParent, KPRes.Ok, (int)DialogResult.OK,
				KPRes.Cancel, (int)DialogResult.Cancel);
			if(r < 0)
				r = (int)MessageService.Ask(str, null, MessageBoxButtons.OKCancel);

			return (r == (int)DialogResult.OK);
		}
	}
}