Exemple #1
1
		AVSValue __cdecl CreateWritePipe(AVSValue args, void* user_data, IScriptEnvironment* env) {
			LPCSTR pipe_name = args[0].AsString();
			HANDLE hPipe = CreateNamedPipeA(pipe_name, PIPE_ACCESS_OUTBOUND,
				PIPE_TYPE_BYTE | PIPE_WAIT, 1, PIPE_BUFFER_SIZE, 0, NMPWAIT_USE_DEFAULT_WAIT, nullptr);
			if (hPipe == INVALID_HANDLE_VALUE)
				env->ThrowError("Error creating pipe with name \"%s\", code 0x%08X", pipe_name, GetLastError());
			return (int)hPipe;
		}
Exemple #2
0
// References:
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365588(v=vs.85).aspx
static HANDLE
connect_pipe(const char* app_name) {
	HANDLE pipe = INVALID_HANDLE_VALUE;
	char username[UNLEN + 1];
	DWORD unlen = UNLEN + 1;
	if (GetUserNameA(username, &unlen)) {
		// add username to the pipe path so it will not clash with other users' pipes.
		char pipe_name[MAX_PATH];
		sprintf(pipe_name, "\\\\.\\pipe\\%s\\%s_pipe", username, app_name);
		const size_t buffer_size = 1024;
		// create the pipe
		pipe = CreateNamedPipeA(pipe_name,
			PIPE_ACCESS_DUPLEX,
			PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
			PIPE_UNLIMITED_INSTANCES,
			buffer_size,
			buffer_size,
			NMPWAIT_USE_DEFAULT_WAIT,
			&g_securityAttributes);

		if (pipe != INVALID_HANDLE_VALUE) {
			// try to connect to the named pipe
			// NOTE: this is a blocking call
			if (FALSE == ConnectNamedPipe(pipe, NULL)) {
				// fail to connect the pipe
				CloseHandle(pipe);
				pipe = INVALID_HANDLE_VALUE;
			}
		}
	}
	return pipe;
}
void CWE253_Incorrect_Check_of_Function_Return_Value__char_w32ImpersonateNamedPipeClient_17_bad()
{
    int j;
    for(j = 0; j < 1; j++)
    {
        {
            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);
        }
    }
}
Exemple #4
0
static void test_runner(void (*p_run_test)(void))
{
    HANDLE thread;

    sprintf(service_name, "WineTestService%d", GetTickCount());
    trace("service_name: %s\n", service_name);
    sprintf(named_pipe_name, "\\\\.\\pipe\\%s_pipe", service_name);

    pipe_handle = CreateNamedPipeA(named_pipe_name, PIPE_ACCESS_INBOUND,
                                   PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT, 10, 2048, 2048, 10000, NULL);
    ok(pipe_handle != INVALID_HANDLE_VALUE, "CreateNamedPipe failed: %u\n", GetLastError());
    if(pipe_handle == INVALID_HANDLE_VALUE)
        return;

    InitializeCriticalSection(&event_cs);
    event_handle = CreateEventA(NULL, FALSE, FALSE, NULL);
    ok(event_handle != INVALID_HANDLE_VALUE, "CreateEvent failed: %u\n", GetLastError());
    if(event_handle == INVALID_HANDLE_VALUE)
        return;

    thread = CreateThread(NULL, 0, pipe_thread, NULL, 0, NULL);
    ok(thread != NULL, "CreateThread failed: %u\n", GetLastError());
    if(!thread)
        return;

    p_run_test();

    WaitForSingleObject(thread, INFINITE);
    CloseHandle(event_handle);
    CloseHandle(pipe_handle);
}
/* good1() uses the GoodSinkBody in the for statements */
static void good1()
{
    int k;
    for(k = 0; k < 1; k++)
    {
        {
            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);
        }
    }
}
static void good1()
{
    {
        char * pipeName = "\\\\.\\pipe\\mypipe";
        HANDLE hPipe = INVALID_HANDLE_VALUE;
        BOOL fConnected = FALSE;
        hPipe = CreateNamedPipeA(
                    pipeName,
                    FILE_FLAG_FIRST_PIPE_INSTANCE, /* FILE_FLAG_FIRST_PIPE_INSTANCE - this flag must be set */
                    PIPE_TYPE_MESSAGE |
                    PIPE_READMODE_MESSAGE |
                    PIPE_WAIT,
                    PIPE_UNLIMITED_INSTANCES,
                    BUFFER_SIZE,
                    BUFFER_SIZE,
                    NMPWAIT_USE_DEFAULT_WAIT,
                    NULL);
        /* FIX: check for the correct return value */
        if (hPipe == INVALID_HANDLE_VALUE)
        {
            exit(1);
        }
        fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
        /* We'll leave out most of the implementation since it has nothing to do with the CWE
         * and since the checkers are looking for certain function calls anyway */
        CloseHandle(hPipe);
    }
}
void CWE253_Incorrect_Check_of_Function_Return_Value__char_w32CreateNamedPipe_01_bad()
{
    {
        char * pipeName = "\\\\.\\pipe\\mypipe";
        HANDLE hPipe = INVALID_HANDLE_VALUE;
        BOOL fConnected = FALSE;
        hPipe = CreateNamedPipeA(
                    pipeName,
                    FILE_FLAG_FIRST_PIPE_INSTANCE, /* FILE_FLAG_FIRST_PIPE_INSTANCE - this flag must be set */
                    PIPE_TYPE_MESSAGE |
                    PIPE_READMODE_MESSAGE |
                    PIPE_WAIT,
                    PIPE_UNLIMITED_INSTANCES,
                    BUFFER_SIZE,
                    BUFFER_SIZE,
                    NMPWAIT_USE_DEFAULT_WAIT,
                    NULL);
        /* FLAW: If CreateNamedPipeA() failed, the return value will be INVALID_HANDLE_VALUE,
           but we are checking to see if the return value is NULL */
        if (hPipe == NULL)
        {
            exit(1);
        }
        fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
        /* We'll leave out most of the implementation since it has nothing to do with the CWE
         * and since the checkers are looking for certain function calls anyway */
        CloseHandle(hPipe);
    }
}
Exemple #8
0
// Create a synchronous pipe for messaging
static int create_logger(DWORD buffsize)
{
	if (buffsize == 0) {
		buffsize = LOGGER_PIPE_SIZE;
	}

	if (logger_wr_handle != INVALID_HANDLE_VALUE) {
		// We (supposedly) don't have logging, so try to reach a stderr
		fprintf(stderr, "trying to recreate logger pipe\n");
		return WDI_ERROR_EXISTS;
	}

	// Read end of the pipe
	logger_rd_handle = CreateNamedPipeA(LOGGER_PIPE_NAME, PIPE_ACCESS_INBOUND,
		PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE, 1, buffsize, buffsize, 0, NULL);
	if (logger_rd_handle == INVALID_HANDLE_VALUE) {
		fprintf(stderr, "could not create logger pipe for reading: %s\n", windows_error_str(0));
		return WDI_ERROR_RESOURCE;
	}

	// Write end of the pipe
	logger_wr_handle = CreateFileA(LOGGER_PIPE_NAME, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL, NULL);
	if (logger_wr_handle == INVALID_HANDLE_VALUE) {
		fprintf(stderr, "could not create logger pipe for writing: %s\n", windows_error_str(0));
		CloseHandle(logger_rd_handle);
		logger_rd_handle = INVALID_HANDLE_VALUE;
		return WDI_ERROR_RESOURCE;
	}

	log_messages_pending = 0;

	return WDI_SUCCESS;
}
Exemple #9
0
    void NamedPipe::Initialize()
    {
        SECURITY_ATTRIBUTES attr;
        attr.bInheritHandle = TRUE;
        attr.nLength = sizeof(SECURITY_ATTRIBUTES);
        attr.lpSecurityDescriptor = NULL;

        mHandle = CreateFileA(
            mName.c_str(),
            GENERIC_READ | GENERIC_WRITE,
            0,
            &attr,
            OPEN_EXISTING,
            0,
            NULL);

        if (mHandle == INVALID_HANDLE) {
            mHandle = CreateNamedPipeA(
                mName.c_str(),
                PIPE_ACCESS_DUPLEX,
                PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                PIPE_UNLIMITED_INSTANCES,
                65536,
                65536,
                NMPWAIT_WAIT_FOREVER,
                &attr);

            if (mHandle == INVALID_HANDLE) {
                throw NamedPipeException(GetLastErrorString());
            } else if (!ConnectNamedPipe(mHandle, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) {
                throw NamedPipeException(GetLastErrorString());
            }
        }
    }
void CWE252_Unchecked_Return_Value__char_w32CreateNamedPipe_04_bad()
{
    if(STATIC_CONST_TRUE)
    {
        {
            char * pipeName = "\\\\.\\pipe\\mypipe";
            HANDLE hPipe = INVALID_HANDLE_VALUE;
            BOOL fConnected = FALSE;
            hPipe = CreateNamedPipeA(
                        pipeName,
                        FILE_FLAG_FIRST_PIPE_INSTANCE, /* FILE_FLAG_FIRST_PIPE_INSTANCE - this flag must be set */
                        PIPE_TYPE_MESSAGE |
                        PIPE_READMODE_MESSAGE |
                        PIPE_WAIT,
                        PIPE_UNLIMITED_INSTANCES,
                        BUFSIZE,
                        BUFSIZE,
                        NMPWAIT_USE_DEFAULT_WAIT,
                        NULL);
            /* FLAW: Do not check the return value */
            fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
            /* We'll leave out most of the implementation since it has nothing to do with the CWE
             * and since the checkers are looking for certain function calls anyway */
            CloseHandle(hPipe);
        }
    }
}
bool
named_pipe_t::create()
{
    // FIXME i#1703: NYI
    // We should document the 256 char limit on path name.
    HANDLE pipe = CreateNamedPipeA(named_pipe.c_str(),
                                   PIPE_ACCESS...);
}
void *VMPI_OpenAndConnectToNamedPipe(const char *pipeName)
{
  char name[256];
  _snprintf(name, sizeof(name), "\\\\.\\pipe\\%s", pipeName);
  HANDLE pipe = CreateNamedPipeA((LPCSTR)name, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 4096, 4096, 100, NULL);
  ConnectNamedPipe(pipe, NULL);
  return (void*)pipe;
}
static PIPE_HANDLE createNamedPipe(const char* pipeName, SECURITY_ATTRIBUTES sa)
{
	return CreateNamedPipeA(	pipeName,
	                        PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
	                        PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
	                        PIPE_UNLIMITED_INSTANCES,
	                        8192, 8192, 0,
	                        &sa);
}
Exemple #14
0
int uv_stdio_pipe_server(uv_pipe_t* handle, DWORD access, char* name, size_t nameSize) {
  HANDLE pipeHandle;
  int errno;
  int err;
  char* ptr = (char*)handle;

  while (TRUE) {
    uv_unique_pipe_name(ptr, name, nameSize);

    pipeHandle = CreateNamedPipeA(name,
                                  access | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
                                  PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                                  1,
                                  65536,
                                  65536,
                                  0,
                                  NULL);

    if (pipeHandle != INVALID_HANDLE_VALUE) {
      /* No name collisions.  We're done. */
      break;
    }

    errno = GetLastError();
    if (errno != ERROR_PIPE_BUSY && errno != ERROR_ACCESS_DENIED) {
      uv_set_sys_error(errno);
      err = -1;
      goto done;
    }

    /* Pipe name collision.  Increment the pointer and try again. */
    ptr++;
  }

  if (CreateIoCompletionPort(pipeHandle,
                             LOOP->iocp,
                             (ULONG_PTR)handle,
                             0) == NULL) {
    uv_set_sys_error(GetLastError());
    err = -1;
    goto done;
  }

  uv_connection_init((uv_stream_t*)handle);
  handle->handle = pipeHandle;
  handle->flags |= UV_HANDLE_GIVEN_OS_HANDLE;
  err = 0;

done:
  if (err && pipeHandle != INVALID_HANDLE_VALUE) {
    CloseHandle(pipeHandle);
  }

  return err;
}
/*!
    \internal
*/
void QInterProcessChannel::run() {
  if (!serverMode) return;

  HANDLE hPipe;
  char buffer[bufferSize];
  bool connected, readSuccess;
  DWORD bytesRead;

  // thread loop
  for (;;) {
    hPipe =
        CreateNamedPipeA(qPrintable(pipeName), PIPE_ACCESS_INBOUND,
                         PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
                         1, 0, bufferSize, 0, NULL);

    if (hPipe == INVALID_HANDLE_VALUE) break;

    connected = ConnectNamedPipe(hPipe, NULL)
                    ? TRUE
                    : (GetLastError() == ERROR_PIPE_CONNECTED);

    if (!connected) {
      CloseHandle(hPipe);
      continue;
    }

    readSuccess = ReadFile(hPipe, buffer, bufferSize, &bytesRead, NULL);
    buffer[bufferSize - 1] = 0;

    if (!readSuccess || !bytesRead) {
      CloseHandle(hPipe);
      continue;
    }

    QStringList argv = QManagedRequest::splitArguments(QString(buffer));
    const QString cmd = argv.at(0);

    // if server instance is going to suspend thread...
    if (cmd == "--quit") {
      CloseHandle(hPipe);
      break;
    } else if (cmd == "--request") {
      argv.removeAt(0);
      emit request(argv);
    } else {
      emit message(QString(buffer));
    }

    CloseHandle(hPipe);
  }
}
Exemple #16
0
/*++
Routine Description:
    The MyCreatePipe API is used to create an anonymous pipe I/O device.
    Unlike CreatePipe FILE_FLAG_OVERLAPPED may be specified for one or
    both handles.
    Two handles to the device are created.  One handle is opened for
    reading and the other is opened for writing.  These handles may be
    used in subsequent calls to ReadFile and WriteFile to transmit data
    through the pipe.
Arguments:
    lpReadPipe - Returns a handle to the read side of the pipe.  Data
        may be read from the pipe by specifying this handle value in a
        subsequent call to ReadFile.
    lpWritePipe - Returns a handle to the write side of the pipe.  Data
        may be written to the pipe by specifying this handle value in a
        subsequent call to WriteFile.
    lpPipeAttributes - An optional parameter that may be used to specify
        the attributes of the new pipe.  If the parameter is not
        specified, then the pipe is created without a security
        descriptor, and the resulting handles are not inherited on
        process creation.  Otherwise, the optional security attributes
        are used on the pipe, and the inherit handles flag effects both
        pipe handles.
    nSize - Supplies the requested buffer size for the pipe.  This is
        only a suggestion and is used by the operating system to
        calculate an appropriate buffering mechanism.  A value of zero
        indicates that the system is to choose the default buffering
        scheme.
Return Value:
    TRUE - The operation was successful.
    FALSE/NULL - The operation failed. Extended error status is available
        using GetLastError.
--*/
BOOL APIENTRY MyCreatePipe(OUT LPHANDLE lpReadPipe, OUT LPHANDLE lpWritePipe, IN LPSECURITY_ATTRIBUTES lpPipeAttributes,
                           IN DWORD nSize)

{
    HANDLE ReadPipeHandle, WritePipeHandle;
    DWORD dwError;
    CHAR PipeNameBuffer[MAX_PATH];

    //
    // Only one valid OpenMode flag - FILE_FLAG_OVERLAPPED
    //
    DWORD dwReadMode = FILE_FLAG_OVERLAPPED;
    DWORD dwWriteMode = FILE_FLAG_OVERLAPPED;

    //
    //  Set the default timeout to 120 seconds
    //
    if(nSize == 0) { nSize = 4096; }

    // Increment the pipe number, in a MT safe way
    InterlockedIncrement(&PipeSerialNumber);
    sprintf(PipeNameBuffer, "\\\\.\\Pipe\\LOCAL\\RemoteExeAnon.%08x.%08x", (unsigned int)GetCurrentProcessId(),
            (unsigned int)PipeSerialNumber);

    ReadPipeHandle = CreateNamedPipeA(PipeNameBuffer, PIPE_ACCESS_INBOUND | dwReadMode, PIPE_TYPE_BYTE | PIPE_WAIT,
                                      1,          // Number of pipes
                                      nSize,      // Out buffer size
                                      nSize,      // In buffer size
                                      120 * 1000, // Timeout in ms
                                      lpPipeAttributes);

    if(!ReadPipeHandle) { return FALSE; }

    WritePipeHandle = CreateFileA(PipeNameBuffer, GENERIC_WRITE,
                                  0, // No sharing
                                  lpPipeAttributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | dwWriteMode,
                                  NULL // Template file
    );

    if(INVALID_HANDLE_VALUE == WritePipeHandle) {
        dwError = GetLastError();
        CloseHandle(ReadPipeHandle);
        SetLastError(dwError);
        return FALSE;
    }

    *lpReadPipe = ReadPipeHandle;
    *lpWritePipe = WritePipeHandle;
    return (TRUE);
}
Exemple #17
0
uv_err_t uv_stdio_pipe_server(uv_loop_t* loop, uv_pipe_t* handle, DWORD access,
    char* name, size_t nameSize) {
  HANDLE pipeHandle;
  int errorno;
  uv_err_t err;
  char* ptr = (char*)handle;

  for (;;) {
    uv_unique_pipe_name(ptr, name, nameSize);

    pipeHandle = CreateNamedPipeA(name,
      access | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
      PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 65536, 65536, 0,
      NULL);

    if (pipeHandle != INVALID_HANDLE_VALUE) {
      /* No name collisions.  We're done. */
      break;
    }

    errorno = GetLastError();
    if (errorno != ERROR_PIPE_BUSY && errorno != ERROR_ACCESS_DENIED) {
      err = uv__new_sys_error(errorno);
      goto error;
    }

    /* Pipe name collision.  Increment the pointer and try again. */
    ptr++;
  }

  if (CreateIoCompletionPort(pipeHandle,
                             loop->iocp,
                             (ULONG_PTR)handle,
                             0) == NULL) {
    err = uv__new_sys_error(GetLastError());
    goto error;
  }

  uv_pipe_connection_init(handle);
  handle->handle = pipeHandle;

  return uv_ok_;

 error:
  if (pipeHandle != INVALID_HANDLE_VALUE) {
    CloseHandle(pipeHandle);
  }

  return err;
}
Exemple #18
0
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	
	ZeroMemory(szRawArgs,MAG_BUFFER);
	ZeroMemory(szDllName,MAG_BUFFER);
	ZeroMemory(szTargetFunc,MAG_BUFFER);
	ZeroMemory(szSuppliedFunc,MAG_BUFFER);

	hNamedPipe = CreateNamedPipeA("\\\\.\\pipe\\dllargs",
		PIPE_ACCESS_DUPLEX,
		PIPE_TYPE_BYTE,
		PIPE_UNLIMITED_INSTANCES ,
		MAG_BUFFER,
		MAG_BUFFER,
		INFINITE,
		NULL);

	Sleep(1000);
	if(!ReadFile(hNamedPipe,
		szRawArgs,
		MAG_BUFFER,
		&dwBytesRead,
		NULL))
	{
		
	}

	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		
		//break;
	case DLL_THREAD_ATTACH:
		//break;
	case DLL_THREAD_DETACH:
		//break;
	case DLL_PROCESS_DETACH:
		MessageBoxExA(NULL,
		szRawArgs,
		"Hooked",
		MB_ABORTRETRYIGNORE,
		0);
		break;
	}
	//return TRUE;
}
/* 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);
        }
    }
}
int TestPipeCreateNamedPipe(int argc, char* argv[])
{
	HANDLE SingleThread;
	HANDLE ClientThread;
	HANDLE ServerThread;
	HANDLE hPipe;

	/* Verify that CreateNamedPipe returns INVALID_HANDLE_VALUE on failure */
	hPipe = CreateNamedPipeA(NULL, 0, 0, 0, 0, 0, 0, NULL);
	if (hPipe != INVALID_HANDLE_VALUE)
	{
		printf("CreateNamedPipe unexpectedly returned %p instead of INVALID_HANDLE_VALUE (%p)\n",
			hPipe, INVALID_HANDLE_VALUE);
		return -1;
	}

