summaryrefslogtreecommitdiffstats
path: root/security/sandbox/chromium/sandbox/win/src/app_container_test.cc
blob: a6c0948a942685b2544dbd93f4749e20b673bd66 (plain)
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>

#include <sddl.h>

#include <memory>
#include <string>
#include <vector>

#include "base/rand_util.h"
#include "base/strings/stringprintf.h"
#include "base/win/scoped_handle.h"
#include "base/win/scoped_process_information.h"
#include "base/win/windows_version.h"
#include "sandbox/win/src/app_container_profile_base.h"
#include "sandbox/win/src/sync_policy_test.h"
#include "sandbox/win/src/win_utils.h"
#include "sandbox/win/tests/common/controller.h"
#include "sandbox/win/tests/common/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace sandbox {

namespace {

const wchar_t kAppContainerSid[] =
    L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
    L"924012148-2839372144";

std::wstring GenerateRandomPackageName() {
  return base::StringPrintf(L"%016lX%016lX", base::RandUint64(),
                            base::RandUint64());
}

const char* TokenTypeToName(TOKEN_TYPE token_type) {
  return token_type == ::TokenPrimary ? "Primary Token" : "Impersonation Token";
}

void CheckToken(HANDLE token,
                TOKEN_TYPE token_type,
                PSECURITY_CAPABILITIES security_capabilities,
                BOOL restricted) {
  ASSERT_EQ(restricted, ::IsTokenRestricted(token))
      << TokenTypeToName(token_type);

  DWORD appcontainer;
  DWORD return_length;
  ASSERT_TRUE(::GetTokenInformation(token, ::TokenIsAppContainer, &appcontainer,
                                    sizeof(appcontainer), &return_length))
      << TokenTypeToName(token_type);
  ASSERT_TRUE(appcontainer) << TokenTypeToName(token_type);
  TOKEN_TYPE token_type_real;
  ASSERT_TRUE(::GetTokenInformation(token, ::TokenType, &token_type_real,
                                    sizeof(token_type_real), &return_length))
      << TokenTypeToName(token_type);
  ASSERT_EQ(token_type_real, token_type) << TokenTypeToName(token_type);
  if (token_type == ::TokenImpersonation) {
    SECURITY_IMPERSONATION_LEVEL imp_level;
    ASSERT_TRUE(::GetTokenInformation(token, ::TokenImpersonationLevel,
                                      &imp_level, sizeof(imp_level),
                                      &return_length))
        << TokenTypeToName(token_type);
    ASSERT_EQ(imp_level, ::SecurityImpersonation)
        << TokenTypeToName(token_type);
  }

  std::unique_ptr<Sid> package_sid;
  ASSERT_TRUE(GetTokenAppContainerSid(token, &package_sid))
      << TokenTypeToName(token_type);
  EXPECT_TRUE(::EqualSid(security_capabilities->AppContainerSid,
                         package_sid->GetPSID()))
      << TokenTypeToName(token_type);

  std::vector<SidAndAttributes> capabilities;
  ASSERT_TRUE(GetTokenGroups(token, ::TokenCapabilities, &capabilities))
      << TokenTypeToName(token_type);

  ASSERT_EQ(capabilities.size(), security_capabilities->CapabilityCount)
      << TokenTypeToName(token_type);
  for (size_t index = 0; index < capabilities.size(); ++index) {
    EXPECT_EQ(capabilities[index].GetAttributes(),
              security_capabilities->Capabilities[index].Attributes)
        << TokenTypeToName(token_type);
    EXPECT_TRUE(::EqualSid(capabilities[index].GetPSID(),
                           security_capabilities->Capabilities[index].Sid))
        << TokenTypeToName(token_type);
  }
}

void CheckProcessToken(HANDLE process,
                       PSECURITY_CAPABILITIES security_capabilities,
                       bool restricted) {
  HANDLE token_handle;
  ASSERT_TRUE(::OpenProcessToken(process, TOKEN_ALL_ACCESS, &token_handle));
  base::win::ScopedHandle token(token_handle);
  CheckToken(token_handle, ::TokenPrimary, security_capabilities, restricted);
}

void CheckThreadToken(HANDLE thread,
                      PSECURITY_CAPABILITIES security_capabilities,
                      bool restricted) {
  HANDLE token_handle;
  ASSERT_TRUE(::OpenThreadToken(thread, TOKEN_ALL_ACCESS, TRUE, &token_handle));
  base::win::ScopedHandle token(token_handle);
  CheckToken(token_handle, ::TokenImpersonation, security_capabilities,
             restricted);
}

// Check for LPAC using an access check. We could query for a security attribute
// but that's undocumented and has the potential to change.
void CheckLpacToken(HANDLE process) {
  HANDLE token_handle;
  ASSERT_TRUE(::OpenProcessToken(process, TOKEN_ALL_ACCESS, &token_handle));
  base::win::ScopedHandle token(token_handle);
  ASSERT_TRUE(
      ::DuplicateToken(token.Get(), ::SecurityImpersonation, &token_handle));
  token.Set(token_handle);
  PSECURITY_DESCRIPTOR security_desc_ptr;
  // AC is AllPackages, S-1-15-2-2 is AllRestrictedPackages. An LPAC token
  // will get granted access of 2, where as a normal AC token will get 3.
  ASSERT_TRUE(::ConvertStringSecurityDescriptorToSecurityDescriptor(
      L"O:SYG:SYD:(A;;0x3;;;WD)(A;;0x1;;;AC)(A;;0x2;;;S-1-15-2-2)",
      SDDL_REVISION_1, &security_desc_ptr, nullptr));
  std::unique_ptr<void, LocalFreeDeleter> security_desc(security_desc_ptr);
  GENERIC_MAPPING generic_mapping = {};
  PRIVILEGE_SET priv_set = {};
  DWORD priv_set_length = sizeof(PRIVILEGE_SET);
  DWORD granted_access;
  BOOL access_status;
  ASSERT_TRUE(::AccessCheck(security_desc_ptr, token.Get(), MAXIMUM_ALLOWED,
                            &generic_mapping, &priv_set, &priv_set_length,
                            &granted_access, &access_status));
  ASSERT_TRUE(access_status);
  ASSERT_EQ(DWORD{2}, granted_access);
}

class AppContainerProfileTest : public ::testing::Test {
 public:
  void SetUp() override {
    if (base::win::GetVersion() < base::win::Version::WIN8)
      return;
    package_name_ = GenerateRandomPackageName();
    broker_services_ = GetBroker();
    policy_ = broker_services_->CreatePolicy();
    ASSERT_EQ(SBOX_ALL_OK,
              policy_->SetProcessMitigations(MITIGATION_HEAP_TERMINATE));
    ASSERT_EQ(SBOX_ALL_OK,
              policy_->AddAppContainerProfile(package_name_.c_str(), true));
    // For testing purposes we known the base class so cast directly.
    profile_ = static_cast<AppContainerProfileBase*>(
        policy_->GetAppContainerProfile().get());
  }

