File: DPAPIProtectedConfigurationProvider.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (268 lines) | stat: -rw-r--r-- 11,860 bytes parent folder | download | duplicates (7)
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
//------------------------------------------------------------------------------
// <copyright file="DpapiProtectedConfigurationProvider.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Configuration
{
    using System.Collections.Specialized;
    using System.Runtime.Serialization;
    using System.Configuration.Provider;
    using System.Xml;
    using System.Text;
    using  System.Runtime.InteropServices;
    using Microsoft.Win32;
    using System.Security.Permissions;
    using Microsoft.Win32.SafeHandles;
    using System.Runtime.CompilerServices;

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public sealed class DpapiProtectedConfigurationProvider : ProtectedConfigurationProvider
    {
        public override XmlNode Decrypt(XmlNode encryptedNode)
        {
            if (encryptedNode.NodeType != XmlNodeType.Element ||
                encryptedNode.Name != "EncryptedData") {
                throw new ConfigurationErrorsException(SR.GetString(SR.DPAPI_bad_data));
            }

            XmlNode cipherNode = TraverseToChild(encryptedNode, "CipherData", false);
            if (cipherNode == null)
                throw new ConfigurationErrorsException(SR.GetString(SR.DPAPI_bad_data));

            XmlNode cipherValue = TraverseToChild(cipherNode, "CipherValue", true);
            if (cipherValue == null)
                throw new ConfigurationErrorsException(SR.GetString(SR.DPAPI_bad_data));

            string encText = cipherValue.InnerText;
            if (encText == null)
                throw new ConfigurationErrorsException(SR.GetString(SR.DPAPI_bad_data));

            string decText = DecryptText(encText);
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.PreserveWhitespace = true;
            xmlDocument.LoadXml(decText);
            return xmlDocument.DocumentElement;
        }

        public override XmlNode Encrypt(XmlNode node)
        {
            string text = node.OuterXml;
            string encText = EncryptText(text);
            string pre = @"<EncryptedData><CipherData><CipherValue>";
            string post = @"</CipherValue></CipherData></EncryptedData>";
            string xmlText = pre + encText + post;

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.PreserveWhitespace = true;
            xmlDocument.LoadXml(xmlText);
            return xmlDocument.DocumentElement;
        }


        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        private string EncryptText(string clearText)
        {
            if (clearText == null || clearText.Length < 1)
                return clearText;

            DATA_BLOB inputData, entData, outputData;
            SafeNativeMemoryHandle safeInputDataHandle = new SafeNativeMemoryHandle();
            SafeNativeMemoryHandle safeOutputDataHandle = new SafeNativeMemoryHandle(true);
            SafeNativeMemoryHandle safeEntDataHandle = new SafeNativeMemoryHandle();

            inputData.pbData = entData.pbData = outputData.pbData = IntPtr.Zero;
            inputData.cbData = entData.cbData = outputData.cbData = 0;
            try {

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                }
                finally {
                    inputData = PrepareDataBlob(clearText);
                    safeInputDataHandle.SetDataHandle(inputData.pbData);

                    entData = PrepareDataBlob(_KeyEntropy);
                    safeEntDataHandle.SetDataHandle(entData.pbData);
                }

                CRYPTPROTECT_PROMPTSTRUCT   prompt      = PreparePromptStructure();
                UInt32                      dwFlags     = CRYPTPROTECT_UI_FORBIDDEN;
                if (UseMachineProtection)
                    dwFlags |= CRYPTPROTECT_LOCAL_MACHINE;
                bool success = false;

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                }
                finally {
                    success = UnsafeNativeMethods.CryptProtectData(ref inputData, "", ref entData,
                                                                    IntPtr.Zero, ref prompt,
                                                                    dwFlags, ref outputData);
                    safeOutputDataHandle.SetDataHandle(outputData.pbData);
                }
                if (!success || outputData.pbData == IntPtr.Zero) {
                    outputData.pbData = IntPtr.Zero;
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                byte[] buf = new byte[outputData.cbData];
                Marshal.Copy(outputData.pbData, buf, 0, buf.Length);
                return Convert.ToBase64String(buf);
            } finally {
                if (!(safeOutputDataHandle == null || safeOutputDataHandle.IsInvalid)) {
                    safeOutputDataHandle.Dispose();
                    outputData.pbData = IntPtr.Zero;
                }
                if (!(safeEntDataHandle == null || safeEntDataHandle.IsInvalid)) {
                    safeEntDataHandle.Dispose();
                    entData.pbData = IntPtr.Zero;
                }
                if (!(safeInputDataHandle == null || safeInputDataHandle.IsInvalid)) {
                    safeInputDataHandle.Dispose();
                    inputData.pbData = IntPtr.Zero;
                }
            }
        }

        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        private string DecryptText(string encText)
        {
            if (encText == null || encText.Length < 1)
                return encText;

            DATA_BLOB inputData, entData, outputData;
            SafeNativeMemoryHandle safeInputDataHandle = new SafeNativeMemoryHandle();
            SafeNativeMemoryHandle safeOutputDataHandle = new SafeNativeMemoryHandle(true);
            SafeNativeMemoryHandle safeEntDataHandle = new SafeNativeMemoryHandle();

            inputData.pbData = entData.pbData = outputData.pbData = IntPtr.Zero;
            inputData.cbData = entData.cbData = outputData.cbData = 0;

            try {
                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                }
                finally {
                    inputData = PrepareDataBlob(Convert.FromBase64String(encText));
                    safeInputDataHandle.SetDataHandle(inputData.pbData);

                    entData = PrepareDataBlob(_KeyEntropy);
                    safeEntDataHandle.SetDataHandle(entData.pbData);
                }

                CRYPTPROTECT_PROMPTSTRUCT   prompt      = PreparePromptStructure();
                UInt32                      dwFlags     = CRYPTPROTECT_UI_FORBIDDEN;

                if (UseMachineProtection)
                    dwFlags |= CRYPTPROTECT_LOCAL_MACHINE;
                bool success = false;
                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                }
                finally {
                    success = UnsafeNativeMethods.CryptUnprotectData(ref inputData, IntPtr.Zero,
                                                                      ref entData, IntPtr.Zero,
                                                                      ref prompt, dwFlags, ref outputData);
                    safeOutputDataHandle.SetDataHandle(outputData.pbData);
                }

                if (!success || outputData.pbData == IntPtr.Zero) {
                    outputData.pbData = IntPtr.Zero;
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                byte[] buf = new byte[outputData.cbData];
                Marshal.Copy(outputData.pbData, buf, 0, buf.Length);
                return Encoding.Unicode.GetString(buf);
            } finally {
                if (!(safeOutputDataHandle == null || safeOutputDataHandle.IsInvalid)) {
                    safeOutputDataHandle.Dispose();
                    outputData.pbData = IntPtr.Zero;
                }
                if (!(safeEntDataHandle == null || safeEntDataHandle.IsInvalid)) {
                    safeEntDataHandle.Dispose();
                    entData.pbData = IntPtr.Zero;
                }
                if (!(safeInputDataHandle == null || safeInputDataHandle.IsInvalid)) {
                    safeInputDataHandle.Dispose();
                    inputData.pbData = IntPtr.Zero;
                }
            }
        }

        public bool     UseMachineProtection   { get { return _UseMachineProtection; }}
        //private virtual string   KeyEntropy    { get { return _KeyEntropy; } }

        public override void Initialize(string name, NameValueCollection configurationValues)
        {
            base.Initialize(name, configurationValues);
            _UseMachineProtection = GetBooleanValue(configurationValues, "useMachineProtection", true);
            _KeyEntropy = configurationValues["keyEntropy"];
            configurationValues.Remove("keyEntropy");
            if (configurationValues.Count > 0)
                throw new ConfigurationErrorsException(SR.GetString(SR.Unrecognized_initialization_value, configurationValues.GetKey(0)));
        }

        private const int CRYPTPROTECT_UI_FORBIDDEN = 0x1;
        private const int CRYPTPROTECT_LOCAL_MACHINE = 0x4;
        private bool   _UseMachineProtection = true;
        private string  _KeyEntropy;

        private static XmlNode TraverseToChild(XmlNode node, string name, bool onlyChild)
        {
            foreach (XmlNode child in node.ChildNodes)
            {
                if (child.NodeType != XmlNodeType.Element)
                    continue;

                if (child.Name == name)
                    return child; // found it!

                if (onlyChild)
                    return null;
            }

            return null;
        }

        private static DATA_BLOB PrepareDataBlob(byte[] buf)
        {
            if (buf == null)
                buf = new byte[0];
            DATA_BLOB db = new DATA_BLOB();
            db.cbData = buf.Length;
            db.pbData = Marshal.AllocHGlobal(db.cbData);
            Marshal.Copy(buf, 0, db.pbData, db.cbData);
            return db;
        }
        private static DATA_BLOB PrepareDataBlob(string s)
        {
            return PrepareDataBlob((s != null) ? Encoding.Unicode.GetBytes(s) : new byte[0]);
        }
        private static CRYPTPROTECT_PROMPTSTRUCT PreparePromptStructure()
        {
            CRYPTPROTECT_PROMPTSTRUCT cps = new CRYPTPROTECT_PROMPTSTRUCT();
            cps.cbSize = Marshal.SizeOf(typeof(CRYPTPROTECT_PROMPTSTRUCT));
            cps.dwPromptFlags = 0;
            cps.hwndApp = IntPtr.Zero;
            cps.szPrompt = null;
            return cps;
        }
        private static bool GetBooleanValue(NameValueCollection configurationValues, string valueName, bool defaultValue) {
            string s = configurationValues[valueName];
            if (s == null)
                return defaultValue;
            configurationValues.Remove(valueName);
            if (s == "true")
                return true;
            if (s == "false")
                return false;
            throw new ConfigurationErrorsException(SR.GetString(SR.Config_invalid_boolean_attribute, valueName));
        }
    }

}