forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSSPIHandler.cs
More file actions
334 lines (302 loc) · 11.3 KB
/
SSPIHandler.cs
File metadata and controls
334 lines (302 loc) · 11.3 KB
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
#if NET45 || NET452 || DNX452
#region License
// The PostgreSQL License
//
// Copyright (C) 2015 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace Npgsql
{
/// <summary>
/// A class to handle everything associated with SSPI authentication
/// </summary>
internal class SSPIHandler : IDisposable
{
#region constants and structs
private const int SECBUFFER_VERSION = 0;
private const int SECBUFFER_TOKEN = 2;
private const int SEC_E_OK = 0x00000000;
private const int SEC_I_CONTINUE_NEEDED = 0x00090312;
private const int ISC_REQ_ALLOCATE_MEMORY=0x00000100;
private const int SECURITY_NETWORK_DREP=0x00000000;
private const int SECPKG_CRED_OUTBOUND=0x00000002;
[StructLayout(LayoutKind.Sequential)]
private struct SecHandle
{
public IntPtr dwLower;
public IntPtr dwUpper;
}
[StructLayout(LayoutKind.Sequential)]
private struct SecBuffer
{
public int cbBuffer;
public int BufferType;
public IntPtr pvBuffer;
}
/// <summary>
/// Simplified SecBufferDesc struct with only one SecBuffer
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct SecBufferDesc
{
public int ulVersion;
public int cBuffers;
public IntPtr pBuffer;
}
#endregion
#region p/invoke methods
[DllImport("Secur32.dll")]
private extern static int AcquireCredentialsHandle(
string pszPrincipal,
string pszPackage,
int fCredentialUse,
IntPtr pvLogonID,
IntPtr pAuthData,
IntPtr pGetKeyFn,
IntPtr pvGetKeyArgument,
ref SecHandle phCredential,
out SecHandle ptsExpiry
);
[DllImport("secur32", CharSet=CharSet.Auto, SetLastError=true)]
static extern int InitializeSecurityContext(
ref SecHandle phCredential,
ref SecHandle phContext,
string pszTargetName,
int fContextReq,
int Reserved1,
int TargetDataRep,
ref SecBufferDesc pInput,
int Reserved2,
out SecHandle phNewContext,
out SecBufferDesc pOutput,
out int pfContextAttr,
out SecHandle ptsExpiry);
[DllImport("secur32", CharSet=CharSet.Auto, SetLastError=true)]
static extern int InitializeSecurityContext(
ref SecHandle phCredential,
IntPtr phContext,
string pszTargetName,
int fContextReq,
int Reserved1,
int TargetDataRep,
IntPtr pInput,
int Reserved2,
out SecHandle phNewContext,
out SecBufferDesc pOutput,
out int pfContextAttr,
out SecHandle ptsExpiry);
[DllImport("Secur32.dll")]
private extern static int FreeContextBuffer(
IntPtr pvContextBuffer
);
[DllImport("Secur32.dll")]
private extern static int FreeCredentialsHandle(
ref SecHandle phCredential
);
[DllImport("Secur32.dll")]
private extern static int DeleteSecurityContext(
ref SecHandle phContext
);
#endregion
private bool disposed;
private string sspitarget;
private SecHandle sspicred;
private SecHandle sspictx;
private bool sspictx_set;
public SSPIHandler(string pghost, string krbsrvname, bool useGssapi)
{
if (pghost == null)
throw new ArgumentNullException(nameof(pghost));
if (krbsrvname == null)
krbsrvname = String.Empty;
sspitarget = $"{krbsrvname}/{pghost}";
SecHandle expire;
int status = AcquireCredentialsHandle(
"",
useGssapi ? "kerberos" : "negotiate",
SECPKG_CRED_OUTBOUND,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
ref sspicred,
out expire
);
if (status != SEC_E_OK)
{
// This will automaticcaly fill in the message of the last Win32 error
throw new Win32Exception();
}
}
public byte[] Continue(byte[] authData)
{
if (authData == null && sspictx_set)
throw new InvalidOperationException("The authData parameter con only be null at the first call to continue!");
int status;
SecBuffer OutBuffer;
SecBuffer InBuffer;
SecBufferDesc inbuf;
SecBufferDesc outbuf;
SecHandle newContext;
SecHandle expire;
int contextAttr;
OutBuffer.pvBuffer = IntPtr.Zero;
OutBuffer.BufferType = SECBUFFER_TOKEN;
OutBuffer.cbBuffer = 0;
outbuf.cBuffers = 1;
outbuf.ulVersion = SECBUFFER_VERSION;
outbuf.pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(OutBuffer));
try
{
Marshal.StructureToPtr(OutBuffer, outbuf.pBuffer, false);
if (sspictx_set)
{
inbuf.pBuffer = IntPtr.Zero;
InBuffer.pvBuffer = Marshal.AllocHGlobal(authData.Length);
try
{
Marshal.Copy(authData, 0, InBuffer.pvBuffer, authData.Length);
InBuffer.cbBuffer = authData.Length;
InBuffer.BufferType = SECBUFFER_TOKEN;
inbuf.ulVersion = SECBUFFER_VERSION;
inbuf.cBuffers = 1;
inbuf.pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(InBuffer));
Marshal.StructureToPtr(InBuffer, inbuf.pBuffer, false);
status = InitializeSecurityContext(
ref sspicred,
ref sspictx,
sspitarget,
ISC_REQ_ALLOCATE_MEMORY,
0,
SECURITY_NETWORK_DREP,
ref inbuf,
0,
out newContext,
out outbuf,
out contextAttr,
out expire
);
}
finally
{
if (InBuffer.pvBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(InBuffer.pvBuffer);
if (inbuf.pBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(inbuf.pBuffer);
}
}
else
{
status = InitializeSecurityContext(
ref sspicred,
IntPtr.Zero,
sspitarget,
ISC_REQ_ALLOCATE_MEMORY,
0,
SECURITY_NETWORK_DREP,
IntPtr.Zero,
0,
out newContext,
out outbuf,
out contextAttr,
out expire
);
}
if (status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED)
{
// This will automaticcaly fill in the message of the last Win32 error
throw new Win32Exception();
}
if (!sspictx_set)
{
sspictx.dwUpper = newContext.dwUpper;
sspictx.dwLower = newContext.dwLower;
sspictx_set = true;
}
if (outbuf.cBuffers > 0)
{
if (outbuf.cBuffers != 1)
{
throw new InvalidOperationException("SSPI returned invalid number of output buffers");
}
// attention: OutBuffer is still our initially created struct but outbuf.pBuffer doesn't point to
// it but to the copy of it we created on the unmanaged heap and passed to InitializeSecurityContext()
// we have to marshal it back to see the content change
OutBuffer = (SecBuffer)Marshal.PtrToStructure(outbuf.pBuffer, typeof(SecBuffer));
if (OutBuffer.cbBuffer > 0)
{
// we need the buffer with a terminating 0 so we
// make it one byte bigger
byte[] buffer = new byte[OutBuffer.cbBuffer];
Marshal.Copy(OutBuffer.pvBuffer, buffer, 0, buffer.Length);
// The SSPI authentication data must be sent as password message
return buffer;
//stream.WriteByte((byte)'p');
//PGUtil.WriteInt32(stream, buffer.Length + 5);
//stream.Write(buffer, 0, buffer.Length);
//stream.Flush();
}
}
return new byte[0];
}
finally
{
if (OutBuffer.pvBuffer != IntPtr.Zero)
FreeContextBuffer(OutBuffer.pvBuffer);
if (outbuf.pBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(outbuf.pBuffer);
}
}
#region resource cleanup
private void FreeHandles()
{
if (sspictx_set)
{
FreeCredentialsHandle(ref sspicred);
DeleteSecurityContext(ref sspictx);
}
}
~SSPIHandler()
{
FreeHandles();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
FreeHandles();
}
disposed = true;
}
}
#endregion
}
}
#endif