Update V8 to version 4.7.24.
[chromium-blink-merge.git] / ipc / attachment_broker_privileged_win_unittest.cc
blob6e8f8814371c58eb0481096ae1b73d9b85840b6b
1 // Copyright 2015 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.
5 #include "build/build_config.h"
7 #include <windows.h>
9 #include "base/files/file_path.h"
10 #include "base/files/file_util.h"
11 #include "base/files/scoped_temp_dir.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "ipc/attachment_broker_privileged_win.h"
14 #include "ipc/attachment_broker_unprivileged_win.h"
15 #include "ipc/handle_attachment_win.h"
16 #include "ipc/handle_win.h"
17 #include "ipc/ipc_listener.h"
18 #include "ipc/ipc_message.h"
19 #include "ipc/ipc_test_base.h"
21 namespace {
23 const char kDataBuffer[] = "This is some test data to write to the file.";
25 // Returns the contents of the file represented by |h| as a std::string.
26 std::string ReadFromFile(HANDLE h) {
27 SetFilePointer(h, 0, nullptr, FILE_BEGIN);
28 char buffer[100];
29 DWORD bytes_read;
30 BOOL success = ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)),
31 &bytes_read, nullptr);
32 return success ? std::string(buffer, bytes_read) : std::string();
35 HANDLE GetHandleFromBrokeredAttachment(
36 const scoped_refptr<IPC::BrokerableAttachment>& attachment) {
37 if (attachment->GetType() !=
38 IPC::BrokerableAttachment::TYPE_BROKERABLE_ATTACHMENT)
39 return nullptr;
40 if (attachment->GetBrokerableType() != IPC::BrokerableAttachment::WIN_HANDLE)
41 return nullptr;
42 IPC::internal::HandleAttachmentWin* received_handle_attachment =
43 static_cast<IPC::internal::HandleAttachmentWin*>(attachment.get());
44 return received_handle_attachment->get_handle();
47 // Returns true if |attachment| is a file HANDLE whose contents is
48 // |kDataBuffer|.
49 bool CheckContentsOfBrokeredAttachment(
50 const scoped_refptr<IPC::BrokerableAttachment>& attachment) {
51 HANDLE h = GetHandleFromBrokeredAttachment(attachment);
52 if (h == nullptr)
53 return false;
55 std::string contents = ReadFromFile(h);
56 return contents == std::string(kDataBuffer);
59 enum TestResult {
60 RESULT_UNKNOWN,
61 RESULT_SUCCESS,
62 RESULT_FAILURE,
65 // Once the test is finished, send a control message to the parent process with
66 // the result. The message may require the runloop to be run before its
67 // dispatched.
68 void SendControlMessage(IPC::Sender* sender, bool success) {
69 IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
70 TestResult result = success ? RESULT_SUCCESS : RESULT_FAILURE;
71 message->WriteInt(result);
72 sender->Send(message);
75 class MockObserver : public IPC::AttachmentBroker::Observer {
76 public:
77 void ReceivedBrokerableAttachmentWithId(
78 const IPC::BrokerableAttachment::AttachmentId& id) override {
79 id_ = id;
81 IPC::BrokerableAttachment::AttachmentId* get_id() { return &id_; }
83 private:
84 IPC::BrokerableAttachment::AttachmentId id_;
87 // Forwards all messages to |listener_|. Quits the message loop after a
88 // message is received, or the channel has an error.
89 class ProxyListener : public IPC::Listener {
90 public:
91 ProxyListener() : reason_(MESSAGE_RECEIVED) {}
92 ~ProxyListener() override {}
94 // The reason for exiting the message loop.
95 enum Reason { MESSAGE_RECEIVED, CHANNEL_ERROR };
97 bool OnMessageReceived(const IPC::Message& message) override {
98 bool result = listener_->OnMessageReceived(message);
99 reason_ = MESSAGE_RECEIVED;
100 base::MessageLoop::current()->Quit();
101 return result;
104 void OnChannelError() override {
105 reason_ = CHANNEL_ERROR;
106 base::MessageLoop::current()->Quit();
109 void set_listener(IPC::Listener* listener) { listener_ = listener; }
110 Reason get_reason() { return reason_; }
112 private:
113 IPC::Listener* listener_;
114 Reason reason_;
117 // Waits for a result to be sent over the channel. Quits the message loop
118 // after a message is received, or the channel has an error.
119 class ResultListener : public IPC::Listener {
120 public:
121 ResultListener() : result_(RESULT_UNKNOWN) {}
122 ~ResultListener() override {}
124 bool OnMessageReceived(const IPC::Message& message) override {
125 base::PickleIterator iter(message);
127 int result;
128 EXPECT_TRUE(iter.ReadInt(&result));
129 result_ = static_cast<TestResult>(result);
130 return true;
133 TestResult get_result() { return result_; }
135 private:
136 TestResult result_;
139 // The parent process acts as an unprivileged process. The forked process acts
140 // as the privileged process.
141 class IPCAttachmentBrokerPrivilegedWinTest : public IPCTestBase {
142 public:
143 IPCAttachmentBrokerPrivilegedWinTest() : message_index_(0) {}
144 ~IPCAttachmentBrokerPrivilegedWinTest() override {}
146 void SetUp() override {
147 IPCTestBase::SetUp();
148 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
149 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(), &temp_path_));
152 void TearDown() override { IPCTestBase::TearDown(); }
154 // Takes ownership of |broker|. Has no effect if called after CommonSetUp().
155 void set_broker(IPC::AttachmentBrokerUnprivilegedWin* broker) {
156 broker_.reset(broker);
159 void CommonSetUp() {
160 if (!broker_.get())
161 set_broker(new IPC::AttachmentBrokerUnprivilegedWin);
162 broker_->AddObserver(&observer_);
163 set_attachment_broker(broker_.get());
164 CreateChannel(&proxy_listener_);
165 broker_->DesignateBrokerCommunicationChannel(channel());
166 ASSERT_TRUE(ConnectChannel());
167 ASSERT_TRUE(StartClient());
170 void CommonTearDown() {
171 // Close the channel so the client's OnChannelError() gets fired.
172 channel()->Close();
174 EXPECT_TRUE(WaitForClientShutdown());
175 DestroyChannel();
176 broker_.reset();
179 HANDLE CreateTempFile() {
180 EXPECT_NE(-1, WriteFile(temp_path_, kDataBuffer,
181 static_cast<int>(strlen(kDataBuffer))));
183 HANDLE h =
184 CreateFile(temp_path_.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0,
185 nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
186 EXPECT_NE(h, INVALID_HANDLE_VALUE);
187 return h;
190 void SendMessageWithAttachment(HANDLE h) {
191 IPC::Message* message =
192 new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
193 message->WriteInt(message_index_++);
194 scoped_refptr<IPC::internal::HandleAttachmentWin> attachment(
195 new IPC::internal::HandleAttachmentWin(h, IPC::HandleWin::DUPLICATE));
196 ASSERT_TRUE(message->WriteAttachment(attachment));
197 sender()->Send(message);
200 ProxyListener* get_proxy_listener() { return &proxy_listener_; }
201 IPC::AttachmentBrokerUnprivilegedWin* get_broker() { return broker_.get(); }
202 MockObserver* get_observer() { return &observer_; }
204 private:
205 base::ScopedTempDir temp_dir_;
206 base::FilePath temp_path_;
207 int message_index_;
208 ProxyListener proxy_listener_;
209 scoped_ptr<IPC::AttachmentBrokerUnprivilegedWin> broker_;
210 MockObserver observer_;
213 // A broker which always sets the current process as the destination process
214 // for attachments.
215 class MockBroker : public IPC::AttachmentBrokerUnprivilegedWin {
216 public:
217 MockBroker() {}
218 ~MockBroker() override {}
219 bool SendAttachmentToProcess(const IPC::BrokerableAttachment* attachment,
220 base::ProcessId destination_process) override {
221 return IPC::AttachmentBrokerUnprivilegedWin::SendAttachmentToProcess(
222 attachment, base::Process::Current().Pid());
226 // An unprivileged process makes a file HANDLE, and writes a string to it. The
227 // file HANDLE is sent to the privileged process using the attachment broker.
228 // The privileged process dups the HANDLE into its own HANDLE table. This test
229 // checks that the file has the same contents in the privileged process.
230 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandle) {
231 Init("SendHandle");
233 CommonSetUp();
234 ResultListener result_listener;
235 get_proxy_listener()->set_listener(&result_listener);
237 HANDLE h = CreateTempFile();
238 SendMessageWithAttachment(h);
239 base::MessageLoop::current()->Run();
241 // Check the result.
242 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
243 get_proxy_listener()->get_reason());
244 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
246 CommonTearDown();
249 // Similar to SendHandle, except the file HANDLE attached to the message has
250 // neither read nor write permissions.
251 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandleWithoutPermissions) {
252 Init("SendHandleWithoutPermissions");
254 CommonSetUp();
255 ResultListener result_listener;
256 get_proxy_listener()->set_listener(&result_listener);
258 HANDLE h = CreateTempFile();
259 HANDLE h2;
260 BOOL result = ::DuplicateHandle(GetCurrentProcess(), h, GetCurrentProcess(),
261 &h2, 0, FALSE, DUPLICATE_CLOSE_SOURCE);
262 ASSERT_TRUE(result);
263 SendMessageWithAttachment(h2);
264 base::MessageLoop::current()->Run();
266 // Check the result.
267 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
268 get_proxy_listener()->get_reason());
269 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
271 CommonTearDown();
274 // Similar to SendHandle, except the attachment's destination process is this
275 // process. This is an unrealistic scenario, but simulates an unprivileged
276 // process sending an attachment to another unprivileged process.
277 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandleToSelf) {
278 Init("SendHandleToSelf");
280 set_broker(new MockBroker);
281 CommonSetUp();
282 // Technically, the channel is an endpoint, but we need the proxy listener to
283 // receive the messages so that it can quit the message loop.
284 channel()->SetAttachmentBrokerEndpoint(false);
285 get_proxy_listener()->set_listener(get_broker());
287 HANDLE h = CreateTempFile();
288 SendMessageWithAttachment(h);
289 base::MessageLoop::current()->Run();
291 // Get the received attachment.
292 IPC::BrokerableAttachment::AttachmentId* id = get_observer()->get_id();
293 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
294 get_broker()->GetAttachmentWithId(*id, &received_attachment);
295 ASSERT_NE(received_attachment.get(), nullptr);
297 // Check that it's a new entry in the HANDLE table.
298 HANDLE h2 = GetHandleFromBrokeredAttachment(received_attachment);
299 EXPECT_NE(h2, h);
300 EXPECT_NE(h2, nullptr);
302 // But it still points to the same file.
303 std::string contents = ReadFromFile(h);
304 EXPECT_EQ(contents, std::string(kDataBuffer));
306 CommonTearDown();
309 // Similar to SendHandle, except this test uses the HandleWin class.
310 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandleWin) {
311 Init("SendHandleWin");
313 CommonSetUp();
314 ResultListener result_listener;
315 get_proxy_listener()->set_listener(&result_listener);
317 HANDLE h = CreateTempFile();
318 IPC::HandleWin handle_win(h, IPC::HandleWin::FILE_READ_WRITE);
319 IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
320 message->WriteInt(0);
321 IPC::ParamTraits<IPC::HandleWin>::Write(message, handle_win);
322 sender()->Send(message);
323 base::MessageLoop::current()->Run();
325 // Check the result.
326 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
327 get_proxy_listener()->get_reason());
328 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
330 CommonTearDown();
333 using OnMessageReceivedCallback =
334 void (*)(MockObserver* observer,
335 IPC::AttachmentBrokerPrivilegedWin* broker,
336 IPC::Sender* sender);
338 int CommonPrivilegedProcessMain(OnMessageReceivedCallback callback,
339 const char* channel_name) {
340 base::MessageLoopForIO main_message_loop;
341 ProxyListener listener;
343 // Set up IPC channel.
344 IPC::AttachmentBrokerPrivilegedWin broker;
345 listener.set_listener(&broker);
346 scoped_ptr<IPC::Channel> channel(IPC::Channel::CreateClient(
347 IPCTestBase::GetChannelName(channel_name), &listener, &broker));
348 broker.RegisterCommunicationChannel(channel.get());
349 CHECK(channel->Connect());
351 MockObserver observer;
352 broker.AddObserver(&observer);
354 while (true) {
355 base::MessageLoop::current()->Run();
356 ProxyListener::Reason reason = listener.get_reason();
357 if (reason == ProxyListener::CHANNEL_ERROR)
358 break;
360 callback(&observer, &broker, channel.get());
363 return 0;
366 void SendHandleCallback(MockObserver* observer,
367 IPC::AttachmentBrokerPrivilegedWin* broker,
368 IPC::Sender* sender) {
369 IPC::BrokerableAttachment::AttachmentId* id = observer->get_id();
370 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
371 broker->GetAttachmentWithId(*id, &received_attachment);
373 // Check that it's the expected handle.
374 bool success = CheckContentsOfBrokeredAttachment(received_attachment);
376 SendControlMessage(sender, success);
379 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandle) {
380 return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandle");
383 void SendHandleWithoutPermissionsCallback(
384 MockObserver* observer,
385 IPC::AttachmentBrokerPrivilegedWin* broker,
386 IPC::Sender* sender) {
387 IPC::BrokerableAttachment::AttachmentId* id = observer->get_id();
388 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
389 broker->GetAttachmentWithId(*id, &received_attachment);
391 // Check that it's the expected handle.
392 HANDLE h = GetHandleFromBrokeredAttachment(received_attachment);
393 if (h != nullptr) {
394 SetFilePointer(h, 0, nullptr, FILE_BEGIN);
396 char buffer[100];
397 DWORD bytes_read;
398 BOOL success =
399 ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)),
400 &bytes_read, nullptr);
401 if (!success && GetLastError() == ERROR_ACCESS_DENIED) {
402 SendControlMessage(sender, true);
403 return;
407 SendControlMessage(sender, false);
410 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWithoutPermissions) {
411 return CommonPrivilegedProcessMain(&SendHandleWithoutPermissionsCallback,
412 "SendHandleWithoutPermissions");
415 void SendHandleToSelfCallback(MockObserver* observer,
416 IPC::AttachmentBrokerPrivilegedWin* broker,
417 IPC::Sender* sender) {
418 // Do nothing special. The default behavior already runs the
419 // AttachmentBrokerPrivilegedWin.
422 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleToSelf) {
423 return CommonPrivilegedProcessMain(&SendHandleToSelfCallback,
424 "SendHandleToSelf");
427 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWin) {
428 return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandleWin");
431 } // namespace