//*************************************************************** // From the book "Win32 System Services: The Heart of Windows 98 // and Windows 2000" // by Marshall Brain // Published by Prentice Hall // // Copyright 1995, by Prentice Hall. // // This code allows a client to connect, and then impersonates // that client until it disconnects. //*************************************************************** // imprecv.cpp #include #include int main(void) { char toDisptxt[80]; HANDLE ssnpPipe; DWORD NumBytesRead; char buffer[80]; DWORD bufferLen; SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sd; InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE); sa.nLength= sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = &sd; /* Create a named pipe for receiving messages */ ssnpPipe=CreateNamedPipe("\\\\.\\pipe\\ssnp", PIPE_ACCESS_INBOUND, PIPE_TYPE_MESSAGE | PIPE_WAIT, 1, 0, 0, 150, &sa); /* Check and see if the named pipe was created */ if (ssnpPipe == INVALID_HANDLE_VALUE) { cerr << "ERROR: Unable to create a named pipe." << endl; return (1); } bufferLen = 80; GetUserName(buffer, &bufferLen); cout << "Right now my user is: " << buffer << endl; cout << "Waiting for connection..." << endl; /* Allow a client to connect to the name pipe, terminate if unsuccessful */ if(!ConnectNamedPipe(ssnpPipe, (LPOVERLAPPED) NULL)) { cerr << "ERROR: Unable to connect a pipe " << GetLastError() << endl; CloseHandle(ssnpPipe); return (1); } cout << "Beginning impersonation...\n"; if (!ImpersonateNamedPipeClient(ssnpPipe)) { cerr << "ERROR: Cannot impersonate, " << GetLastError() << endl; CloseHandle(ssnpPipe); return(1); } bufferLen = 80; GetUserName(buffer, &bufferLen); cout << "Now my user is: " << buffer << endl; /* Repeatedly check for messages until the program is terminated */ while(1) { /* Read the message and check to see if read was successful */ if (!ReadFile(ssnpPipe, toDisptxt, sizeof(toDisptxt), &NumBytesRead, (LPOVERLAPPED) NULL)) { cerr << "ERROR: Unable to read from pipe" << endl; CloseHandle(ssnpPipe); break; } /* Display the Message */ cout << toDisptxt << endl; } /* while */ cout << "Reverting back to original user.\n"; RevertToSelf(); bufferLen = 80; GetUserName(buffer, &bufferLen); cout << "Now my user is: " << buffer << endl; }