File: elevated_tracing_service_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (365 lines) | stat: -rw-r--r-- 13,316 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <objbase.h>

#include <windows.h>

#include <shlobj.h>
#include <wrl/client.h>

#include <string_view>
#include <utility>

#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/process/process.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/multiprocess_test.h"
#include "base/test/task_environment.h"
#include "base/win/elevation_util.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/win_util.h"
#include "chrome/windows_services/elevated_tracing_service/system_tracing_session.h"
#include "chrome/windows_services/elevated_tracing_service/tracing_service_idl.h"
#include "chrome/windows_services/service_program/test_support/scoped_medium_integrity.h"
#include "chrome/windows_services/service_program/test_support/service_environment.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/platform/named_platform_channel.h"
#include "mojo/public/cpp/system/invitation.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"

namespace {

void TestGetServiceProcessHandle() {
  base::test::SingleThreadTaskEnvironment task_environment;

  Microsoft::WRL::ComPtr<IUnknown> unknown;
  ASSERT_HRESULT_SUCCEEDED(::CoCreateInstance(
      elevated_tracing_service::kTestSystemTracingSessionClsid, nullptr,
      CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&unknown)));

  Microsoft::WRL::ComPtr<ISystemTraceSession> trace_session;
  ASSERT_HRESULT_SUCCEEDED(unknown.As(&trace_session));
  unknown.Reset();

  ASSERT_HRESULT_SUCCEEDED(::CoSetProxyBlanket(
      trace_session.Get(), RPC_C_AUTHN_DEFAULT, RPC_C_AUTHZ_DEFAULT,
      COLE_DEFAULT_PRINCIPAL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
      RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_DYNAMIC_CLOAKING));

  mojo::NamedPlatformChannel channel(mojo::NamedPlatformChannel::Options{});
  mojo::OutgoingInvitation invitation;
  invitation.set_extra_flags(MOJO_SEND_INVITATION_FLAG_ELEVATED);
  mojo::ScopedMessagePipeHandle pipe = invitation.AttachMessagePipe(/*name=*/0);

  DWORD pid = base::kNullProcessId;
  ASSERT_HRESULT_SUCCEEDED(
      trace_session->AcceptInvitation(channel.GetServerName().c_str(), &pid));
  ASSERT_NE(pid, base::kNullProcessId);

  mojo::OutgoingInvitation::Send(std::move(invitation),
                                 /*target_process=*/base::kNullProcessHandle,
                                 channel.TakeServerEndpoint());

  // Wait for the service to connect to the pipe.
  mojo::SimpleWatcher pipe_watcher(FROM_HERE,
                                   mojo::SimpleWatcher::ArmingPolicy::MANUAL);
  base::RunLoop run_loop;
  ASSERT_EQ(
      pipe_watcher.Watch(
          pipe.get(),
          MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
          MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
          base::BindLambdaForTesting(
              [quit_closure = run_loop.QuitClosure()](
                  MojoResult result, const mojo::HandleSignalsState& state) {
                EXPECT_EQ(result, MOJO_RESULT_OK);
                EXPECT_EQ(state.satisfied_signals, MOJO_HANDLE_SIGNAL_WRITABLE);
                quit_closure.Run();
              })),
      MOJO_RESULT_OK);
  pipe_watcher.ArmOrNotify();
  run_loop.Run();

  // Releasing `trace_session` will trigger termination in the service.
}

// Tests that AcceptInvitation refuses a second invitation from a client.
void TestOnlyOneInvitation() {
  // Create a session and activate it by sending an invitation.
  Microsoft::WRL::ComPtr<IUnknown> unknown;
  ASSERT_HRESULT_SUCCEEDED(::CoCreateInstance(
      elevated_tracing_service::kTestSystemTracingSessionClsid, nullptr,
      CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&unknown)));

  Microsoft::WRL::ComPtr<ISystemTraceSession> trace_session;
  ASSERT_HRESULT_SUCCEEDED(unknown.As(&trace_session));
  unknown.Reset();

  ASSERT_HRESULT_SUCCEEDED(::CoSetProxyBlanket(
      trace_session.Get(), RPC_C_AUTHN_DEFAULT, RPC_C_AUTHZ_DEFAULT,
      COLE_DEFAULT_PRINCIPAL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
      RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_DYNAMIC_CLOAKING));

  mojo::ScopedMessagePipeHandle pipe;
  {
    mojo::NamedPlatformChannel channel(mojo::NamedPlatformChannel::Options{});
    mojo::OutgoingInvitation invitation;
    invitation.set_extra_flags(MOJO_SEND_INVITATION_FLAG_ELEVATED);
    pipe = invitation.AttachMessagePipe(/*name=*/0);

    DWORD pid = base::kNullProcessId;
    ASSERT_HRESULT_SUCCEEDED(
        trace_session->AcceptInvitation(channel.GetServerName().c_str(), &pid));
    ASSERT_NE(pid, base::kNullProcessId);

    mojo::OutgoingInvitation::Send(std::move(invitation),
                                   /*target_process=*/base::kNullProcessHandle,
                                   channel.TakeServerEndpoint());
  }

  {
    mojo::NamedPlatformChannel channel(mojo::NamedPlatformChannel::Options{});
    mojo::OutgoingInvitation invitation;
    invitation.set_extra_flags(MOJO_SEND_INVITATION_FLAG_ELEVATED);
    mojo::ScopedMessagePipeHandle pipe2 =
        invitation.AttachMessagePipe(/*name=*/0);

    DWORD pid = base::kNullProcessId;
    ASSERT_EQ(
        trace_session->AcceptInvitation(channel.GetServerName().c_str(), &pid),
        kErrorSessionAlreadyActive);
  }
}

