| 1 |
[CmdletBinding()] |
| 2 |
param ( |
| 3 |
[int] |
| 4 |
$Port = 16854 |
| 5 |
) |
| 6 |
|
| 7 |
$ErrorActionPreference = 'Stop' |
| 8 |
|
| 9 |
Add-Type -TypeDefinition @' |
| 10 |
using Microsoft.Win32.SafeHandles; |
| 11 |
using System; |
| 12 |
using System.Collections.Generic; |
| 13 |
using System.Diagnostics; |
| 14 |
using System.Linq; |
| 15 |
using System.Runtime.ConstrainedExecution; |
| 16 |
using System.Runtime.InteropServices; |
| 17 |
using System.Security.Principal; |
| 18 |
|
| 19 |
namespace Pyspnego |
| 20 |
{ |
| 21 |
internal class NativeHelpers |
| 22 |
{ |
| 23 |
[StructLayout(LayoutKind.Sequential)] |
| 24 |
public struct LUID |
| 25 |
{ |
| 26 |
public UInt32 LowPart; |
| 27 |
public Int32 HighPart; |
| 28 |
|
| 29 |
public static explicit operator UInt64(LUID l) |
| 30 |
{ |
| 31 |
return (UInt64)((UInt64)l.HighPart << 32) | (UInt64)l.LowPart; |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
[StructLayout(LayoutKind.Sequential)] |
| 36 |
public struct LUID_AND_ATTRIBUTES |
| 37 |
{ |
| 38 |
public LUID Luid; |
| 39 |
public PrivilegeAttributes Attributes; |
| 40 |
} |
| 41 |
|
| 42 |
[StructLayout(LayoutKind.Sequential)] |
| 43 |
public struct SID_AND_ATTRIBUTES |
| 44 |
{ |
| 45 |
public IntPtr Sid; |
| 46 |
public int Attributes; |
| 47 |
} |
| 48 |
|
| 49 |
[StructLayout(LayoutKind.Sequential)] |
| 50 |
public class SecBufferDesc : IDisposable |
| 51 |
{ |
| 52 |
public UInt32 ulVersion; |
| 53 |
public UInt32 cBuffers; |
| 54 |
public IntPtr pBuffers { |
| 55 |
get { return this._buffer.DangerousGetHandle(); } |
| 56 |
} |
| 57 |
|
| 58 |
private SafeMemoryBuffer _buffer; |
| 59 |
|
| 60 |
public SecBufferDesc(List<SecurityBuffer> buffers) |
| 61 |
{ |
| 62 |
cBuffers = (UInt32)buffers.Count; |
| 63 |
_buffer = new SafeMemoryBuffer(IntPtr.Zero); |
| 64 |
|
| 65 |
if (cBuffers > 0) |
| 66 |
{ |
| 67 |
int bufferLength = Marshal.SizeOf(typeof(SecBuffer)); |
| 68 |
int bufferDataOffset = bufferLength * buffers.Count; |
| 69 |
int bufferDataLength = buffers.Sum(i => i.Data == null ? 0 : i.Data.Length); |
| 70 |
|
| 71 |
_buffer = new SafeMemoryBuffer(bufferDataOffset + bufferDataLength); |
| 72 |
IntPtr inputBufferPtr = _buffer.DangerousGetHandle(); |
| 73 |
IntPtr inputBufferDataPtr = IntPtr.Add(inputBufferPtr, bufferDataOffset); |
| 74 |
|
| 75 |
foreach (SecurityBuffer buffer in buffers) |
| 76 |
{ |
| 77 |
SecBuffer bufferElement = new SecBuffer() |
| 78 |
{ |
| 79 |
BufferType = buffer.BufferType, |
| 80 |
}; |
| 81 |
|
| 82 |
if (buffer.Data == null) |
| 83 |
{ |
| 84 |
bufferElement.cbBuffer = 0; |
| 85 |
bufferElement.pvBuffer = IntPtr.Zero; |
| 86 |
} |
| 87 |
else |
| 88 |
{ |
| 89 |
bufferElement.cbBuffer = buffer.Data.Length; |
| 90 |
bufferElement.pvBuffer = inputBufferDataPtr; |
| 91 |
Marshal.Copy(buffer.Data, 0, inputBufferDataPtr, buffer.Data.Length); |
| 92 |
inputBufferDataPtr = IntPtr.Add(inputBufferDataPtr, buffer.Data.Length); |
| 93 |
} |
| 94 |
|
| 95 |
Marshal.StructureToPtr(bufferElement, inputBufferPtr, false); |
| 96 |
inputBufferPtr = IntPtr.Add(inputBufferPtr, bufferLength); |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
public static explicit operator List<SecurityBuffer>(SecBufferDesc b) |
| 102 |
{ |
| 103 |
List<SecurityBuffer> buffers = new List<SecurityBuffer>(); |
| 104 |
if (b.cBuffers == 0) |
| 105 |
return buffers; |
| 106 |
|
| 107 |
for (int i = 0; i < b.cBuffers; i++) |
| 108 |
{ |
| 109 |
SecBuffer entry = (SecBuffer)Marshal.PtrToStructure( |
| 110 |
IntPtr.Add(b.pBuffers, i * Marshal.SizeOf(typeof(SecBuffer))), typeof(SecBuffer)); |
| 111 |
|
| 112 |
byte[] entryData = new byte[entry.cbBuffer]; |
| 113 |
Marshal.Copy(entry.pvBuffer, entryData, 0, entry.cbBuffer); |
| 114 |
|
| 115 |
buffers.Add(new SecurityBuffer() |
| 116 |
{ |
| 117 |
BufferType = entry.BufferType, |
| 118 |
Data = entryData, |
| 119 |
}); |
| 120 |
} |
| 121 |
|
| 122 |
return buffers; |
| 123 |
} |
| 124 |
|
| 125 |
public void Dispose() |
| 126 |
{ |
| 127 |
_buffer.Dispose(); |
| 128 |
GC.SuppressFinalize(this); |
| 129 |
} |
| 130 |
~SecBufferDesc() { this.Dispose(); } |
| 131 |
} |
| 132 |
|
| 133 |
[StructLayout(LayoutKind.Sequential)] |
| 134 |
public struct SecBuffer |
| 135 |
{ |
| 136 |
public Int32 cbBuffer; |
| 137 |
public BufferType BufferType; |
| 138 |
public IntPtr pvBuffer; |
| 139 |
} |
| 140 |
|
| 141 |
[StructLayout(LayoutKind.Sequential)] |
| 142 |
public struct SecHandle |
| 143 |
{ |
| 144 |
public UIntPtr dwLower; |
| 145 |
public UIntPtr dwUpper; |
| 146 |
} |
| 147 |
|
| 148 |
[StructLayout(LayoutKind.Sequential)] |
| 149 |
public struct SecPkgContext_SessionKey |
| 150 |
{ |
| 151 |
public UInt32 SessionKeyLength; |
| 152 |
public IntPtr SessionKey; |
| 153 |
} |
| 154 |
|
| 155 |
[StructLayout(LayoutKind.Sequential)] |
| 156 |
public struct SecPkgContextSizes |
| 157 |
{ |
| 158 |
public Int32 cbMaxToken; |
| 159 |
public Int32 cbMaxSignature; |
| 160 |
public Int32 cbBlockSize; |
| 161 |
public Int32 cbSecurityTrailer; |
| 162 |
} |
| 163 |
|
| 164 |
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] |
| 165 |
public struct SecPkgInfoW |
| 166 |
{ |
| 167 |
public Int32 fCapabilities; |
| 168 |
public Int16 wVersion; |
| 169 |
public Int16 wRPCID; |
| 170 |
public Int32 cbMaxToken; |
| 171 |
[MarshalAs(UnmanagedType.LPWStr)] public string Name; |
| 172 |
[MarshalAs(UnmanagedType.LPWStr)] public string Comment; |
| 173 |
} |
| 174 |
|
| 175 |
[StructLayout(LayoutKind.Sequential)] |
| 176 |
public struct TOKEN_PRIVILEGES |
| 177 |
{ |
| 178 |
public UInt32 PrivilegeCount; |
| 179 |
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] |
| 180 |
public LUID_AND_ATTRIBUTES[] Privileges; |
| 181 |
} |
| 182 |
|
| 183 |
[StructLayout(LayoutKind.Sequential)] |
| 184 |
public struct TOKEN_USER |
| 185 |
{ |
| 186 |
public SID_AND_ATTRIBUTES User; |
| 187 |
} |
| 188 |
|
| 189 |
public enum TokenInformationClass : uint |
| 190 |
{ |
| 191 |
TokenUser = 1, |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
internal class NativeMethods |
| 196 |
{ |
| 197 |
[DllImport("Secur32.dll")] |
| 198 |
public static extern Int32 AcceptSecurityContext( |
| 199 |
ServerCredential phCredential, |
| 200 |
IntPtr phContext, |
| 201 |
NativeHelpers.SecBufferDesc pInput, |
| 202 |
UInt32 fContextReq, |
| 203 |
UInt32 TargetDataRep, |
| 204 |
IntPtr phNewContext, |
| 205 |
NativeHelpers.SecBufferDesc pOutput, |
| 206 |
out UInt32 pfContextAttr, |
| 207 |
out Int64 ptsExpiry); |
| 208 |
|
| 209 |
[DllImport("Secur32.dll", CharSet = CharSet.Unicode)] |
| 210 |
public static extern Int32 AcquireCredentialsHandleW( |
| 211 |
[MarshalAs(UnmanagedType.LPWStr)] string pszPrincipal, |
| 212 |
[MarshalAs(UnmanagedType.LPWStr)] string pPackage, |
| 213 |
UInt32 fCredentialUse, |
| 214 |
IntPtr pvLogonId, |
| 215 |
IntPtr pAuthData, |
| 216 |
IntPtr pGetKeyFn, |
| 217 |
IntPtr pvGetKeyArgument, |
| 218 |
IntPtr phCredential, |
| 219 |
out Int64 ptsExpiry); |
| 220 |
|
| 221 |
[DllImport("Advapi32.dll", SetLastError = true)] |
| 222 |
public static extern bool AdjustTokenPrivileges( |
| 223 |
IntPtr TokenHandle, |
| 224 |
[MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges, |
| 225 |
IntPtr NewState, |
| 226 |
UInt32 BufferLength, |
| 227 |
IntPtr PreviousState, |
| 228 |
out UInt32 ReturnLength); |
| 229 |
|
| 230 |
[DllImport("Kernel32.dll", SetLastError = true)] |
| 231 |
public static extern bool CloseHandle( |
| 232 |
IntPtr hObject); |
| 233 |
|
| 234 |
[DllImport("Secur32.dll")] |
| 235 |
public static extern Int32 CompleteAuthToken( |
| 236 |
IntPtr phContext, |
| 237 |
NativeHelpers.SecBufferDesc pToken); |
| 238 |
|
| 239 |
[DllImport("Secur32.dll")] |
| 240 |
public static extern Int32 DecryptMessage( |
| 241 |
IntPtr phContext, |
| 242 |
NativeHelpers.SecBufferDesc pMessage, |
| 243 |
UInt32 MessageSeqNo, |
| 244 |
ref UInt32 pfQOP); |
| 245 |
|
| 246 |
[DllImport("Secur32.dll")] |
| 247 |
public static extern Int32 DeleteSecurityContext( |
| 248 |
IntPtr phContext); |
| 249 |
|
| 250 |
[DllImport("Secur32.dll")] |
| 251 |
public static extern Int32 EncryptMessage( |
| 252 |
IntPtr phContext, |
| 253 |
UInt32 fQOP, |
| 254 |
NativeHelpers.SecBufferDesc pMessage, |
| 255 |
UInt32 MessageSeqNo); |
| 256 |
|
| 257 |
[DllImport("Secur32.dll")] |
| 258 |
public static extern Int32 FreeContextBuffer( |
| 259 |
IntPtr pvContextBuffer); |
| 260 |
|
| 261 |
[DllImport("Secur32.dll")] |
| 262 |
public static extern Int32 FreeCredentialsHandle( |
| 263 |
IntPtr phCredential); |
| 264 |
|
| 265 |
[DllImport("Kernel32.dll")] |
| 266 |
public static extern IntPtr GetCurrentProcess(); |
| 267 |
|
| 268 |
[DllImport("Advapi32.dll", SetLastError = true)] |
| 269 |
public static extern bool GetTokenInformation( |
| 270 |
IntPtr TokenHandle, |
| 271 |
NativeHelpers.TokenInformationClass TokenInformationClass, |
| 272 |
SafeMemoryBuffer TokenInformation, |
| 273 |
UInt32 TokenInformationLength, |
| 274 |
out UInt32 ReturnLength); |
| 275 |
|
| 276 |
[DllImport("Advapi32.dll", SetLastError = true)] |
| 277 |
public static extern bool ImpersonateLoggedOnUser( |
| 278 |
IntPtr hToken); |
| 279 |
|
| 280 |
[DllImport("Advapi32.dll")] |
| 281 |
public static extern bool ImpersonateSelf( |
| 282 |
SecurityImpersonationLevel ImpersonationLevel); |
| 283 |
|
| 284 |
[DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] |
| 285 |
public static extern bool LookupPrivilegeValueW( |
| 286 |
string lpSystemName, |
| 287 |
string lpName, |
| 288 |
ref NativeHelpers.LUID lpLuid); |
| 289 |
|
| 290 |
[DllImport("Kernel32.dll", SetLastError = true)] |
| 291 |
public static extern SafeNativeHandle OpenProcess( |
| 292 |
ProcessAccessFlags dwDesiredAccess, |
| 293 |
bool bInheritHandle, |
| 294 |
UInt32 dwProcessId); |
| 295 |
|
| 296 |
[DllImport("Advapi32.dll", SetLastError = true)] |
| 297 |
public static extern bool OpenProcessToken( |
| 298 |
IntPtr ProcessHandle, |
| 299 |
TokenAccessLevels DesiredAccess, |
| 300 |
out SafeNativeHandle TokenHandle); |
| 301 |
|
| 302 |
[DllImport("Secur32.dll", CharSet = CharSet.Unicode)] |
| 303 |
public static extern Int32 QueryContextAttributesW( |
| 304 |
IntPtr phContext, |
| 305 |
SecPackageAttribute ulAttribute, |
| 306 |
IntPtr pBuffer); |
| 307 |
|
| 308 |
[DllImport("Secur32.dll", CharSet = CharSet.Unicode)] |
| 309 |
public static extern Int32 QuerySecurityPackageInfoW( |
| 310 |
string pPackageName, |
| 311 |
ref IntPtr ppPackageInfo); |
| 312 |
|
| 313 |
[DllImport("Advapi32.dll", SetLastError = true)] |
| 314 |
public static extern bool RevertToSelf(); |
| 315 |
} |
| 316 |
|
| 317 |
internal class SafeMemoryBuffer : SafeHandleZeroOrMinusOneIsInvalid |
| 318 |
{ |
| 319 |
public SafeMemoryBuffer() : base(true) { } |
| 320 |
public SafeMemoryBuffer(int cb) : base(true) |
| 321 |
{ |
| 322 |
base.SetHandle(Marshal.AllocHGlobal(cb)); |
| 323 |
} |
| 324 |
public SafeMemoryBuffer(IntPtr ptr) : base(true) |
| 325 |
{ |
| 326 |
base.SetHandle(handle); |
| 327 |
} |
| 328 |
|
| 329 |
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] |
| 330 |
protected override bool ReleaseHandle() |
| 331 |
{ |
| 332 |
Marshal.FreeHGlobal(handle); |
| 333 |
return true; |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
internal class SafeNativeHandle : SafeHandleZeroOrMinusOneIsInvalid |
| 338 |
{ |
| 339 |
public SafeNativeHandle() : base(true) { } |
| 340 |
|
| 341 |
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] |
| 342 |
protected override bool ReleaseHandle() |
| 343 |
{ |
| 344 |
return NativeMethods.CloseHandle(handle); |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
public class Win32Exception : System.ComponentModel.Win32Exception |
| 349 |
{ |
| 350 |
private string _msg; |
| 351 |
|
| 352 |
public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { } |
| 353 |
public Win32Exception(int errorCode, string message) : base(errorCode) |
| 354 |
{ |
| 355 |
_msg = String.Format("{0} ({1}, Win32ErrorCode {2} - 0x{2:X8})", message, base.Message, errorCode); |
| 356 |
} |
| 357 |
|
| 358 |
public override string Message { get { return _msg; } } |
| 359 |
public static explicit operator Win32Exception(string message) { return new Win32Exception(message); } |
| 360 |
} |
| 361 |
|
| 362 |
public class ServerCredential : SafeHandleZeroOrMinusOneIsInvalid |
| 363 |
{ |
| 364 |
private bool _initialized = false; |
| 365 |
|
| 366 |
public Int64 Expiry; |
| 367 |
public SecurityPackageInfo PackageInfo; |
| 368 |
|
| 369 |
public ServerCredential(string package) : base(true) |
| 370 |
{ |
| 371 |
base.SetHandle(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeHelpers.SecHandle)))); |
| 372 |
|
| 373 |
Int32 res = NativeMethods.AcquireCredentialsHandleW( |
| 374 |
null, |
| 375 |
package, |
| 376 |
0x00000001, // SECPKG_CRED_INBOUND |
| 377 |
IntPtr.Zero, |
| 378 |
IntPtr.Zero, |
| 379 |
IntPtr.Zero, |
| 380 |
IntPtr.Zero, |
| 381 |
this.handle, |
| 382 |
out Expiry); |
| 383 |
|
| 384 |
if (res != 0) |
| 385 |
throw new Win32Exception(res, "AcquireCredentialsHandleW() failed"); |
| 386 |
_initialized = true; |
| 387 |
|
| 388 |
PackageInfo = QuerySecurityPackageInfo(package); |
| 389 |
} |
| 390 |
|
| 391 |
private static SecurityPackageInfo QuerySecurityPackageInfo(string package) |
| 392 |
{ |
| 393 |
IntPtr pkgInfo = IntPtr.Zero; |
| 394 |
Int32 res = NativeMethods.QuerySecurityPackageInfoW(package, ref pkgInfo); |
| 395 |
if (res != 0) |
| 396 |
throw new Win32Exception(res, "QuerySecurityPackageInfoW() failed"); |
| 397 |
|
| 398 |
try |
| 399 |
{ |
| 400 |
NativeHelpers.SecPkgInfoW rawInfo = (NativeHelpers.SecPkgInfoW)Marshal.PtrToStructure(pkgInfo, |
| 401 |
typeof(NativeHelpers.SecPkgInfoW)); |
| 402 |
|
| 403 |
return new SecurityPackageInfo() |
| 404 |
{ |
| 405 |
Capabilities = rawInfo.fCapabilities, |
| 406 |
Version = rawInfo.wVersion, |
| 407 |
RPCID = rawInfo.wRPCID, |
| 408 |
MaxToken = rawInfo.cbMaxToken, |
| 409 |
Name = rawInfo.Name, |
| 410 |
Comment = rawInfo.Comment, |
| 411 |
}; |
| 412 |
} |
| 413 |
finally |
| 414 |
{ |
| 415 |
NativeMethods.FreeContextBuffer(pkgInfo); |
| 416 |
} |
| 417 |
} |
| 418 |
|
| 419 |
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] |
| 420 |
protected override bool ReleaseHandle() |
| 421 |
{ |
| 422 |
if (_initialized) |
| 423 |
NativeMethods.FreeCredentialsHandle(this.handle); |
| 424 |
|
| 425 |
Marshal.FreeHGlobal(this.handle); |
| 426 |
|
| 427 |
return true; |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
public class SecurityContext : SafeHandleZeroOrMinusOneIsInvalid |
| 432 |
{ |
| 433 |
private Int32 SEC_E_OK = 0x00000000; |
| 434 |
private Int32 SEC_I_COMPLETE_AND_CONTINUE = 0x00090314; |
| 435 |
private Int32 SEC_I_COMPLETE_NEEDED = 0x00090313; |
| 436 |
private Int32 SEC_I_CONTINUE_NEEDED = 0x00090312; |
| 437 |
|
| 438 |
private ServerCredential _credential; |
| 439 |
private bool _initialized = false; |
| 440 |
private UInt32 _sequenceEncrypt = 0; |
| 441 |
private UInt32 _sequenceDecrypt = 0; |
| 442 |
private int _trailerSize; |
| 443 |
private int _blockSize; |
| 444 |
|
| 445 |
public bool Complete = false; |
| 446 |
public UInt32 ContextAttributes; |
| 447 |
public Int64 Expiry; |
| 448 |
public byte[] SessionKey; |
| 449 |
|
| 450 |
public SecurityContext(ServerCredential credential) : base(true) |
| 451 |
{ |
| 452 |
this._credential = credential; |
| 453 |
base.SetHandle(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeHelpers.SecHandle)))); |
| 454 |
} |
| 455 |
|
| 456 |
public byte[] Step(byte[] token) |
| 457 |
{ |
| 458 |
List<SecurityBuffer> input = new List<SecurityBuffer>() |
| 459 |
{ |
| 460 |
new SecurityBuffer() |
| 461 |
{ |
| 462 |
BufferType = BufferType.Token, |
| 463 |
Data = token, |
| 464 |
}, |
| 465 |
}; |
| 466 |
|
| 467 |
List<SecurityBuffer> output = new List<SecurityBuffer>() |
| 468 |
{ |
| 469 |
new SecurityBuffer() |
| 470 |
{ |
| 471 |
BufferType = BufferType.Token, |
| 472 |
Data = new byte[_credential.PackageInfo.MaxToken], |
| 473 |
}, |
| 474 |
}; |
| 475 |
|
| 476 |
using (NativeHelpers.SecBufferDesc inputBuffer = new NativeHelpers.SecBufferDesc(input)) |
| 477 |
using (NativeHelpers.SecBufferDesc outputBuffer = new NativeHelpers.SecBufferDesc(output)) |
| 478 |
{ |
| 479 |
Int32 res = NativeMethods.AcceptSecurityContext( |
| 480 |
_credential, |
| 481 |
_initialized ? this.handle : IntPtr.Zero, |
| 482 |
inputBuffer, |
| 483 |
0, |
| 484 |
0x00000010, // SECURITY_NATIVE_DREP |
| 485 |
this.handle, |
| 486 |
outputBuffer, |
| 487 |
out ContextAttributes, |
| 488 |
out Expiry); |
| 489 |
|
| 490 |
_initialized = true; |
| 491 |
|
| 492 |
if (new List<Int32>() { SEC_I_COMPLETE_AND_CONTINUE, SEC_I_COMPLETE_NEEDED }.Contains(res)) |
| 493 |
res = NativeMethods.CompleteAuthToken(this.handle, outputBuffer); |
| 494 |
|
| 495 |
if (res == SEC_E_OK) |
| 496 |
{ |
| 497 |
Complete = true; |
| 498 |
GetSecPkgSessionKey(); |
| 499 |
GetSecPkgSizes(); |
| 500 |
} |
| 501 |
else if (res != SEC_I_CONTINUE_NEEDED) |
| 502 |
throw new Win32Exception(res, "AcceptSecurityContext() failed"); |
| 503 |
|
| 504 |
output = (List<SecurityBuffer>)outputBuffer; |
| 505 |
return output[0].Data; |
| 506 |
} |
| 507 |
} |
| 508 |
|
| 509 |
public byte[] Unwrap(byte[] data) |
| 510 |
{ |
| 511 |
List<SecurityBuffer> input = new List<SecurityBuffer>() |
| 512 |
{ |
| 513 |
new SecurityBuffer() |
| 514 |
{ |
| 515 |
BufferType = BufferType.Stream, |
| 516 |
Data = data, |
| 517 |
}, |
| 518 |
new SecurityBuffer() |
| 519 |
{ |
| 520 |
BufferType = BufferType.Data, |
| 521 |
Data = null, |
| 522 |
}, |
| 523 |
}; |
| 524 |
|
| 525 |
using (NativeHelpers.SecBufferDesc inputInfo = new NativeHelpers.SecBufferDesc(input)) |
| 526 |
{ |
| 527 |
UInt32 qop = 0; |
| 528 |
Int32 res = NativeMethods.DecryptMessage(this.handle, inputInfo, _sequenceDecrypt, ref qop); |
| 529 |
if (res != SEC_E_OK) |
| 530 |
throw new Win32Exception(res, "DecryptMessage() failed"); |
| 531 |
_sequenceDecrypt++; |
| 532 |
|
| 533 |
List<SecurityBuffer> output = (List<SecurityBuffer>)inputInfo; |
| 534 |
return output[1].Data; |
| 535 |
} |
| 536 |
} |
| 537 |
|
| 538 |
public byte[] Wrap(byte[] data) |
| 539 |
{ |
| 540 |
List<SecurityBuffer> input = new List<SecurityBuffer>() |
| 541 |
{ |
| 542 |
new SecurityBuffer() |
| 543 |
{ |
| 544 |
BufferType = BufferType.Token, |
| 545 |
Data = new byte[_trailerSize], |
| 546 |
}, |
| 547 |
new SecurityBuffer() |
| 548 |
{ |
| 549 |
BufferType = BufferType.Data, |
| 550 |
Data = data, |
| 551 |
}, |
| 552 |
new SecurityBuffer() |
| 553 |
{ |
| 554 |
BufferType = BufferType.Padding, |
| 555 |
Data = new byte[_blockSize], |
| 556 |
}, |
| 557 |
}; |
| 558 |
|
| 559 |
using (NativeHelpers.SecBufferDesc inputInfo = new NativeHelpers.SecBufferDesc(input)) |
| 560 |
{ |
| 561 |
Int32 res = NativeMethods.EncryptMessage(this.handle, 0, inputInfo, _sequenceEncrypt); |
| 562 |
if (res != SEC_E_OK) |
| 563 |
throw new Win32Exception(res, "DecryptMessage() failed"); |
| 564 |
_sequenceEncrypt++; |
| 565 |
|
| 566 |
List<SecurityBuffer> output = (List<SecurityBuffer>)inputInfo; |
| 567 |
|
| 568 |
byte[] encData = new byte[output.Sum(i => i.Data.Length)]; |
| 569 |
int offset = 0; |
| 570 |
foreach (SecurityBuffer buffer in output) |
| 571 |
{ |
| 572 |
Buffer.BlockCopy(buffer.Data, 0, encData, offset, buffer.Data.Length); |
| 573 |
offset += buffer.Data.Length; |
| 574 |
} |
| 575 |
|
| 576 |
return encData; |
| 577 |
} |
| 578 |
} |
| 579 |
|
| 580 |
private void GetSecPkgSessionKey() |
| 581 |
{ |
| 582 |
using (SafeMemoryBuffer sessionPtr = new SafeMemoryBuffer(Marshal.SizeOf( |
| 583 |
typeof(NativeHelpers.SecPkgContext_SessionKey)))) |
| 584 |
{ |
| 585 |
Int32 res = NativeMethods.QueryContextAttributesW(this.handle, SecPackageAttribute.SessionKey, |
| 586 |
sessionPtr.DangerousGetHandle()); |
| 587 |
if (res != SEC_E_OK) |
| 588 |
throw new Win32Exception(res, "QueryContextAttributesW(SessionKey) failed"); |
| 589 |
|
| 590 |
var sessionKey = (NativeHelpers.SecPkgContext_SessionKey)Marshal.PtrToStructure( |
| 591 |
sessionPtr.DangerousGetHandle(), typeof(NativeHelpers.SecPkgContext_SessionKey)); |
| 592 |
|
| 593 |
try |
| 594 |
{ |
| 595 |
SessionKey = new byte[sessionKey.SessionKeyLength]; |
| 596 |
Marshal.Copy(sessionKey.SessionKey, SessionKey, 0, SessionKey.Length); |
| 597 |
} |
| 598 |
finally |
| 599 |
{ |
| 600 |
NativeMethods.FreeContextBuffer(sessionKey.SessionKey); |
| 601 |
} |
| 602 |
} |
| 603 |
} |
| 604 |
|
| 605 |
private void GetSecPkgSizes() |
| 606 |
{ |
| 607 |
using (SafeMemoryBuffer sizePtr = new SafeMemoryBuffer(Marshal.SizeOf( |
| 608 |
typeof(NativeHelpers.SecPkgContextSizes)))) |
| 609 |
{ |
| 610 |
Int32 res = NativeMethods.QueryContextAttributesW(this.handle, SecPackageAttribute.Sizes, |
| 611 |
sizePtr.DangerousGetHandle()); |
| 612 |
if (res != SEC_E_OK) |
| 613 |
throw new Win32Exception(res, "QueryContextAttributesW(Sizes) failed"); |
| 614 |
|
| 615 |
NativeHelpers.SecPkgContextSizes sizes = (NativeHelpers.SecPkgContextSizes)Marshal.PtrToStructure( |
| 616 |
sizePtr.DangerousGetHandle(), typeof(NativeHelpers.SecPkgContextSizes)); |
| 617 |
|
| 618 |
_blockSize = sizes.cbBlockSize; |
| 619 |
_trailerSize = sizes.cbSecurityTrailer; |
| 620 |
} |
| 621 |
} |
| 622 |
|
| 623 |
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] |
| 624 |
protected override bool ReleaseHandle() |
| 625 |
{ |
| 626 |
if (_initialized) |
| 627 |
NativeMethods.DeleteSecurityContext(this.handle); |
| 628 |
|
| 629 |
Marshal.FreeHGlobal(this.handle); |
| 630 |
|
| 631 |
return true; |
| 632 |
} |
| 633 |
} |
| 634 |
|
| 635 |
public class PrivilegeEnabler : IDisposable |
| 636 |
{ |
| 637 |
public PrivilegeEnabler(params string[] privileges) |
| 638 |
{ |
| 639 |
int tokenPrivLength = Marshal.SizeOf(typeof(NativeHelpers.TOKEN_PRIVILEGES)); |
| 640 |
int luidAttrLength = luidAttrLength = Marshal.SizeOf( |
| 641 |
typeof(NativeHelpers.LUID_AND_ATTRIBUTES)) * (privileges.Length - 1); |
| 642 |
|
| 643 |
byte[] newStateBytes = new byte[tokenPrivLength + luidAttrLength]; |
| 644 |
using (SafeMemoryBuffer buffer = new SafeMemoryBuffer(tokenPrivLength + luidAttrLength)) |
| 645 |
{ |
| 646 |
IntPtr ptrOffset = buffer.DangerousGetHandle(); |
| 647 |
NativeHelpers.TOKEN_PRIVILEGES tokenPrivileges = new NativeHelpers.TOKEN_PRIVILEGES() |
| 648 |
{ |
| 649 |
PrivilegeCount = (UInt32)privileges.Length, |
| 650 |
Privileges = new NativeHelpers.LUID_AND_ATTRIBUTES[1], |
| 651 |
}; |
| 652 |
tokenPrivileges.Privileges[0].Attributes = PrivilegeAttributes.Enabled; |
| 653 |
tokenPrivileges.Privileges[0].Luid = LookupPrivilegeValue(privileges[0]); |
| 654 |
|
| 655 |
Marshal.StructureToPtr(tokenPrivileges, ptrOffset, false); |
| 656 |
ptrOffset = IntPtr.Add(ptrOffset, Marshal.SizeOf(tokenPrivileges)); |
| 657 |
|
| 658 |
for (int i = 1; i < privileges.Length; i++) |
| 659 |
{ |
| 660 |
NativeHelpers.LUID_AND_ATTRIBUTES luidAttr = new NativeHelpers.LUID_AND_ATTRIBUTES() |
| 661 |
{ |
| 662 |
Attributes = PrivilegeAttributes.Enabled, |
| 663 |
Luid = LookupPrivilegeValue(privileges[i]), |
| 664 |
}; |
| 665 |
Marshal.StructureToPtr(luidAttr, ptrOffset, false); |
| 666 |
ptrOffset = IntPtr.Add(ptrOffset, Marshal.SizeOf(luidAttr)); |
| 667 |
} |
| 668 |
|
| 669 |
if (!NativeMethods.ImpersonateSelf(SecurityImpersonationLevel.SecurityImpersonation)) |
| 670 |
throw new Win32Exception("ImpersonateSelf() failed"); |
| 671 |
try |
| 672 |
{ |
| 673 |
IntPtr currentProcess = NativeMethods.GetCurrentProcess(); |
| 674 |
SafeNativeHandle token; |
| 675 |
if (!NativeMethods.OpenProcessToken(currentProcess, TokenAccessLevels.AdjustPrivileges, out token)) |
| 676 |
throw new Win32Exception("OpenProcessToken() failed"); |
| 677 |
|
| 678 |
using (token) |
| 679 |
{ |
| 680 |
UInt32 returnLength; |
| 681 |
bool res = NativeMethods.AdjustTokenPrivileges(token.DangerousGetHandle(), false, |
| 682 |
buffer.DangerousGetHandle(), 0, IntPtr.Zero, out returnLength); |
| 683 |
int lastError = Marshal.GetLastWin32Error(); |
| 684 |
|
| 685 |
if (!res || lastError == 0x00000514) // ERROR_NOT_ALL_ASSIGNED |
| 686 |
throw new Win32Exception(lastError, "AdjustTokenPrivileges() failed"); |
| 687 |
} |
| 688 |
} |
| 689 |
catch |
| 690 |
{ |
| 691 |
NativeMethods.RevertToSelf(); |
| 692 |
throw; |
| 693 |
} |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
private NativeHelpers.LUID LookupPrivilegeValue(string privilege) |
| 698 |
{ |
| 699 |
NativeHelpers.LUID luid = new NativeHelpers.LUID(); |
| 700 |
if (!NativeMethods.LookupPrivilegeValueW(null, privilege, ref luid)) |
| 701 |
throw new Win32Exception(String.Format("LookupPrivilegeValueW({0}) failed", privilege)); |
| 702 |
|
| 703 |
return luid; |
| 704 |
} |
| 705 |
|
| 706 |
public void Dispose() |
| 707 |
{ |
| 708 |
NativeMethods.RevertToSelf(); |
| 709 |
GC.SuppressFinalize(this); |
| 710 |
} |
| 711 |
~PrivilegeEnabler() { this.Dispose(); } |
| 712 |
} |
| 713 |
|
| 714 |
public class SecurityBuffer |
| 715 |
{ |
| 716 |
public BufferType BufferType; |
| 717 |
public byte[] Data; |
| 718 |
} |
| 719 |
|
| 720 |
public class SecurityPackageInfo |
| 721 |
{ |
| 722 |
public Int32 Capabilities; |
| 723 |
public Int16 Version; |
| 724 |
public Int16 RPCID; |
| 725 |
public Int32 MaxToken; |
| 726 |
public string Name; |
| 727 |
public string Comment; |
| 728 |
} |
| 729 |
|
| 730 |
public class UserImpersonation : IDisposable |
| 731 |
{ |
| 732 |
public UserImpersonation(IdentityReference account) |
| 733 |
{ |
| 734 |
TokenAccessLevels tokenAccess = TokenAccessLevels.Duplicate | TokenAccessLevels.Impersonate | |
| 735 |
TokenAccessLevels.Query; |
| 736 |
|
| 737 |
foreach (Process process in Process.GetProcesses()) |
| 738 |
{ |
| 739 |
using (SafeNativeHandle processHandle = NativeMethods.OpenProcess(ProcessAccessFlags.QueryInformation, false, |
| 740 |
(UInt32)process.Id)) |
| 741 |
{ |
| 742 |
if (processHandle.IsInvalid) |
| 743 |
continue; |
| 744 |
|
| 745 |
SafeNativeHandle token; |
| 746 |
|
| 747 |
if (!NativeMethods.OpenProcessToken(processHandle.DangerousGetHandle(), tokenAccess, out token)) |
| 748 |
continue; |
| 749 |
|
| 750 |
using (token) |
| 751 |
using (SafeMemoryBuffer tokenUser = GetTokenInformation(token, |
| 752 |
NativeHelpers.TokenInformationClass.TokenUser)) |
| 753 |
{ |
| 754 |
NativeHelpers.TOKEN_USER user = (NativeHelpers.TOKEN_USER)Marshal.PtrToStructure( |
| 755 |
tokenUser.DangerousGetHandle(), typeof(NativeHelpers.TOKEN_USER)); |
| 756 |
|
| 757 |
SecurityIdentifier actualUser = new SecurityIdentifier(user.User.Sid); |
| 758 |
if (!actualUser.Equals(account.Translate(typeof(SecurityIdentifier)))) |
| 759 |
continue; |
| 760 |
|
| 761 |
if (!NativeMethods.ImpersonateLoggedOnUser(token.DangerousGetHandle())) |
| 762 |
continue; |
| 763 |
|
| 764 |
return; |
| 765 |
} |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
throw new Exception(String.Format("Failed to get access to a token for {0}", account.ToString())); |
| 770 |
} |
| 771 |
|
| 772 |
private SafeMemoryBuffer GetTokenInformation(SafeHandle handle, NativeHelpers.TokenInformationClass infoClass) |
| 773 |
{ |
| 774 |
UInt32 bufferLength; |
| 775 |
NativeMethods.GetTokenInformation(handle.DangerousGetHandle(), infoClass, |
| 776 |
new SafeMemoryBuffer(IntPtr.Zero), 0, out bufferLength); |
| 777 |
|
| 778 |
SafeMemoryBuffer buffer = new SafeMemoryBuffer((int)bufferLength); |
| 779 |
if (!NativeMethods.GetTokenInformation(handle.DangerousGetHandle(), infoClass, buffer, bufferLength, |
| 780 |
out bufferLength)) |
| 781 |
{ |
| 782 |
throw new Win32Exception(String.Format("GetTokenInformation({0}) failed", infoClass.ToString())); |
| 783 |
} |
| 784 |
|
| 785 |
return buffer; |
| 786 |
} |
| 787 |
|
| 788 |
public void Dispose() |
| 789 |
{ |
| 790 |
NativeMethods.RevertToSelf(); |
| 791 |
GC.SuppressFinalize(this); |
| 792 |
} |
| 793 |
~UserImpersonation() { this.Dispose(); } |
| 794 |
} |
| 795 |
|
| 796 |
[Flags] |
| 797 |
public enum BufferType : uint |
| 798 |
{ |
| 799 |
Empty = 0x0000000, |
| 800 |
Data = 0x00000001, |
| 801 |
Token = 0x00000002, |
| 802 |
PkgParams = 0x00000003, |
| 803 |
Missing = 0x00000004, |
| 804 |
Extra = 0x00000005, |
| 805 |
StreamTrailer = 0x00000006, |
| 806 |
StreamHeader = 0x00000007, |
| 807 |
NegotiationInfo = 0x00000008, |
| 808 |
Padding = 0x00000009, |
| 809 |
Stream = 0x0000000A, |
| 810 |
MechList = 0x0000000B, |
| 811 |
MechlistSignature = 0x0000000C, |
| 812 |
Target = 0x0000000D, |
| 813 |
ChannelBindings = 0x0000000E, |
| 814 |
ChangePassResponse = 0x0000000F, |
| 815 |
TargetHost = 0x00000010, |
| 816 |
Alert = 0x00000011, |
| 817 |
ApplicationProtocols = 0x00000012, |
| 818 |
StrpProtectionProfiles = 0x00000013, |
| 819 |
StrpMasterKeyIdentifier = 0x00000014, |
| 820 |
TokenBinding = 0x00000015, |
| 821 |
PreSharedKey = 0x00000016, |
| 822 |
PreSharedKeyIdentity = 0x00000017, |
| 823 |
DtlsMtu = 0x00000018, |
| 824 |
ReadOnlyWithChecksum = 0x10000000, |
| 825 |
ReadOnly = 0x80000000, |
| 826 |
AttrMask = 0xF0000000, |
| 827 |
} |
| 828 |
|
| 829 |
[Flags] |
| 830 |
public enum PrivilegeAttributes : uint |
| 831 |
{ |
| 832 |
Disabled = 0x00000000, |
| 833 |
EnabledByDefault = 0x00000001, |
| 834 |
Enabled = 0x00000002, |
| 835 |
Removed = 0x00000004, |
| 836 |
UsedForAccess = 0x80000000, |
| 837 |
} |
| 838 |
|
| 839 |
[Flags] |
| 840 |
public enum ProcessAccessFlags : uint |
| 841 |
{ |
| 842 |
Terminate = 0x00000001, |
| 843 |
CreateThread = 0x00000002, |
| 844 |
VmOperation = 0x00000008, |
| 845 |
VmRead = 0x00000010, |
| 846 |
VmWrite = 0x00000020, |
| 847 |
DupHandle = 0x00000040, |
| 848 |
CreateProcess = 0x00000080, |
| 849 |
SetQuota = 0x00000100, |
| 850 |
SetInformation = 0x00000200, |
| 851 |
QueryInformation = 0x00000400, |
| 852 |
SuspendResume = 0x00000800, |
| 853 |
QueryLimitedInformation = 0x00001000, |
| 854 |
Delete = 0x00010000, |
| 855 |
ReadControl = 0x00020000, |
| 856 |
WriteDac = 0x00040000, |
| 857 |
WriteOwner = 0x00080000, |
| 858 |
Synchronize = 0x00100000, |
| 859 |
} |
| 860 |
|
| 861 |
public enum SecPackageAttribute : uint |
| 862 |
{ |
| 863 |
ServerAuthFlags = 0x80000083, |
| 864 |
AccessToken = 0x80000012, |
| 865 |
Creds = 0x80000080, |
| 866 |
NegotiationPackage = 0x80000081, |
| 867 |
FullAccessToken = 0x80000082, |
| 868 |
CertTrustStatus = 0x80000084, |
| 869 |
Creds2 = 0x80000086, |
| 870 |
Sizes = 0x00000000, |
| 871 |
SessionKey = 0x00000009, |
| 872 |
PackageInfo = 0x0000000A, |
| 873 |
SubjectSecurityAttributes = 0x0000007C, |
| 874 |
} |
| 875 |
|
| 876 |
public enum SecurityImpersonationLevel : uint |
| 877 |
{ |
| 878 |
SecurityAnonymous = 0, |
| 879 |
SecurityIdentification = 1, |
| 880 |
SecurityImpersonation = 2, |
| 881 |
SecurityDelegation = 3, |
| 882 |
} |
| 883 |
} |
| 884 |
'@ |
| 885 |
|
| 886 |
Function Write-Verbose { |
| 887 |
[CmdletBinding()] |
| 888 |
param ( |
| 889 |
[Parameter(Mandatory=$true)] |
| 890 |
[String] |
| 891 |
$Message |
| 892 |
) |
| 893 |
|
| 894 |
$msg = "{0} - RID[{1}] USER[{2}] - {3}" -f ( |
| 895 |
(Get-Date).ToString('o'), |
| 896 |
[Runspace]::DefaultRunspace.Id, |
| 897 |
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name, |
| 898 |
$Message |
| 899 |
) |
| 900 |
Microsoft.PowerShell.Utility\Write-Verbose -Message $msg |
| 901 |
} |
| 902 |
|
| 903 |
$clientProcessor = { |
| 904 |
[CmdletBinding()] |
| 905 |
param ( |
| 906 |
[Parameter(Mandatory=$true)] |
| 907 |
[System.Net.Sockets.TcpClient]$Client |
| 908 |
) |
| 909 |
|
| 910 |
trap { |
| 911 |
$msg = "Uncaught exception, exiting listener`n$($_ | Out-String)`n$($_.ScriptStackTrace)" |
| 912 |
Write-Verbose -Message $msg |
| 913 |
return |
| 914 |
} |
| 915 |
|
| 916 |
Function Get-StreamData { |
| 917 |
[CmdletBinding()] |
| 918 |
param ( |
| 919 |
[Parameter(Mandatory=$true)] |
| 920 |
[System.IO.Stream] |
| 921 |
$Stream |
| 922 |
) |
| 923 |
|
| 924 |
Write-Verbose -Message "Reading data from $clientIp" |
| 925 |
$data = New-Object -TypeName System.Byte[] -ArgumentList 4 |
| 926 |
$null = $Stream.Read($data, 0, $data.Length) |
| 927 |
$length = [System.BitConverter]::ToInt32($data, 0) |
| 928 |
|
| 929 |
Write-Verbose -Message "Trying to read $length bytes from $clientIp" |
| 930 |
$data = New-Object -TypeName System.Byte[] -ArgumentList $length |
| 931 |
$null = $Stream.Read($data, 0, $data.Length) |
| 932 |
|
| 933 |
,$data |
| 934 |
} |
| 935 |
|
| 936 |
Function Set-StreamData { |
| 937 |
[CmdletBinding()] |
| 938 |
param ( |
| 939 |
[Parameter(Mandatory=$true)] |
| 940 |
[System.IO.Stream] |
| 941 |
$Stream, |
| 942 |
|
| 943 |
[Parameter(Mandatory=$true)] |
| 944 |
[AllowEmptyCollection()] |
| 945 |
[byte[]] |
| 946 |
$Data |
| 947 |
) |
| 948 |
|
| 949 |
Write-Verbose -Message "Writing $($Data.Length) bytes to $clientIp" |
| 950 |
$length = [BitConverter]::GetBytes($Data.Length) |
| 951 |
$Stream.Write($length, 0, $length.Length) |
| 952 |
if ($Data.Length -gt 0) { |
| 953 |
$Stream.Write($Data, 0, $Data.Length) |
| 954 |
} |
| 955 |
} |
| 956 |
|
| 957 |
Function Use-UserImpersonation { |
| 958 |
[CmdletBinding()] |
| 959 |
param ( |
| 960 |
[Parameter(Mandatory=$true)] |
| 961 |
[System.Security.Principal.IdentityReference] |
| 962 |
$Account, |
| 963 |
|
| 964 |
[Parameter(Mandatory=$true)] |
| 965 |
[ScriptBlock] |
| 966 |
$ScriptBlock, |
| 967 |
|
| 968 |
[System.Collections.IDictionary] |
| 969 |
$Parameters = @{} |
| 970 |
) |
| 971 |
|
| 972 |
# SeDebugPrivilege is used to make sure we can interrogate each process on the system. |
| 973 |
$privEnabler = New-Object -TypeName Pyspnego.PrivilegeEnabler -ArgumentList 'SeDebugPrivilege' |
| 974 |
try { |
| 975 |
$accountName = $Account.Translate([System.Security.Principal.NTAccount]).Value |
| 976 |
Write-Verbose -Message "Attempting to impersonate existing token for $accountName" |
| 977 |
$userImpersonation = New-Object -TypeName Pyspnego.UserImpersonation -ArgumentList $Account |
| 978 |
try { |
| 979 |
.$ScriptBlock @Parameters |
| 980 |
} finally { |
| 981 |
$userImpersonation.Dispose() |
| 982 |
} |
| 983 |
} finally { |
| 984 |
$privEnabler.Dispose() |
| 985 |
} |
| 986 |
} |
| 987 |
|
| 988 |
$process = { |
| 989 |
param ( |
| 990 |
[Parameter(Mandatory=$true)] |
| 991 |
[System.IO.Stream] |
| 992 |
$Stream |
| 993 |
) |
| 994 |
# Get the new context data, i.e. protocol to use and initial token |
| 995 |
$data = Get-StreamData -Stream $Stream |
| 996 |
$protocol = [System.Text.Encoding]::UTF8.GetString($data) |
| 997 |
|
| 998 |
$data = Get-StreamData -Stream $Stream |
| 999 |
|
| 1000 |
Write-Verbose -Message "Creating server credential with the protocol $protocol" |
| 1001 |
$cred = New-Object -TypeName Pyspnego.ServerCredential -ArgumentList $protocol |
| 1002 |
try { |
| 1003 |
Write-Verbose -Message "Creating server context" |
| 1004 |
$context = New-Object -TypeName Pyspnego.SecurityContext -ArgumentList $cred |
| 1005 |
try { |
| 1006 |
while (-not $context.Complete) { |
| 1007 |
Write-Verbose -Message "Process token from client" |
| 1008 |
$output = $context.Step($data) |
| 1009 |
|
| 1010 |
Set-StreamData -Stream $Stream -Data $output |
| 1011 |
$data = Get-StreamData -Stream $Stream |
| 1012 |
} |
| 1013 |
|
| 1014 |
Write-Verbose -Message ("SessionKey: {0}" -f ([System.Convert]::ToBase64String($context.SessionKey))) |
| 1015 |
|
| 1016 |
while ($true) { |
| 1017 |
if ($data.Length -eq 0) { |
| 1018 |
Write-Verbose -Message "Received empty msg from the server, exiting client context" |
| 1019 |
return |
| 1020 |
} |
| 1021 |
|
| 1022 |
Write-Verbose -Message "Unwrapping message from client" |
| 1023 |
$output = $context.Unwrap($data) |
| 1024 |
Write-Verbose -Message "Unwrapped data: $([System.Text.Encoding]::UTF8.GetString($output))" |
| 1025 |
|
| 1026 |
Write-Verbose -Message "Wrapping message for client" |
| 1027 |
$output = $context.Wrap($output) |
| 1028 |
|
| 1029 |
Set-StreamData -Stream $Stream -Data $output |
| 1030 |
$data = Get-StreamData -Stream $Stream |
| 1031 |
} |
| 1032 |
} finally { |
| 1033 |
Write-Verbose -Message "Closing server context" |
| 1034 |
$context.Dispose() |
| 1035 |
} |
| 1036 |
} finally { |
| 1037 |
Write-Verbose -Message "Closing server credential" |
| 1038 |
$cred.Dispose() |
| 1039 |
} |
| 1040 |
} |
| 1041 |
|
| 1042 |
$clientIp = $Client.Client.RemoteEndPoint |
| 1043 |
$systemSid = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList @( |
| 1044 |
[System.Security.Principal.WellKnownSidType]::LocalSystemSid, $null |
| 1045 |
) |
| 1046 |
|
| 1047 |
try { |
| 1048 |
Write-Verbose -Message "Started client pipeline for $clientIp" |
| 1049 |
$stream = $Client.GetStream() |
| 1050 |
try { |
| 1051 |
Use-UserImpersonation -Account $systemSid -ScriptBlock $process -Parameters @{Stream = $stream} |
| 1052 |
} finally { |
| 1053 |
Write-Verbose -Message "Disposing stream for $clientIp" |
| 1054 |
$stream.Dispose() |
| 1055 |
} |
| 1056 |
} finally { |
| 1057 |
Write-Verbose -Message "Disposing client socket for $clientIp" |
| 1058 |
$Client.Dispose() |
| 1059 |
} |
| 1060 |
} |
| 1061 |
|
| 1062 |
$serverListener = { |
| 1063 |
[CmdletBinding()] |
| 1064 |
param ( |
| 1065 |
[Parameter(Mandatory=$true)] |
| 1066 |
[System.Management.Automation.Runspaces.RunspacePool] |
| 1067 |
$RunspacePool, |
| 1068 |
|
| 1069 |
[Parameter(Mandatory=$true)] |
| 1070 |
[System.Net.Sockets.TcpListener] |
| 1071 |
$Listener |
| 1072 |
) |
| 1073 |
|
| 1074 |
Write-Verbose -Message "Starting TCP listener" |
| 1075 |
$Listener.Start() |
| 1076 |
$jobList = [System.Collections.Generic.List[PSObject]]@() |
| 1077 |
|
| 1078 |
while ($true) { |
| 1079 |
Write-Verbose -Message "Waiting for client connection" |
| 1080 |
try { |
| 1081 |
$client = $Listener.AcceptTcpClient() |
| 1082 |
} catch { |
| 1083 |
# The parent runspace closed the listener, just exit this pipeline. |
| 1084 |
break |
| 1085 |
} |
| 1086 |
|
| 1087 |
Write-Verbose -Message "Client connected from $($client.Client.RemoteEndPoint), starting pipeline" |
| 1088 |
|
| 1089 |
$clientPs = [PowerShell]::Create() |
| 1090 |
$clientPs.RunspacePool = $RunspacePool |
| 1091 |
$null = $clientPs.AddScript($ClientProcessor, $true).AddParameter('Client', $client) |
| 1092 |
$handle = $clientPs.BeginInvoke() |
| 1093 |
|
| 1094 |
$jobList.Add([PSCustomObject]@{ |
| 1095 |
PowerShell = $clientPs |
| 1096 |
Handle = $handle |
| 1097 |
Client = $client |
| 1098 |
}) |
| 1099 |
} |
| 1100 |
|
| 1101 |
Write-Verbose -Message "TCP Server has ended, ensure client connection jobs have ended" |
| 1102 |
foreach ($job in $jobList) { |
| 1103 |
$jobId = $job.PowerShell.InstanceId |
| 1104 |
Write-Verbose -Message "Encding client on $jobId" |
| 1105 |
$job.Client.Dispose() |
| 1106 |
|
| 1107 |
Write-Verbose -Message "Calling EndInvoke() on $jobId" |
| 1108 |
$null = $job.PowerShell.EndInvoke($job.Handle) |
| 1109 |
|
| 1110 |
Write-Verbose -Message "Disposing client pipeline $jobId" |
| 1111 |
$job.PowerShell.Dispose() |
| 1112 |
} |
| 1113 |
|
| 1114 |
Write-Verbose -Message "Ending TCP listener" |
| 1115 |
} |
| 1116 |
|
| 1117 |
$ss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() |
| 1118 |
$ss.Variables.Add( |
| 1119 |
(New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList @( |
| 1120 |
'ErrorActionPreference', $ErrorActionPreference, $null |
| 1121 |
)) |
| 1122 |
) |
| 1123 |
$ss.Variables.Add( |
| 1124 |
(New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList @( |
| 1125 |
'VerbosePreference', $VerbosePreference, $null |
| 1126 |
)) |
| 1127 |
) |
| 1128 |
$ss.Variables.Add( |
| 1129 |
(New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList @( |
| 1130 |
'ClientProcessor', $clientProcessor, $null |
| 1131 |
)) |
| 1132 |
) |
| 1133 |
$ss.Commands.Add( |
| 1134 |
(New-Object -TypeName System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList @( |
| 1135 |
'Write-Verbose', (Get-Content function:\Write-Verbose) |
| 1136 |
)) |
| 1137 |
) |
| 1138 |
|
| 1139 |
Write-Verbose -Message "Creating runspace pool" |
| 1140 |
$pool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(2, 4, $ss, $Host) |
| 1141 |
$pool.Open() |
| 1142 |
|
| 1143 |
try { |
| 1144 |
Write-Verbose -Message "Creating TCP listener on port $Port" |
| 1145 |
$listener = New-Object -TypeName System.Net.Sockets.TcpListener -ArgumentList @([System.Net.IPAddress]0, $Port) |
| 1146 |
|
| 1147 |
Write-Verbose -Message "Creating TCP server pipeline" |
| 1148 |
$serverPs = [PowerShell]::Create() |
| 1149 |
$serverPs.RunspacePool = $pool |
| 1150 |
$null = $serverPs.AddScript($serverListener, $true).AddParameter('RunspacePool', $pool) |
| 1151 |
$null = $serverPs.AddParameter('Listener', $listener) |
| 1152 |
$handle = $serverPs.BeginInvoke() |
| 1153 |
|
| 1154 |
try { |
| 1155 |
# Wait until user input before killing the server. |
| 1156 |
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") |
| 1157 |
} finally { |
| 1158 |
# Stop the listener so the serverPs runspace will stop running. |
| 1159 |
$listener.Stop() |
| 1160 |
|
| 1161 |
$null = $serverPs.EndInvoke($handle) |
| 1162 |
$serverPs.Dispose() |
| 1163 |
} |
| 1164 |
} finally { |
| 1165 |
Write-Verbose -Message "Stopping runspace pool" |
| 1166 |
$pool.Dispose() |
| 1167 |
} |