  void TearDown() override {
    if (scoped_process_info_.IsValid())
      ::TerminateProcess(scoped_process_info_.process_handle(), 0);
    if (profile_)
      AppContainerProfileBase::Delete(package_name_.c_str());
  }

 protected:
  void CreateProcess() {
    // Get the path to the sandboxed app.
    wchar_t prog_name[MAX_PATH] = {};
    ASSERT_NE(DWORD{0}, ::GetModuleFileNameW(nullptr, prog_name, MAX_PATH));

    PROCESS_INFORMATION process_info = {};
    ResultCode last_warning = SBOX_ALL_OK;
    DWORD last_error = 0;
    ResultCode result = broker_services_->SpawnTarget(
        prog_name, prog_name, policy_, &last_warning, &last_error,
        &process_info);
    ASSERT_EQ(SBOX_ALL_OK, result) << "Last Error: " << last_error;
    scoped_process_info_.Set(process_info);
  }

  std::wstring package_name_;
  BrokerServices* broker_services_;
  scoped_refptr<AppContainerProfileBase> profile_;
  scoped_refptr<TargetPolicy> policy_;
  base::win::ScopedProcessInformation scoped_process_info_;
};

}  // namespace


TEST(AppContainerTest, DenyOpenEventForLowBox) {
  if (base::win::GetVersion() < base::win::Version::WIN8)
    return;

  TestRunner runner(JOB_UNPROTECTED, USER_UNPROTECTED, USER_UNPROTECTED);

  EXPECT_EQ(SBOX_ALL_OK, runner.GetPolicy()->SetLowBox(kAppContainerSid));
  // Run test once, this ensures the app container directory exists, we
  // ignore the result.
  runner.RunTest(L"Event_Open f test");
  std::wstring event_name = L"AppContainerNamedObjects\\";
  event_name += kAppContainerSid;
  event_name += L"\\test";

  base::win::ScopedHandle event(
      ::CreateEvent(nullptr, false, false, event_name.c_str()));
  ASSERT_TRUE(event.IsValid());

  EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test"));
}

TEST_F(AppContainerProfileTest, CheckIncompatibleOptions) {
  if (!profile_)
    return;
  EXPECT_EQ(SBOX_ERROR_BAD_PARAMS,
            policy_->SetIntegrityLevel(INTEGRITY_LEVEL_UNTRUSTED));
  EXPECT_EQ(SBOX_ERROR_BAD_PARAMS, policy_->SetLowBox(kAppContainerSid));

  MitigationFlags expected_mitigations = 0;
  MitigationFlags expected_delayed = MITIGATION_HEAP_TERMINATE;
  sandbox::ResultCode expected_result = SBOX_ERROR_BAD_PARAMS;

  if (base::win::GetVersion() >= base::win::Version::WIN10_RS5) {
    expected_mitigations = MITIGATION_HEAP_TERMINATE;
    expected_delayed = 0;
    expected_result = SBOX_ALL_OK;
  }

  EXPECT_EQ(expected_mitigations, policy_->GetProcessMitigations());
  EXPECT_EQ(expected_delayed, policy_->GetDelayedProcessMitigations());
  EXPECT_EQ(expected_result,
            policy_->SetProcessMitigations(MITIGATION_HEAP_TERMINATE));
}

