/* good2() reverses the bodies in the if statement */ static void good2() { if(GLOBAL_CONST_TRUE) { { char * pipeName = "\\\\.\\pipe\\mypipe"; HANDLE hPipe = INVALID_HANDLE_VALUE; hPipe = CreateNamedPipeA( pipeName, FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUFFER_SIZE, BUFFER_SIZE, NMPWAIT_USE_DEFAULT_WAIT, NULL); if (hPipe == INVALID_HANDLE_VALUE) { exit(1); } /* FIX: check for the correct return value */ if (!ImpersonateNamedPipeClient(hPipe)) { exit(1); } CloseHandle(hPipe); } } }
void CWE253_Incorrect_Check_of_Function_Return_Value__char_w32ImpersonateNamedPipeClient_09_bad() { if(GLOBAL_CONST_TRUE) { { char * pipeName = "\\\\.\\pipe\\mypipe"; HANDLE hPipe = INVALID_HANDLE_VALUE; hPipe = CreateNamedPipeA( pipeName, FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUFFER_SIZE, BUFFER_SIZE, NMPWAIT_USE_DEFAULT_WAIT, NULL); if (hPipe == INVALID_HANDLE_VALUE) { exit(1); } /* FLAW: ImpersonateNamedPipeClient() might fail, in which case the return value will be 0 (false), but * we are checking to see if the return value is greater than zero (which will be true) */ if (ImpersonateNamedPipeClient(hPipe) > 0) { exit(1); } CloseHandle(hPipe); } } }
void Win32NamedPipeImpersonator::impersonate() { HANDLE hPipe = mPipeSession.mSocketPtr->native(); BOOL ok = ImpersonateNamedPipeClient(hPipe); DWORD dwErr = GetLastError(); RCF_VERIFY(ok, RCF::Exception(_RcfError_Pipe(), dwErr)); }
HRESULT PipeStream::ImpersonateClient() { if (!IsValid()) return E_HANDLE; if (!ImpersonateNamedPipeClient(handle_)) return HRESULT_FROM_LAST_ERROR(); return S_OK; }
void Win32NamedPipeImpersonator::impersonate() { Win32NamedPipeSessionState & sessionState = dynamic_cast<Win32NamedPipeSessionState &>( RCF::getCurrentRcfSessionPtr()->getSessionState()); BOOL ok = ImpersonateNamedPipeClient(sessionState.mhPipe); DWORD dwErr = GetLastError(); RCF_VERIFY(ok, RCF::Exception(_RcfError_Pipe(), dwErr)); }
HRESULT NamedPipeChannel::Impersonate() { base::AutoLock guard(lock_); if (end_point_ != EndPoint::kServer) return E_HANDLE; if (!ImpersonateNamedPipeClient(handle_)) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; }
static int get_token(connection_context *c) { int res = 0; int wres; HANDLE token; if (c->runas) { credentials crd; if (!prepare_credentials(c->runas, &crd)) { hprintf(c->pipe, "error Incorrect runas credentials\n"); goto finish; } wres = LogonUser(crd.user, crd.domain, crd.password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &c->token); if (!wres) { hprintf(c->pipe, "error Cannot LogonUser(%s,%s,%s) %d\n", crd.user, crd.domain, crd.password, GetLastError()); goto finish; } res = 1; goto finish; } else if (c->system) { if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) { hprintf(c->pipe, "error Cannot OpenProcessToken %d\n", GetLastError()); goto finish; } } else { if (!ImpersonateNamedPipeClient(c->pipe->h)) { hprintf(c->pipe, "error Cannot ImpersonateNamedPipeClient %d\n", GetLastError()); goto finish; } if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE, &token)) { hprintf(c->pipe, "error Cannot OpenThreadToken %d\n", GetLastError()); goto finishRevertToSelf; } } if (!DuplicateTokenEx(token, MAXIMUM_ALLOWED, 0, c->implevel, TokenPrimary, &c->token)) { hprintf(c->pipe, "error Cannot Duplicate Token %d\n", GetLastError()); goto finishCloseToken; } res = 1; finishCloseToken: CloseHandle(token); finishRevertToSelf: if (!c->system) { if (!RevertToSelf()) { hprintf(c->pipe, "error Cannot RevertToSelf %d\n", GetLastError()); res = 0; } } finish: return res; }
void PipeImpersonatedThread::execute() { m_success = ImpersonateNamedPipeClient(m_pipeHandle) != 0; if (!m_success) { // Store fault reason Environment::getErrStr(&m_faultReason); } m_impersonationReadyEvent.notify(); while (!isTerminating()) { m_threadSleeper.waitForEvent(); } RevertToSelf(); }
/* good1() uses if(staticFive!=5) instead of if(staticFive==5) */ static void good1() { if(staticFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { HANDLE hPipe = INVALID_HANDLE_VALUE; hPipe = CreateNamedPipeA( "\\\\.\\pipe\\test_pipe", PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, NMPWAIT_USE_DEFAULT_WAIT, NULL); if (hPipe == INVALID_HANDLE_VALUE) { exit(1); } /* ConnectNamedPipe returns failure if a client connected between CreateNamedPipe and now, * which isn't actually an error in terms of waiting for a client. */ if (!ConnectNamedPipe(hPipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) { CloseHandle(hPipe); exit(1); } /* FIX: Check if "ImpersonateNamedPipeClient" succeeded or not */ if (!ImpersonateNamedPipeClient(hPipe)) { printLine("Failed to impersonate"); } else { printLine("Impersonated"); if (!RevertToSelf()) { exit(1); } } CloseHandle(hPipe); } } }
void CWE273_Improper_Check_for_Dropped_Privileges__w32_ImpersonateNamedPipeClient_07_bad() { if(staticFive==5) { { HANDLE hPipe = INVALID_HANDLE_VALUE; hPipe = CreateNamedPipeA( "\\\\.\\pipe\\test_pipe", PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, NMPWAIT_USE_DEFAULT_WAIT, NULL); if (hPipe == INVALID_HANDLE_VALUE) { exit(1); } /* ConnectNamedPipe returns failure if a client connected between CreateNamedPipe and now, * which isn't actually an error in terms of waiting for a client. */ if (!ConnectNamedPipe(hPipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) { CloseHandle(hPipe); exit(1); } /* FLAW: Failed to check return status of ImpersonateNamedPipeClient * -- However, since we're not even DOING anything with the pipe * it's debatable whether this is really a bug */ ImpersonateNamedPipeClient(hPipe); printLine("Impersonated"); if (!RevertToSelf()) { exit(1); } CloseHandle(hPipe); } } }
/* good1() uses if(GLOBAL_CONST_FALSE) instead of if(GLOBAL_CONST_TRUE) */ static void good1() { if(GLOBAL_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { char * pipeName = "\\\\.\\pipe\\mypipe"; HANDLE hPipe = INVALID_HANDLE_VALUE; hPipe = CreateNamedPipeA( pipeName, FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUFFER_SIZE, BUFFER_SIZE, NMPWAIT_USE_DEFAULT_WAIT, NULL); if (hPipe == INVALID_HANDLE_VALUE) { exit(1); } /* FIX: check for the correct return value */ if (!ImpersonateNamedPipeClient(hPipe)) { exit(1); } CloseHandle(hPipe); } } }
int main(int argc,char* argv[]) { DWORD dwType = REG_DWORD; DWORD dwSize = sizeof(DWORD); DWORD dwNumber = 0; char szUser[256]; exit(0); HANDLE hPipe = 0; if (argc > 1) lsasspid=atoi(argv[1]); if (argc > 2) sscanf(argv[2],"%x",&MAGICESPINLSA); printf("Fun with debug registers. Written by Georgi Guninski\n"); printf("vvdr started: lsasspid=%d breakp=%x\n",lsasspid,MAGICESPINLSA); CreateThread(0, 0, &threadwriter, NULL, 0, 0); CreateThread(0, 0, &waitlsadie, NULL, 0, 0); CreateThread(0, 0, &threaddeb, NULL, 0, 0); while(!lsadied); printf("start %s\n",szPipe); hPipe = CreateNamedPipe (szPipe, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE|PIPE_WAIT, 2, 0, 0, 0, NULL); if (hPipe == INVALID_HANDLE_VALUE) { printf ("Failed to create named pipe:\n %s\n", szPipe); return 3; } CreateThread(0, 0, &threadlock, NULL, 0, 0); ConnectNamedPipe (hPipe, NULL); if (!ReadFile (hPipe, (void *) &dwNumber, 4, &dwSize, NULL)) { printf ("Failed to read the named pipe.\n"); CloseHandle(hPipe); return 4; } if (!ImpersonateNamedPipeClient (hPipe)) { printf ("Failed to impersonate the named pipe.\n"); CloseHandle(hPipe); return 5; } dwSize = 256; GetUserName(szUser, &dwSize); printf ("Impersonating dummy :) : %s\n\n\n\n", szUser); // the action begins FILE *f1; f1=fopen("c:\\winnt\\system32\\vv1.vv","a"); if (f1 != NULL) { fprintf(f1,"lsass worked\n"); fclose(f1); printf("\n%s\n","Done!"); } else printf("error creating file"); fflush(stdout); HKEY mykey; RegCreateKey(HKEY_CLASSES_ROOT,"vv",&mykey); RegCloseKey(mykey); CloseHandle(hPipe); return 0; }
/* * Worker thread for named pipe impersonation. Creates a named pipe and impersonates * the first client which connects to it. */ DWORD THREADCALL elevate_namedpipe_thread(THREAD * thread) { DWORD dwResult = ERROR_ACCESS_DENIED; HANDLE hServerPipe = NULL; HANDLE hToken = NULL; HANDLE hSem = NULL; char * cpServicePipe = NULL; Remote * remote = NULL; BYTE bMessage[128] = {0}; DWORD dwBytes = 0; do { if (!thread) { BREAK_WITH_ERROR("[ELEVATE] elevate_namedpipe_thread. invalid thread", ERROR_BAD_ARGUMENTS); } cpServicePipe = (char *)thread->parameter1; remote = (Remote *)thread->parameter2; hSem = (HANDLE)thread->parameter3; if (!cpServicePipe || !remote) { BREAK_WITH_ERROR("[ELEVATE] elevate_namedpipe_thread. invalid thread arguments", ERROR_BAD_ARGUMENTS); } dprintf("[ELEVATE] pipethread. CreateNamedPipe(%s)",cpServicePipe); // create the named pipe for the client service to connect to hServerPipe = CreateNamedPipe(cpServicePipe, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE|PIPE_WAIT, 2, 0, 0, 0, NULL); if (!hServerPipe) { BREAK_ON_ERROR("[ELEVATE] elevate_namedpipe_thread. CreateNamedPipe failed"); } while (TRUE) { if (event_poll(thread->sigterm, 0)) { BREAK_WITH_ERROR("[ELEVATE] elevate_namedpipe_thread. thread->sigterm received", ERROR_DBG_TERMINATE_THREAD); } //signal the client that the pipe is ready if (hSem) { if (!ReleaseSemaphore(hSem, 1, NULL)) { BREAK_WITH_ERROR("[ELEVATE] elevate_namedpipe_thread. ReleaseSemaphore failed", ERROR_DBG_TERMINATE_THREAD); } } // wait for a client to connect to our named pipe... if (!ConnectNamedPipe(hServerPipe, NULL)) { if (GetLastError() != ERROR_PIPE_CONNECTED) continue; } dprintf("[ELEVATE] pipethread. got client conn."); // we can't impersonate a client untill we have performed a read on the pipe... if (!ReadFile(hServerPipe, &bMessage, 1, &dwBytes, NULL)) { CONTINUE_ON_ERROR("[ELEVATE] pipethread. ReadFile failed"); } // impersonate the client! if (!ImpersonateNamedPipeClient(hServerPipe)) { CONTINUE_ON_ERROR("[ELEVATE] elevate_namedpipe_thread. ImpersonateNamedPipeClient failed"); } // get a handle to this threads token if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE, &hToken)) { CONTINUE_ON_ERROR("[ELEVATE] elevate_namedpipe_thread. OpenThreadToken failed"); } // now we can set the meterpreters thread token to that of our system // token so all subsequent meterpreter threads will use this token. core_update_thread_token(remote, hToken); dwResult = ERROR_SUCCESS; break; } } while (0); if (hServerPipe) { DisconnectNamedPipe(hServerPipe); CLOSE_HANDLE(hServerPipe); } dprintf("[ELEVATE] elevate_namedpipe_thread finishing, dwResult=%d", dwResult); return dwResult; }
bool GetUserHandle(Settings& settings, BOOL& bLoadedProfile, PROFILEINFO& profile, HANDLE hCmdPipe) { DWORD gle = 0; if(settings.bUseSystemAccount) { if(BAD_HANDLE(settings.hUser)) //might already have hUser from a previous call { EnablePrivilege(SE_DEBUG_NAME); //helps with OpenProcess, required for GetLocalSystemProcessToken settings.hUser = GetLocalSystemProcessToken(); if(BAD_HANDLE(settings.hUser)) { Log(L"Not able to get Local System token", true); return false; } else Log(L"Got Local System handle", false); Duplicate(settings.hUser, __FILE__, __LINE__); } return true; } else { //not Local System, so either as specified user, or as current user if(FALSE == settings.user.IsEmpty()) { CString user, domain; GetUserDomain(settings.user, user, domain); BOOL bLoggedIn = LogonUser(user, domain.IsEmpty() ? NULL : domain, settings.password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_WINNT50, &settings.hUser); gle = GetLastError(); #ifdef _DEBUG Log(L"DEBUG: LogonUser", gle); #endif if((FALSE == bLoggedIn) || BAD_HANDLE(settings.hUser)) { Log(StrFormat(L"Error logging in as %s", settings.user), gle); return false; } else Duplicate(settings.hUser, __FILE__, __LINE__); //gives max rights if(!BAD_HANDLE(settings.hUser) && (false == settings.bDontLoadProfile)) { EnablePrivilege(SE_RESTORE_NAME); EnablePrivilege(SE_BACKUP_NAME); bLoadedProfile = LoadUserProfile(settings.hUser, &profile); #ifdef _DEBUG gle = GetLastError(); Log(L"DEBUG: LoadUserProfile", gle); #endif } return true; } else { //run as current user if(NULL != hCmdPipe) { BOOL b = ImpersonateNamedPipeClient(hCmdPipe); DWORD gle = GetLastError(); if(FALSE == b) Log(L"Failed to impersonate client user", gle); else Log(L"Impersonated caller", false); } HANDLE hThread = GetCurrentThread(); BOOL bDupe = DuplicateHandle(GetCurrentProcess(), hThread, GetCurrentProcess(), &hThread, 0, TRUE, DUPLICATE_SAME_ACCESS); DWORD gle = GetLastError(); BOOL bOpen = OpenThreadToken(hThread, TOKEN_DUPLICATE | TOKEN_QUERY, TRUE, &settings.hUser); gle = GetLastError(); if(1008 == gle) //no thread token { bOpen = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &settings.hUser); gle = GetLastError(); } if(FALSE == bOpen) Log(L"Failed to open current user token", GetLastError()); Duplicate(settings.hUser, __FILE__, __LINE__); //gives max rights RevertToSelf(); return !BAD_HANDLE(settings.hUser); } } }
int fcgi_accept_request(fcgi_request *req) { #ifdef _WIN32 HANDLE pipe; OVERLAPPED ov; #endif fcgi_finish_request(req); while (1) { if (req->fd < 0) { while (1) { if (in_shutdown) { return -1; } #ifdef _WIN32 pipe = (HANDLE)_get_osfhandle(req->listen_socket); FCGI_LOCK(req->listen_socket); ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!ConnectNamedPipe(pipe, &ov)) { errno = GetLastError(); if (errno == ERROR_IO_PENDING) { while (WaitForSingleObject(ov.hEvent, 1000) == WAIT_TIMEOUT) { if (in_shutdown) { CloseHandle(ov.hEvent); FCGI_UNLOCK(req->listen_socket); return -1; } } } else if (errno != ERROR_PIPE_CONNECTED) { } } CloseHandle(ov.hEvent); req->fd = req->listen_socket; FCGI_UNLOCK(req->listen_socket); #else { sa_t sa; socklen_t len = sizeof(sa); FCGI_LOCK(req->listen_socket); req->fd = accept(req->listen_socket, (struct sockaddr *)&sa, &len); FCGI_UNLOCK(req->listen_socket); } #endif if (req->fd < 0 && (in_shutdown || errno != EINTR)) { return -1; } #ifdef _WIN32 break; #else if (req->fd >= 0) { struct timeval tv = {5,0}; fd_set set; FD_ZERO(&set); FD_SET(req->fd, &set); try_again: errno = 0; if (select(req->fd + 1, &set, NULL, NULL, &tv) >= 0 && FD_ISSET(req->fd, &set)) { break; } if (errno == EINTR) goto try_again; fcgi_close(req, 1, 0); } #endif } } else if (in_shutdown) { return -1; } if (fcgi_read_request(req)) { #ifdef _WIN32 if (is_impersonate) { pipe = (HANDLE)_get_osfhandle(req->fd); if (!ImpersonateNamedPipeClient(pipe)) { fcgi_close(req, 1, 1); continue; } } #endif return req->fd; } else { fcgi_close(req, 1, 1); } } }