Roll src/third_party/WebKit 6c137a7:4aace46 (svn 202008:202009)
[chromium-blink-merge.git] / ipc / attachment_broker_privileged_win_unittest.cc
blob2e46f2b42865591a92e07580c064ee2e6c1350c7
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, DISABLED_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,
252 DISABLED_SendHandleWithoutPermissions) {
253 Init("SendHandleWithoutPermissions");
255 CommonSetUp();
256 ResultListener result_listener;
257 get_proxy_listener()->set_listener(&result_listener);
259 HANDLE h = CreateTempFile();
260 HANDLE h2;
261 BOOL result = ::DuplicateHandle(GetCurrentProcess(), h, GetCurrentProcess(),
262 &h2, 0, FALSE, DUPLICATE_CLOSE_SOURCE);
263 ASSERT_TRUE(result);
264 SendMessageWithAttachment(h2);
265 base::MessageLoop::current()->Run();
267 // Check the result.
268 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
269 get_proxy_listener()->get_reason());
270 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
272 CommonTearDown();
275 // Similar to SendHandle, except the attachment's destination process is this
276 // process. This is an unrealistic scenario, but simulates an unprivileged
277 // process sending an attachment to another unprivileged process.
278 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandleToSelf) {
279 Init("SendHandleToSelf");
281 set_broker(new MockBroker);
282 CommonSetUp();
283 // Technically, the channel is an endpoint, but we need the proxy listener to
284 // receive the messages so that it can quit the message loop.
285 channel()->SetAttachmentBrokerEndpoint(false);
286 get_proxy_listener()->set_listener(get_broker());
288 HANDLE h = CreateTempFile();
289 SendMessageWithAttachment(h);
290 base::MessageLoop::current()->Run();
292 // Get the received attachment.
293 IPC::BrokerableAttachment::AttachmentId* id = get_observer()->get_id();
294 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
295 get_broker()->GetAttachmentWithId(*id, &received_attachment);
296 ASSERT_NE(received_attachment.get(), nullptr);
298 // Check that it's a new entry in the HANDLE table.
299 HANDLE h2 = GetHandleFromBrokeredAttachment(received_attachment);
300 EXPECT_NE(h2, h);
301 EXPECT_NE(h2, nullptr);
303 // But it still points to the same file.
304 std::string contents = ReadFromFile(h);
305 EXPECT_EQ(contents, std::string(kDataBuffer));
307 CommonTearDown();
310 // Similar to SendHandle, except this test uses the HandleWin class.
311 TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandleWin) {
312 Init("SendHandleWin");
314 CommonSetUp();
315 ResultListener result_listener;
316 get_proxy_listener()->set_listener(&result_listener);
318 HANDLE h = CreateTempFile();
319 IPC::HandleWin handle_win(h, IPC::HandleWin::FILE_READ_WRITE);
320 IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL);
321 message->WriteInt(0);
322 IPC::ParamTraits<IPC::HandleWin>::Write(message, handle_win);
323 sender()->Send(message);
324 base::MessageLoop::current()->Run();
326 // Check the result.
327 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED,
328 get_proxy_listener()->get_reason());
329 ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS);
331 CommonTearDown();
334 using OnMessageReceivedCallback =
335 void (*)(MockObserver* observer,
336 IPC::AttachmentBrokerPrivilegedWin* broker,
337 IPC::Sender* sender);
339 int CommonPrivilegedProcessMain(OnMessageReceivedCallback callback,
340 const char* channel_name) {
341 base::MessageLoopForIO main_message_loop;
342 ProxyListener listener;
344 // Set up IPC channel.
345 IPC::AttachmentBrokerPrivilegedWin broker;
346 listener.set_listener(&broker);
347 scoped_ptr<IPC::Channel> channel(IPC::Channel::CreateClient(
348 IPCTestBase::GetChannelName(channel_name), &listener, &broker));
349 broker.RegisterCommunicationChannel(channel.get());
350 CHECK(channel->Connect());
352 MockObserver observer;
353 broker.AddObserver(&observer);
355 while (true) {
356 base::MessageLoop::current()->Run();
357 ProxyListener::Reason reason = listener.get_reason();
358 if (reason == ProxyListener::CHANNEL_ERROR)
359 break;
361 callback(&observer, &broker, channel.get());
364 return 0;
367 void SendHandleCallback(MockObserver* observer,
368 IPC::AttachmentBrokerPrivilegedWin* broker,
369 IPC::Sender* sender) {
370 IPC::BrokerableAttachment::AttachmentId* id = observer->get_id();
371 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
372 broker->GetAttachmentWithId(*id, &received_attachment);
374 // Check that it's the expected handle.
375 bool success = CheckContentsOfBrokeredAttachment(received_attachment);
377 SendControlMessage(sender, success);
380 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandle) {
381 return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandle");
384 void SendHandleWithoutPermissionsCallback(
385 MockObserver* observer,
386 IPC::AttachmentBrokerPrivilegedWin* broker,
387 IPC::Sender* sender) {
388 IPC::BrokerableAttachment::AttachmentId* id = observer->get_id();
389 scoped_refptr<IPC::BrokerableAttachment> received_attachment;
390 broker->GetAttachmentWithId(*id, &received_attachment);
392 // Check that it's the expected handle.
393 HANDLE h = GetHandleFromBrokeredAttachment(received_attachment);
394 if (h != nullptr) {
395 SetFilePointer(h, 0, nullptr, FILE_BEGIN);
397 char buffer[100];
398 DWORD bytes_read;
399 BOOL success =
400 ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)),
401 &bytes_read, nullptr);
402 if (!success && GetLastError() == ERROR_ACCESS_DENIED) {
403 SendControlMessage(sender, true);
404 return;
408 SendControlMessage(sender, false);
411 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWithoutPermissions) {
412 return CommonPrivilegedProcessMain(&SendHandleWithoutPermissionsCallback,
413 "SendHandleWithoutPermissions");
416 void SendHandleToSelfCallback(MockObserver* observer,
417 IPC::AttachmentBrokerPrivilegedWin* broker,
418 IPC::Sender* sender) {
419 // Do nothing special. The default behavior already runs the
420 // AttachmentBrokerPrivilegedWin.
423 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleToSelf) {
424 return CommonPrivilegedProcessMain(&SendHandleToSelfCallback,
425 "SendHandleToSelf");
428 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWin) {
429 return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandleWin");
432 } // namespace