#ifndef _WIN32
	signal(SIGPIPE, SIG_IGN);
#endif
	if (!(ReadyEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
	{
		printf("CreateEvent failure: (%"PRIu32")\n", GetLastError());
		return -1;
	}
	if (!(SingleThread = CreateThread(NULL, 0, named_pipe_single_thread, NULL, 0, NULL)))
	{
		printf("CreateThread (SingleThread) failure: (%"PRIu32")\n", GetLastError());
		return -1;
	}
	if (!(ClientThread = CreateThread(NULL, 0, named_pipe_client_thread, NULL, 0, NULL)))
	{
		printf("CreateThread (ClientThread) failure: (%"PRIu32")\n", GetLastError());
		return -1;
	}
	if (!(ServerThread = CreateThread(NULL, 0, named_pipe_server_thread, NULL, 0, NULL)))
	{
		printf("CreateThread (ServerThread) failure: (%"PRIu32")\n", GetLastError());
		return -1;
	}
	WaitForSingleObject(SingleThread, INFINITE);
	WaitForSingleObject(ClientThread, INFINITE);
	WaitForSingleObject(ServerThread, INFINITE);
	CloseHandle(SingleThread);
	CloseHandle(ClientThread);
	CloseHandle(ServerThread);
	return testFailed;
}
Exemple #21
0
static inline bool ipc_pipe_internal_create_pipe(ipc_pipe_server_t *pipe,
		const char *name)
{
	char new_name[512];
	const DWORD access = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED;
	const DWORD flags = PIPE_TYPE_MESSAGE     |
	                    PIPE_READMODE_MESSAGE |
	                    PIPE_WAIT;

	strcpy_s(new_name, sizeof(new_name), "\\\\.\\pipe\\");
	strcat_s(new_name, sizeof(new_name), name);

	pipe->handle = CreateNamedPipeA(new_name, access, flags, 1,
			IPC_PIPE_BUF_SIZE, IPC_PIPE_BUF_SIZE, 0, NULL);

	return pipe->handle != INVALID_HANDLE_VALUE;
}
Exemple #22
0
void mpk_import_add_named_pipe_instance(common_vars *common_vars) {
  HANDLE named_pipe_handle = CreateNamedPipeA("\\\\.\\pipe\\" m_mpk_import_named_pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, nullptr);
  if (!named_pipe_handle) {
    m_last_error_str(err);
    m_die("cannot create mpk import named pipe instance, call to \"CreateNamedPipeA\" failed\nerr: %s", err);
  }
  HANDLE io_completion_port = CreateIoCompletionPort(named_pipe_handle, common_vars->io_completion_port, mpk_import_named_pipe_event, 0);
  if (!io_completion_port) {
    m_last_error_str(err_str);
    m_die("cannot connect mpk import named pipe to io completion port, call to \"CreateIoCompletionPort\" failed\nerr: %s", err_str);
  }
  mpk_import_named_pipe_instance *new_named_pipe_instance = (mpk_import_named_pipe_instance *)memory_pool_allocate(&common_vars->mpk_import_named_pipe_instance_memory_pool);
  *new_named_pipe_instance = {};
  new_named_pipe_instance->handle = named_pipe_handle;
  sllist_push(&common_vars->mpk_import_named_pipe_instance_list, new_named_pipe_instance);
  ConnectNamedPipe(named_pipe_handle, &new_named_pipe_instance->overlapped);
}
Exemple #23
0
// pipe name: \\.\pipe\pipename
async_pipe_t async_pipe_server(const char* name)
{
	DWORD dwWait;
	Win32Pipe* o;

	o = (Win32Pipe*)GlobalAlloc(GPTR, sizeof(Win32Pipe));
	if(!o)
		return NULL;

	o->pipe = CreateNamedPipeA(name, PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, NULL);
	if(INVALID_HANDLE_VALUE != o->pipe)
	{
		o->overlap.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
		if(NULL != o->overlap.hEvent)
		{
			// MSDN: Overlapped ConnectNamedPipe should return zero. 
			if(0==ConnectNamedPipe(o->pipe, &o->overlap))
			{
				switch(GetLastError())
				{
				case ERROR_PIPE_CONNECTED:
					return o;

				case ERROR_IO_PENDING:
					do
					{
						dwWait = WaitForSingleObjectEx(o->overlap.hEvent, INFINITE, TRUE);
						if(WAIT_OBJECT_0 == dwWait)
						{
							if(GetOverlappedResult(o->pipe, &o->overlap, &dwWait, FALSE))
								return o;
						}
					} while(dwWait==WAIT_IO_COMPLETION);
					break;
				}
			}
			
			CloseHandle(o->overlap.hEvent);
		}
		CloseHandle(o->pipe);
	}

	GlobalFree(o);
	return NULL;
}
Exemple #24
0
value win_pipe(long readMode, long writeMode) {
  CAMLparam0();
  SECURITY_ATTRIBUTES attr;
  HANDLE readh, writeh;
  CHAR name[MAX_PATH];
  CAMLlocal3(readfd, writefd, res);

  attr.nLength = sizeof(attr);
  attr.lpSecurityDescriptor = NULL;
  attr.bInheritHandle = TRUE;

  sprintf(name, "\\\\.\\Pipe\\UnisonAnonPipe.%08lx.%08lx",
             GetCurrentProcessId(), pipeSerial++);

  readh =
    CreateNamedPipeA
    (name, PIPE_ACCESS_INBOUND | readMode, PIPE_TYPE_BYTE | PIPE_WAIT,
     1, UNIX_BUFFER_SIZE, UNIX_BUFFER_SIZE, 0, &attr);

  if (readh == INVALID_HANDLE_VALUE) {
    win32_maperr(GetLastError());
    uerror("CreateNamedPipe", Nothing);
    return FALSE;
  }

  writeh =
    CreateFileA
    (name, GENERIC_WRITE, 0, &attr, OPEN_EXISTING,
     FILE_ATTRIBUTE_NORMAL | writeMode, NULL);

  if (writeh == INVALID_HANDLE_VALUE) {
    win32_maperr(GetLastError());
    CloseHandle(readh);
    uerror("CreateFile", Nothing);
    return FALSE;
  }

  readfd = win_alloc_handle(readh);
  writefd = win_alloc_handle(writeh);
  res = alloc_small(2, 0);
  Store_field(res, 0, readfd);
  Store_field(res, 1, writefd);
  CAMLreturn (res);
}
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);
        }
    }
}
Exemple #26
0
static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
{
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
  TRACE("listening on %s\n", pname);

  npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
                               PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
                               PIPE_UNLIMITED_INSTANCES,
                               RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
  if (npc->pipe == INVALID_HANDLE_VALUE) {
    WARN("CreateNamedPipe failed with error %d\n", GetLastError());
    if (GetLastError() == ERROR_FILE_EXISTS)
      return RPC_S_DUPLICATE_ENDPOINT;
    else
      return RPC_S_CANT_CREATE_ENDPOINT;
  }

  memset(&npc->ovl, 0, sizeof(npc->ovl));
  npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);

  /* Note: we don't call ConnectNamedPipe here because it must be done in the
   * server thread as the thread must be alertable */
  return RPC_S_OK;
}
/* 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);
        }
    }
}
/* good1() uses if(globalReturnsFalse()) instead of if(globalReturnsTrue()) */
static void good1()
{
    if(globalReturnsFalse())
    {
        /* 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;
            BOOL fConnected = FALSE;
            hPipe = CreateNamedPipeA(
                        pipeName,
                        FILE_FLAG_FIRST_PIPE_INSTANCE, /* FILE_FLAG_FIRST_PIPE_INSTANCE - this flag must be set */
                        PIPE_TYPE_MESSAGE |
                        PIPE_READMODE_MESSAGE |
                        PIPE_WAIT,
                        PIPE_UNLIMITED_INSTANCES,
                        BUFSIZE,
                        BUFSIZE,
                        NMPWAIT_USE_DEFAULT_WAIT,
                        NULL);
            /* FIX: Check the return value of CreateNamedPipe() for an invalid handle */
            if (hPipe == INVALID_HANDLE_VALUE)
            {
                exit(1);
            }
            fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
            /* We'll leave out most of the implementation since it has nothing to do with the CWE
             * and since the checkers are looking for certain function calls anyway */
            CloseHandle(hPipe);
        }
    }
}
static HANDLE PipeCreateServer(const char* pipename)
{
  BOOL                ret;
  const char*         sd            = "D:(A;OICI;GA;;;WD)";

  SECURITY_ATTRIBUTES sa;
  HANDLE              result        = INVALID_HANDLE_VALUE;

  sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa.lpSecurityDescriptor = NULL;
  sa.bInheritHandle = FALSE;

  ret = ConvertStringSecurityDescriptorToSecurityDescriptorA(
    sd,
    SDDL_REVISION_1,
    &sa.lpSecurityDescriptor, 
    NULL);

  if(!ret)
    return INVALID_HANDLE_VALUE;

  result = CreateNamedPipeA(
    pipename,
    PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
    PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
    PIPE_UNLIMITED_INSTANCES,
    DEF_BUF_SIZE,
    DEF_BUF_SIZE,
    NMPWAIT_USE_DEFAULT_WAIT,
    &sa);

  if(sa.lpSecurityDescriptor)
    LocalFree(sa.lpSecurityDescriptor);

  return result;
}
Exemple #30
0
/*
 * Create a pipe, a unidirectional channel for interprocess communication.
 */