// Tests that a second session is refused while a first is active.
void TestOnlyOneSession() {
  // Create a session and activate it by sending an invitation.
  Microsoft::WRL::ComPtr<IUnknown> unknown;
  ASSERT_HRESULT_SUCCEEDED(::CoCreateInstance(
      elevated_tracing_service::kTestSystemTracingSessionClsid, nullptr,
      CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&unknown)));

  Microsoft::WRL::ComPtr<ISystemTraceSession> trace_session;
  ASSERT_HRESULT_SUCCEEDED(unknown.As(&trace_session));
  unknown.Reset();

  ASSERT_HRESULT_SUCCEEDED(::CoSetProxyBlanket(
      trace_session.Get(), RPC_C_AUTHN_DEFAULT, RPC_C_AUTHZ_DEFAULT,
      COLE_DEFAULT_PRINCIPAL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
      RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_DYNAMIC_CLOAKING));

  mojo::ScopedMessagePipeHandle pipe;
  {
    mojo::NamedPlatformChannel channel(mojo::NamedPlatformChannel::Options{});
    mojo::OutgoingInvitation invitation;
    invitation.set_extra_flags(MOJO_SEND_INVITATION_FLAG_ELEVATED);
    pipe = invitation.AttachMessagePipe(/*name=*/0);

    DWORD pid = base::kNullProcessId;
    ASSERT_HRESULT_SUCCEEDED(
        trace_session->AcceptInvitation(channel.GetServerName().c_str(), &pid));
    ASSERT_NE(pid, base::kNullProcessId);

    mojo::OutgoingInvitation::Send(std::move(invitation),
                                   /*target_process=*/base::kNullProcessHandle,
                                   channel.TakeServerEndpoint());
  }

  // Now a second client is refused.
  ASSERT_HRESULT_SUCCEEDED(::CoCreateInstance(
      elevated_tracing_service::kTestSystemTracingSessionClsid, nullptr,
      CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&unknown)));

  Microsoft::WRL::ComPtr<ISystemTraceSession> trace_session2;
  ASSERT_HRESULT_SUCCEEDED(unknown.As(&trace_session2));
  unknown.Reset();

  ASSERT_HRESULT_SUCCEEDED(::CoSetProxyBlanket(
      trace_session2.Get(), RPC_C_AUTHN_DEFAULT, RPC_C_AUTHZ_DEFAULT,
      COLE_DEFAULT_PRINCIPAL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
      RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_DYNAMIC_CLOAKING));

  mojo::NamedPlatformChannel channel(mojo::NamedPlatformChannel::Options{});
  mojo::OutgoingInvitation invitation;
  invitation.set_extra_flags(MOJO_SEND_INVITATION_FLAG_ELEVATED);
  mojo::ScopedMessagePipeHandle pipe2 =
      invitation.AttachMessagePipe(/*name=*/0);

  DWORD pid = base::kNullProcessId;
  ASSERT_EQ(
      trace_session2->AcceptInvitation(channel.GetServerName().c_str(), &pid),
      kErrorSessionInProgress);
}

MULTIPROCESS_TEST_MAIN(GetServiceProcessHandleInChild) {
  // base::debug::WaitForDebugger(30, /*silent=*/false);

  base::win::ScopedCOMInitializer com_initializer;
  if (!com_initializer.Succeeded()) {
    return 1;
  }

  TestGetServiceProcessHandle();

  return ::testing::Test::HasFailure() ? 1 : 0;
}

MULTIPROCESS_TEST_MAIN(OnlyOneInvitationInChild) {
  // base::debug::WaitForDebugger(30, /*silent=*/false);

  base::win::ScopedCOMInitializer com_initializer;
  if (!com_initializer.Succeeded()) {
    return 1;
  }

  TestOnlyOneInvitation();

  return ::testing::Test::HasFailure() ? 1 : 0;
}

MULTIPROCESS_TEST_MAIN(OnlyOneSessionInChild) {
  // base::debug::WaitForDebugger(30, /*silent=*/false);

  base::win::ScopedCOMInitializer com_initializer;
  if (!com_initializer.Succeeded()) {
    return 1;
  }

  TestOnlyOneSession();

  return ::testing::Test::HasFailure() ? 1 : 0;
}

