1// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "sandbox/win/src/named_pipe_interception.h"
6
7#include "sandbox/win/src/crosscall_client.h"
8#include "sandbox/win/src/ipc_tags.h"
9#include "sandbox/win/src/policy_params.h"
10#include "sandbox/win/src/policy_target.h"
11#include "sandbox/win/src/sandbox_factory.h"
12#include "sandbox/win/src/sandbox_nt_util.h"
13#include "sandbox/win/src/sharedmem_ipc_client.h"
14#include "sandbox/win/src/target_services.h"
15
16namespace sandbox {
17
18HANDLE WINAPI TargetCreateNamedPipeW(
19    CreateNamedPipeWFunction orig_CreateNamedPipeW, LPCWSTR pipe_name,
20    DWORD open_mode, DWORD pipe_mode, DWORD max_instance, DWORD out_buffer_size,
21    DWORD in_buffer_size, DWORD default_timeout,
22    LPSECURITY_ATTRIBUTES security_attributes) {
23  HANDLE pipe = orig_CreateNamedPipeW(pipe_name, open_mode, pipe_mode,
24                                      max_instance, out_buffer_size,
25                                      in_buffer_size, default_timeout,
26                                      security_attributes);
27  if (INVALID_HANDLE_VALUE != pipe)
28    return pipe;
29
30  // We don't trust that the IPC can work this early.
31  if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
32    return INVALID_HANDLE_VALUE;
33
34  DWORD original_error = ::GetLastError();
35
36  // We don't support specific Security Attributes.
37  if (security_attributes)
38    return INVALID_HANDLE_VALUE;
39
40  do {
41    void* memory = GetGlobalIPCMemory();
42    if (NULL == memory)
43      break;
44
45    CountedParameterSet<NameBased> params;
46    params[NameBased::NAME] = ParamPickerMake(pipe_name);
47
48    if (!QueryBroker(IPC_CREATENAMEDPIPEW_TAG, params.GetBase()))
49      break;
50
51    SharedMemIPCClient ipc(memory);
52    CrossCallReturn answer = {0};
53    ResultCode code = CrossCall(ipc, IPC_CREATENAMEDPIPEW_TAG, pipe_name,
54                                open_mode, pipe_mode, max_instance,
55                                out_buffer_size, in_buffer_size,
56                                default_timeout, &answer);
57    if (SBOX_ALL_OK != code)
58      break;
59
60    ::SetLastError(answer.win32_result);
61
62    if (ERROR_SUCCESS != answer.win32_result)
63      return INVALID_HANDLE_VALUE;
64
65    return answer.handle;
66  } while (false);
67
68  ::SetLastError(original_error);
69  return INVALID_HANDLE_VALUE;
70}
71
72}  // namespace sandbox
73