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"
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/ipc_listener.h"
17 #include "ipc/ipc_message.h"
18 #include "ipc/ipc_test_base.h"
22 const char kDataBuffer
[] = "This is some test data to write to the file.";
24 // Returns the contents of the file represented by |h| as a std::string.
25 std::string
ReadFromFile(HANDLE h
) {
26 SetFilePointer(h
, 0, nullptr, FILE_BEGIN
);
29 BOOL success
= ::ReadFile(h
, buffer
, static_cast<DWORD
>(strlen(kDataBuffer
)),
30 &bytes_read
, nullptr);
31 return success
? std::string(buffer
, bytes_read
) : std::string();
34 HANDLE
GetHandleFromBrokeredAttachment(
35 const scoped_refptr
<IPC::BrokerableAttachment
>& attachment
) {
36 if (attachment
->GetType() !=
37 IPC::BrokerableAttachment::TYPE_BROKERABLE_ATTACHMENT
)
39 if (attachment
->GetBrokerableType() != IPC::BrokerableAttachment::WIN_HANDLE
)
41 IPC::internal::HandleAttachmentWin
* received_handle_attachment
=
42 static_cast<IPC::internal::HandleAttachmentWin
*>(attachment
.get());
43 return received_handle_attachment
->get_handle();
46 // Returns true if |attachment| is a file HANDLE whose contents is
48 bool CheckContentsOfBrokeredAttachment(
49 const scoped_refptr
<IPC::BrokerableAttachment
>& attachment
) {
50 HANDLE h
= GetHandleFromBrokeredAttachment(attachment
);
54 std::string contents
= ReadFromFile(h
);
55 return contents
== std::string(kDataBuffer
);
64 // Once the test is finished, send a control message to the parent process with
65 // the result. The message may require the runloop to be run before its
67 void SendControlMessage(IPC::Sender
* sender
, bool success
) {
68 IPC::Message
* message
= new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL
);
69 TestResult result
= success
? RESULT_SUCCESS
: RESULT_FAILURE
;
70 message
->WriteInt(result
);
71 sender
->Send(message
);
74 class MockObserver
: public IPC::AttachmentBroker::Observer
{
76 void ReceivedBrokerableAttachmentWithId(
77 const IPC::BrokerableAttachment::AttachmentId
& id
) override
{
80 IPC::BrokerableAttachment::AttachmentId
* get_id() { return &id_
; }
83 IPC::BrokerableAttachment::AttachmentId id_
;
86 // Forwards all messages to |listener_|. Quits the message loop after a
87 // message is received, or the channel has an error.
88 class ProxyListener
: public IPC::Listener
{
90 ProxyListener() : reason_(MESSAGE_RECEIVED
) {}
91 ~ProxyListener() override
{}
93 // The reason for exiting the message loop.
94 enum Reason
{ MESSAGE_RECEIVED
, CHANNEL_ERROR
};
96 bool OnMessageReceived(const IPC::Message
& message
) override
{
97 bool result
= listener_
->OnMessageReceived(message
);
98 reason_
= MESSAGE_RECEIVED
;
99 base::MessageLoop::current()->Quit();
103 void OnChannelError() override
{
104 reason_
= CHANNEL_ERROR
;
105 base::MessageLoop::current()->Quit();
108 void set_listener(IPC::Listener
* listener
) { listener_
= listener
; }
109 Reason
get_reason() { return reason_
; }
112 IPC::Listener
* listener_
;
116 // Waits for a result to be sent over the channel. Quits the message loop
117 // after a message is received, or the channel has an error.
118 class ResultListener
: public IPC::Listener
{
120 ResultListener() : result_(RESULT_UNKNOWN
) {}
121 ~ResultListener() override
{}
123 bool OnMessageReceived(const IPC::Message
& message
) override
{
124 base::PickleIterator
iter(message
);
127 EXPECT_TRUE(iter
.ReadInt(&result
));
128 result_
= static_cast<TestResult
>(result
);
132 TestResult
get_result() { return result_
; }
138 // The parent process acts as an unprivileged process. The forked process acts
139 // as the privileged process.
140 class IPCAttachmentBrokerPrivilegedWinTest
: public IPCTestBase
{
142 IPCAttachmentBrokerPrivilegedWinTest() : message_index_(0) {}
143 ~IPCAttachmentBrokerPrivilegedWinTest() override
{}
145 void SetUp() override
{
146 IPCTestBase::SetUp();
147 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
148 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_
.path(), &temp_path_
));
151 void TearDown() override
{ IPCTestBase::TearDown(); }
153 // Takes ownership of |broker|. Has no effect if called after CommonSetUp().
154 void set_broker(IPC::AttachmentBrokerUnprivilegedWin
* broker
) {
155 broker_
.reset(broker
);
160 set_broker(new IPC::AttachmentBrokerUnprivilegedWin
);
161 broker_
->AddObserver(&observer_
);
162 set_attachment_broker(broker_
.get());
163 CreateChannel(&proxy_listener_
);
164 broker_
->DesignateBrokerCommunicationChannel(channel());
165 ASSERT_TRUE(ConnectChannel());
166 ASSERT_TRUE(StartClient());
169 void CommonTearDown() {
170 // Close the channel so the client's OnChannelError() gets fired.
173 EXPECT_TRUE(WaitForClientShutdown());
178 HANDLE
CreateTempFile() {
179 EXPECT_NE(-1, WriteFile(temp_path_
, kDataBuffer
,
180 static_cast<int>(strlen(kDataBuffer
))));
183 CreateFile(temp_path_
.value().c_str(), GENERIC_READ
| GENERIC_WRITE
, 0,
184 nullptr, OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
185 EXPECT_NE(h
, INVALID_HANDLE_VALUE
);
189 void SendMessageWithAttachment(HANDLE h
) {
190 IPC::Message
* message
=
191 new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL
);
192 message
->WriteInt(message_index_
++);
193 scoped_refptr
<IPC::internal::HandleAttachmentWin
> attachment(
194 new IPC::internal::HandleAttachmentWin(h
));
195 ASSERT_TRUE(message
->WriteAttachment(attachment
));
196 sender()->Send(message
);
199 ProxyListener
* get_proxy_listener() { return &proxy_listener_
; }
200 IPC::AttachmentBrokerUnprivilegedWin
* get_broker() { return broker_
.get(); }
201 MockObserver
* get_observer() { return &observer_
; }
204 base::ScopedTempDir temp_dir_
;
205 base::FilePath temp_path_
;
207 ProxyListener proxy_listener_
;
208 scoped_ptr
<IPC::AttachmentBrokerUnprivilegedWin
> broker_
;
209 MockObserver observer_
;
212 // A broker which always sets the current process as the destination process
214 class MockBroker
: public IPC::AttachmentBrokerUnprivilegedWin
{
217 ~MockBroker() override
{}
218 bool SendAttachmentToProcess(const IPC::BrokerableAttachment
* attachment
,
219 base::ProcessId destination_process
) override
{
220 return IPC::AttachmentBrokerUnprivilegedWin::SendAttachmentToProcess(
221 attachment
, base::Process::Current().Pid());
225 // An unprivileged process makes a file HANDLE, and writes a string to it. The
226 // file HANDLE is sent to the privileged process using the attachment broker.
227 // The privileged process dups the HANDLE into its own HANDLE table. This test
228 // checks that the file has the same contents in the privileged process.
229 TEST_F(IPCAttachmentBrokerPrivilegedWinTest
, SendHandle
) {
233 ResultListener result_listener
;
234 get_proxy_listener()->set_listener(&result_listener
);
236 HANDLE h
= CreateTempFile();
237 SendMessageWithAttachment(h
);
238 base::MessageLoop::current()->Run();
241 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED
,
242 get_proxy_listener()->get_reason());
243 ASSERT_EQ(result_listener
.get_result(), RESULT_SUCCESS
);
248 // Similar to SendHandle, except the file HANDLE attached to the message has
249 // neither read nor write permissions.
250 TEST_F(IPCAttachmentBrokerPrivilegedWinTest
, SendHandleWithoutPermissions
) {
251 Init("SendHandleWithoutPermissions");
254 ResultListener result_listener
;
255 get_proxy_listener()->set_listener(&result_listener
);
257 HANDLE h
= CreateTempFile();
259 BOOL result
= ::DuplicateHandle(GetCurrentProcess(), h
, GetCurrentProcess(),
260 &h2
, 0, FALSE
, DUPLICATE_CLOSE_SOURCE
);
262 SendMessageWithAttachment(h2
);
263 base::MessageLoop::current()->Run();
266 ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED
,
267 get_proxy_listener()->get_reason());
268 ASSERT_EQ(result_listener
.get_result(), RESULT_SUCCESS
);
273 // Similar to SendHandle, except the attachment's destination process is this
274 // process. This is an unrealistic scenario, but simulates an unprivileged
275 // process sending an attachment to another unprivileged process.
276 TEST_F(IPCAttachmentBrokerPrivilegedWinTest
, SendHandleToSelf
) {
277 Init("SendHandleToSelf");
279 set_broker(new MockBroker
);
281 // Technically, the channel is an endpoint, but we need the proxy listener to
282 // receive the messages so that it can quit the message loop.
283 channel()->set_attachment_broker_endpoint(false);
284 get_proxy_listener()->set_listener(get_broker());
286 HANDLE h
= CreateTempFile();
287 SendMessageWithAttachment(h
);
288 base::MessageLoop::current()->Run();
290 // Get the received attachment.
291 IPC::BrokerableAttachment::AttachmentId
* id
= get_observer()->get_id();
292 scoped_refptr
<IPC::BrokerableAttachment
> received_attachment
;
293 get_broker()->GetAttachmentWithId(*id
, &received_attachment
);
294 ASSERT_NE(received_attachment
.get(), nullptr);
296 // Check that it's a new entry in the HANDLE table.
297 HANDLE h2
= GetHandleFromBrokeredAttachment(received_attachment
);
299 EXPECT_NE(h2
, nullptr);
301 // But it still points to the same file.
302 std::string contents
= ReadFromFile(h
);
303 EXPECT_EQ(contents
, std::string(kDataBuffer
));
308 using OnMessageReceivedCallback
=
309 void (*)(MockObserver
* observer
,
310 IPC::AttachmentBrokerPrivilegedWin
* broker
,
311 IPC::Sender
* sender
);
313 int CommonPrivilegedProcessMain(OnMessageReceivedCallback callback
,
314 const char* channel_name
) {
315 base::MessageLoopForIO main_message_loop
;
316 ProxyListener listener
;
318 // Set up IPC channel.
319 IPC::AttachmentBrokerPrivilegedWin broker
;
320 listener
.set_listener(&broker
);
321 scoped_ptr
<IPC::Channel
> channel(IPC::Channel::CreateClient(
322 IPCTestBase::GetChannelName(channel_name
), &listener
, &broker
));
323 broker
.RegisterCommunicationChannel(channel
.get());
324 CHECK(channel
->Connect());
326 MockObserver observer
;
327 broker
.AddObserver(&observer
);
330 base::MessageLoop::current()->Run();
331 ProxyListener::Reason reason
= listener
.get_reason();
332 if (reason
== ProxyListener::CHANNEL_ERROR
)
335 callback(&observer
, &broker
, channel
.get());
341 void SendHandleCallback(MockObserver
* observer
,
342 IPC::AttachmentBrokerPrivilegedWin
* broker
,
343 IPC::Sender
* sender
) {
344 IPC::BrokerableAttachment::AttachmentId
* id
= observer
->get_id();
345 scoped_refptr
<IPC::BrokerableAttachment
> received_attachment
;
346 broker
->GetAttachmentWithId(*id
, &received_attachment
);
348 // Check that it's the expected handle.
349 bool success
= CheckContentsOfBrokeredAttachment(received_attachment
);
351 SendControlMessage(sender
, success
);
354 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandle
) {
355 return CommonPrivilegedProcessMain(&SendHandleCallback
, "SendHandle");
358 void SendHandleWithoutPermissionsCallback(
359 MockObserver
* observer
,
360 IPC::AttachmentBrokerPrivilegedWin
* broker
,
361 IPC::Sender
* sender
) {
362 IPC::BrokerableAttachment::AttachmentId
* id
= observer
->get_id();
363 scoped_refptr
<IPC::BrokerableAttachment
> received_attachment
;
364 broker
->GetAttachmentWithId(*id
, &received_attachment
);
366 // Check that it's the expected handle.
367 HANDLE h
= GetHandleFromBrokeredAttachment(received_attachment
);
369 SetFilePointer(h
, 0, nullptr, FILE_BEGIN
);
374 ::ReadFile(h
, buffer
, static_cast<DWORD
>(strlen(kDataBuffer
)),
375 &bytes_read
, nullptr);
376 if (!success
&& GetLastError() == ERROR_ACCESS_DENIED
) {
377 SendControlMessage(sender
, true);
382 SendControlMessage(sender
, false);
385 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWithoutPermissions
) {
386 return CommonPrivilegedProcessMain(&SendHandleWithoutPermissionsCallback
,
387 "SendHandleWithoutPermissions");
390 void SendHandleToSelfCallback(MockObserver
* observer
,
391 IPC::AttachmentBrokerPrivilegedWin
* broker
,
392 IPC::Sender
* sender
) {
393 // Do nothing special. The default behavior already runs the
394 // AttachmentBrokerPrivilegedWin.
397 MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleToSelf
) {
398 return CommonPrivilegedProcessMain(&SendHandleToSelfCallback
,