// Relaunches the test process de-elevated; using the multi-process test
// facilitied to run the named function.
base::Process RunInChildDeElevated(std::string_view function_name) {
  base::CommandLine command_line =
      base::GetMultiProcessTestChildBaseCommandLine();
  command_line.AppendSwitchASCII(switches::kTestChildProcess, function_name);

  return base::win::RunDeElevated(command_line);
}

}  // namespace

// A test harness that installs the tracing service so that tests can call into
// it. The service's log output is redirected to the test process's stderr.
class TracingServiceTest : public ::testing::Test {
 protected:
  static void SetUpTestSuite() {
    if (!::IsUserAnAdmin()) {
      GTEST_SKIP() << "Test requires admin rights";
    }
    service_environment_ = new ServiceEnvironment(
        L"Test Tracing Service",
        FILE_PATH_LITERAL("elevated_tracing_service.exe"),
        elevated_tracing_service::switches::kSystemTracingClsIdForTestingSwitch,
        elevated_tracing_service::kTestSystemTracingSessionClsid,
        __uuidof(ISystemTraceSession));
    ASSERT_TRUE(service_environment_->is_valid());
  }

  static void TearDownTestSuite() {
    delete std::exchange(service_environment_, nullptr);
  }

 private:
  static ServiceEnvironment* service_environment_;
};

// static
ServiceEnvironment* TracingServiceTest::service_environment_ = nullptr;

// Tests calling into the service from the main test process itself after
// dropping to medium integrity level.
TEST_F(TracingServiceTest, GetServiceProcessHandle) {
  base::win::ScopedCOMInitializer com_initializer;
  ASSERT_TRUE(com_initializer.Succeeded());

  ScopedMediumIntegrity medium_integrity;
  ASSERT_TRUE(medium_integrity.Succeeded());

  TestGetServiceProcessHandle();
}

// Tests calling into the service from the main test process itself after
// dropping to medium integrity level.
TEST_F(TracingServiceTest, OnlyOneInvitation) {
  base::win::ScopedCOMInitializer com_initializer;
  ASSERT_TRUE(com_initializer.Succeeded());

  ScopedMediumIntegrity medium_integrity;
  ASSERT_TRUE(medium_integrity.Succeeded());

  TestOnlyOneInvitation();
}

// Tests calling into the service from the main test process itself after
// dropping to medium integrity level.
TEST_F(TracingServiceTest, OnlyOneSession) {
  base::win::ScopedCOMInitializer com_initializer;
  ASSERT_TRUE(com_initializer.Succeeded());

  ScopedMediumIntegrity medium_integrity;
  ASSERT_TRUE(medium_integrity.Succeeded());

  TestOnlyOneSession();
}

// Tests calling into the service from a de-elevated child process. This test is
// skipped if UAC is disabled.
TEST_F(TracingServiceTest, GetServiceProcessHandleInChild) {
  // Pro tip: Add --show-error-dialogs to the test's command line and put
  // base::debug::WaitForDebugger(30, /*silent=*/false); in
  // `GetServiceProcessHandleInChild()` to more easily debug in the child
  // process.
  auto child = RunInChildDeElevated("GetServiceProcessHandleInChild");

  if (!child.IsValid()) {
    GTEST_SKIP() << "Cannot de-elevate when UAC is disabled.";
  }
  int exit_code;
  ASSERT_TRUE(child.WaitForExit(&exit_code));
  ASSERT_EQ(exit_code, 0);
}

// Tests calling into the service from a de-elevated child process. This test is
// skipped if UAC is disabled.
TEST_F(TracingServiceTest, OnlyOneInvitationInChild) {
  // Pro tip: Add --show-error-dialogs to the test's command line and put
  // base::debug::WaitForDebugger(30, /*silent=*/false); in
  // `GetServiceProcessHandleInChild()` to more easily debug in the child
  // process.
  auto child = RunInChildDeElevated("OnlyOneInvitationInChild");

  if (!child.IsValid()) {
    GTEST_SKIP() << "Cannot de-elevate when UAC is disabled.";
  }
  int exit_code;
  ASSERT_TRUE(child.WaitForExit(&exit_code));
  ASSERT_EQ(exit_code, 0);
}

// Tests calling into the service from a de-elevated child process. This test is
// skipped if UAC is disabled.
TEST_F(TracingServiceTest, OnlyOneSessionInChild) {
  // Pro tip: Add --show-error-dialogs to the test's command line and put
  // base::debug::WaitForDebugger(30, /*silent=*/false); in
  // `GetServiceProcessHandleInChild()` to more easily debug in the child
  // process.
  auto child = RunInChildDeElevated("OnlyOneSessionInChild");

  if (!child.IsValid()) {
    GTEST_SKIP() << "Cannot de-elevate when UAC is disabled.";
  }
  int exit_code;
  ASSERT_TRUE(child.WaitForExit(&exit_code));
  ASSERT_EQ(exit_code, 0);
}