TEST_F(AppContainerProfileTest, NoCapabilities) {
  if (!profile_)
    return;

  policy_->SetTokenLevel(USER_UNPROTECTED, USER_UNPROTECTED);
  policy_->SetJobLevel(JOB_NONE, 0);

  CreateProcess();
  auto security_capabilities = profile_->GetSecurityCapabilities();

  CheckProcessToken(scoped_process_info_.process_handle(),
                    security_capabilities.get(), FALSE);
  CheckThreadToken(scoped_process_info_.thread_handle(),
                   security_capabilities.get(), FALSE);
}

TEST_F(AppContainerProfileTest, NoCapabilitiesRestricted) {
  if (!profile_)
    return;

  policy_->SetTokenLevel(USER_LOCKDOWN, USER_RESTRICTED_SAME_ACCESS);
  policy_->SetJobLevel(JOB_NONE, 0);

  CreateProcess();
  auto security_capabilities = profile_->GetSecurityCapabilities();

  CheckProcessToken(scoped_process_info_.process_handle(),
                    security_capabilities.get(), TRUE);
  CheckThreadToken(scoped_process_info_.thread_handle(),
                   security_capabilities.get(), TRUE);
}

TEST_F(AppContainerProfileTest, WithCapabilities) {
  if (!profile_)
    return;

  profile_->AddCapability(kInternetClient);
  profile_->AddCapability(kInternetClientServer);
  policy_->SetTokenLevel(USER_UNPROTECTED, USER_UNPROTECTED);
  policy_->SetJobLevel(JOB_NONE, 0);

  CreateProcess();
  auto security_capabilities = profile_->GetSecurityCapabilities();

  CheckProcessToken(scoped_process_info_.process_handle(),
                    security_capabilities.get(), FALSE);
  CheckThreadToken(scoped_process_info_.thread_handle(),
                   security_capabilities.get(), FALSE);
}

TEST_F(AppContainerProfileTest, WithCapabilitiesRestricted) {
  if (!profile_)
    return;

  profile_->AddCapability(kInternetClient);
  profile_->AddCapability(kInternetClientServer);
  policy_->SetTokenLevel(USER_LOCKDOWN, USER_RESTRICTED_SAME_ACCESS);
  policy_->SetJobLevel(JOB_NONE, 0);

  CreateProcess();
  auto security_capabilities = profile_->GetSecurityCapabilities();

  CheckProcessToken(scoped_process_info_.process_handle(),
                    security_capabilities.get(), TRUE);
  CheckThreadToken(scoped_process_info_.thread_handle(),
                   security_capabilities.get(), TRUE);
}

TEST_F(AppContainerProfileTest, WithImpersonationCapabilities) {
  if (!profile_)
    return;

  profile_->AddCapability(kInternetClient);
  profile_->AddCapability(kInternetClientServer);
  profile_->AddImpersonationCapability(kPrivateNetworkClientServer);
  profile_->AddImpersonationCapability(kPicturesLibrary);
  policy_->SetTokenLevel(USER_UNPROTECTED, USER_UNPROTECTED);
  policy_->SetJobLevel(JOB_NONE, 0);

  CreateProcess();
  auto security_capabilities = profile_->GetSecurityCapabilities();

  CheckProcessToken(scoped_process_info_.process_handle(),
                    security_capabilities.get(), FALSE);
  SecurityCapabilities impersonation_security_capabilities(
      profile_->GetPackageSid(), profile_->GetImpersonationCapabilities());
  CheckThreadToken(scoped_process_info_.thread_handle(),
                   &impersonation_security_capabilities, FALSE);
}

TEST_F(AppContainerProfileTest, NoCapabilitiesLPAC) {
  if (base::win::GetVersion() < base::win::Version::WIN10_RS1)
    return;

  profile_->SetEnableLowPrivilegeAppContainer(true);
  policy_->SetTokenLevel(USER_UNPROTECTED, USER_UNPROTECTED);
  policy_->SetJobLevel(JOB_NONE, 0);

  CreateProcess();
  auto security_capabilities = profile_->GetSecurityCapabilities();

  CheckProcessToken(scoped_process_info_.process_handle(),
                    security_capabilities.get(), FALSE);
  CheckThreadToken(scoped_process_info_.thread_handle(),
                   security_capabilities.get(), FALSE);
  CheckLpacToken(scoped_process_info_.process_handle());
}

}  // namespace sandbox