static int mypipe(int pipefd[2])
{
#if defined HAVE_PIPE
    /* Unix, Linux, and nice systems: just use pipe() */
    return pipe(pipefd);

#elif defined HAVE__PIPE && !defined _WIN32
    /* Systems with _pipe() but not pipe(). They probably don't even
     * exist, apart from Win32 which we handle a different way.
     * The pipe is created with NOINHERIT otherwise both parts are
     * inherited. We then duplicate the part we want. */
    int ret = _pipe(pipefd, 512, _O_BINARY | O_NOINHERIT);
    int tmp = _dup(pipefd[1]);
    close(pipefd[1]);
    pipefd[1] = tmp;
    return ret;

#elif defined _WIN32
    /* Windows: create a unique name for the pipe and use the Win32 API
     * to create it. Inspired by
     * http://www.daniweb.com/software-development/cpp/threads/295780/using-named-pipes-with-asynchronous-io-redirection-to-winapi */
    static int pipe_cnt = 0;
    char pipe_name[BUFSIZ];
    _snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\Pipe\\zzuf.%08x.%d",
              GetCurrentProcessId(), pipe_cnt++);

    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;

    /* At this time, the HANDLE is inheritable and can both read/write */
    HANDLE rpipe = CreateNamedPipeA(pipe_name,
                           PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
                           PIPE_TYPE_BYTE | PIPE_WAIT,
                           1, BUFSIZ, BUFSIZ, 0, &sa);

    /* Create a new handle for write access only; it must be inheritable */
    HANDLE wpipe = CreateFileA(pipe_name, GENERIC_WRITE, 0, &sa,
                               OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                               NULL);

    if (rpipe == INVALID_HANDLE_VALUE || wpipe == INVALID_HANDLE_VALUE)
        return -1;

    /* Create a new handle for the listener; not inheritable */
    HANDLE new_rpipe;
    if (!DuplicateHandle(GetCurrentProcess(), rpipe,
                         GetCurrentProcess(), &new_rpipe,
                         0, FALSE, DUPLICATE_SAME_ACCESS))
        return -1;

    /* Finally we can safetly close the pipe handle */
    CloseHandle(rpipe);

    /* Now we convert handle to fd */
    pipefd[0] = _open_osfhandle((intptr_t)new_rpipe, 0x0);
    pipefd[1] = _open_osfhandle((intptr_t)wpipe, 0x0);

    return 0;
#endif
}