summaryrefslogtreecommitdiffstats
path: root/ipc/mscom/ProcessRuntime.cpp
blob: f20b0658bbcadec4f773c06fee670a8ae62149a1 (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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/mscom/ProcessRuntime.h"

#include "mozilla/Assertions.h"
#include "mozilla/DynamicallyLinkedFunctionPtr.h"
#include "mozilla/mscom/COMWrappers.h"
#include "mozilla/mscom/ProcessRuntimeShared.h"
#include "mozilla/RefPtr.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/Vector.h"
#include "mozilla/WindowsProcessMitigations.h"
#include "mozilla/WindowsVersion.h"

#if defined(MOZILLA_INTERNAL_API)
#  include "mozilla/mscom/EnsureMTA.h"
#  if defined(MOZ_SANDBOX)
#    include "mozilla/sandboxTarget.h"
#  endif  // defined(MOZ_SANDBOX)
#endif    // defined(MOZILLA_INTERNAL_API)

#include <accctrl.h>
#include <aclapi.h>
#include <objbase.h>
#include <objidl.h>

// This API from oleaut32.dll is not declared in Windows SDK headers
extern "C" void __cdecl SetOaNoCache(void);

using namespace mozilla::mscom::detail;

namespace mozilla {
namespace mscom {

#if defined(MOZILLA_INTERNAL_API)
ProcessRuntime* ProcessRuntime::sInstance = nullptr;

ProcessRuntime::ProcessRuntime() : ProcessRuntime(XRE_GetProcessType()) {}

ProcessRuntime::ProcessRuntime(const GeckoProcessType aProcessType)
    : ProcessRuntime(aProcessType == GeckoProcessType_Default
                         ? ProcessCategory::GeckoBrowserParent
                         : ProcessCategory::GeckoChild) {}
#endif  // defined(MOZILLA_INTERNAL_API)

ProcessRuntime::ProcessRuntime(const ProcessCategory aProcessCategory)
    : mInitResult(CO_E_NOTINITIALIZED), mProcessCategory(aProcessCategory) {
#if defined(MOZILLA_INTERNAL_API)
  MOZ_DIAGNOSTIC_ASSERT(!sInstance);
  sInstance = this;

  EnsureMTA();
  /**
   * From this point forward, all threads in this process are implicitly
   * members of the multi-threaded apartment, with the following exceptions:
   * 1. If any Win32 GUI APIs were called on the current thread prior to
   *    executing this constructor, then this thread has already been implicitly
   *    initialized as the process's main STA thread; or
   * 2. A thread explicitly and successfully calls CoInitialize(Ex) to specify
   *    otherwise.
   */

  const bool isCurThreadImplicitMTA = IsCurrentThreadImplicitMTA();
  // We only assert that the implicit MTA precondition holds when not running
  // as the Gecko parent process.
  MOZ_DIAGNOSTIC_ASSERT(aProcessCategory ==
                            ProcessCategory::GeckoBrowserParent ||
                        isCurThreadImplicitMTA);

#  if defined(MOZ_SANDBOX)
  const bool isLockedDownChildProcess =
      mProcessCategory == ProcessCategory::GeckoChild && IsWin32kLockedDown();
  // If our process is running under Win32k lockdown, we cannot initialize
  // COM with a single-threaded apartment. This is because STAs create a hidden
  // window, which implicitly requires user32 and Win32k, which are blocked.
  // Instead we start the multi-threaded apartment and conduct our process-wide
  // COM initialization there.
  if (isLockedDownChildProcess) {
    // Make sure we're still running with the sandbox's privileged impersonation
    // token.
    HANDLE rawCurThreadImpToken;
    if (!::OpenThreadToken(::GetCurrentThread(), TOKEN_DUPLICATE | TOKEN_QUERY,
                           FALSE, &rawCurThreadImpToken)) {
      mInitResult = HRESULT_FROM_WIN32(::GetLastError());
      return;
    }
    nsAutoHandle curThreadImpToken(rawCurThreadImpToken);

    // Ensure that our current token is still an impersonation token (ie, we
    // have not yet called RevertToSelf() on this thread).
    DWORD len;
    TOKEN_TYPE tokenType;
    MOZ_RELEASE_ASSERT(
        ::GetTokenInformation(rawCurThreadImpToken, TokenType, &tokenType,
                              sizeof(tokenType), &len) &&
        len == sizeof(tokenType) && tokenType == TokenImpersonation);

    // Ideally we want our current thread to be running implicitly inside the
    // MTA, but if for some wacky reason we did not end up with that, we may
    // compensate by completing initialization via EnsureMTA's persistent
    // thread.
    if (!isCurThreadImplicitMTA) {
      InitUsingPersistentMTAThread(curThreadImpToken);
      return;
    }
  }
#  endif  // defined(MOZ_SANDBOX)
#endif    // defined(MOZILLA_INTERNAL_API)

  mAptRegion.Init(GetDesiredApartmentType(mProcessCategory));

  // It can happen that we are not the outermost COM initialization on this
  // thread. In fact it should regularly be the case that the outermost
  // initialization occurs from outside of XUL, before we show the skeleton UI,
  // at which point we still need to run some things here from within XUL.
  if (!mAptRegion.IsValidOutermost()) {
    mInitResult = mAptRegion.GetHResult();
#if defined(MOZILLA_INTERNAL_API)
    MOZ_ASSERT(mProcessCategory == ProcessCategory::GeckoBrowserParent);
    if (mProcessCategory != ProcessCategory::GeckoBrowserParent) {
      // This is unexpected unless we're GeckoBrowserParent
      return;
    }

    ProcessInitLock lock;

    // Is another instance of ProcessRuntime responsible for the outer
    // initialization?
    const bool prevInit =
        lock.GetInitState() == ProcessInitState::FullyInitialized;
    MOZ_ASSERT(prevInit);
    if (prevInit) {
      PostInit();
    }
#endif  // defined(MOZILLA_INTERNAL_API)
    return;
  }

  InitInsideApartment();
  if (FAILED(mInitResult)) {
    return;
  }

#if defined(MOZILLA_INTERNAL_API)
#  if defined(MOZ_SANDBOX)
  if (isLockedDownChildProcess) {
    // In locked-down child processes, defer PostInit until priv drop
    SandboxTarget::Instance()->RegisterSandboxStartCallback([self = this]() {
      // Ensure that we're still live and the init was successful before
      // calling PostInit()
      if (self == sInstance && SUCCEEDED(self->mInitResult)) {
        PostInit();
      }
    });
    return;
  }
#  endif  // defined(MOZ_SANDBOX)

  PostInit();
#endif  // defined(MOZILLA_INTERNAL_API)
}

#if defined(MOZILLA_INTERNAL_API)
ProcessRuntime::~ProcessRuntime() {
  MOZ_DIAGNOSTIC_ASSERT(sInstance == this);
  sInstance = nullptr;
}

#  if defined(MOZ_SANDBOX)
void ProcessRuntime::InitUsingPersistentMTAThread(
    const nsAutoHandle& aCurThreadToken) {
  // Create an impersonation token based on the current thread's token
  HANDLE rawMtaThreadImpToken = nullptr;
  if (!::DuplicateToken(aCurThreadToken, SecurityImpersonation,
                        &rawMtaThreadImpToken)) {
    mInitResult = HRESULT_FROM_WIN32(::GetLastError());
    return;
  }
  nsAutoHandle mtaThreadImpToken(rawMtaThreadImpToken);

  // Impersonate and initialize.
  bool tokenSet = false;
  EnsureMTA(
      [this, rawMtaThreadImpToken, &tokenSet]() -> void {
        if (!::SetThreadToken(nullptr, rawMtaThreadImpToken)) {
          mInitResult = HRESULT_FROM_WIN32(::GetLastError());
          return;
        }

        tokenSet = true;
        InitInsideApartment();
      },
      EnsureMTA::Option::ForceDispatchToPersistentThread);

  if (!tokenSet) {
    return;
  }

  SandboxTarget::Instance()->RegisterSandboxStartCallback(
      [self = this]() -> void {
        EnsureMTA(
            []() -> void {
              // This is a security risk if it fails, so we release assert
              MOZ_RELEASE_ASSERT(::RevertToSelf(),
                                 "mscom::ProcessRuntime RevertToSelf failed");
            },
            EnsureMTA::Option::ForceDispatchToPersistentThread);

        // Ensure that we're still live and the init was successful before
        // calling PostInit()
        if (self == sInstance && SUCCEEDED(self->mInitResult)) {
          PostInit();
        }
      });
}
#  endif  // defined(MOZ_SANDBOX)
#endif    // defined(MOZILLA_INTERNAL_API)

/* static */
COINIT ProcessRuntime::GetDesiredApartmentType(
    const ProcessRuntime::ProcessCategory aProcessCategory) {
  switch (aProcessCategory) {
    case ProcessCategory::GeckoBrowserParent:
      return COINIT_APARTMENTTHREADED;
    case ProcessCategory::GeckoChild:
      if (!IsWin32kLockedDown()) {
        // If Win32k is not locked down then we probably still need STA.
        // We disable DDE since that is not usable from child processes.
        return static_cast<COINIT>(COINIT_APARTMENTTHREADED |
                                   COINIT_DISABLE_OLE1DDE);
      }

      [[fallthrough]];
    default:
      return COINIT_MULTITHREADED;
  }
}

void ProcessRuntime::InitInsideApartment() {
  ProcessInitLock lock;
  const ProcessInitState prevInitState = lock.GetInitState();
  if (prevInitState == ProcessInitState::FullyInitialized) {
    // COM has already been initialized by a previous ProcessRuntime instance
    mInitResult = S_OK;
    return;
  }

  if (prevInitState < ProcessInitState::PartialSecurityInitialized) {
    // We are required to initialize security prior to configuring global
    // options.
    mInitResult = InitializeSecurity(mProcessCategory);
    MOZ_DIAGNOSTIC_ASSERT(SUCCEEDED(mInitResult));

    // Even though this isn't great, we should try to proceed even when
    // CoInitializeSecurity has previously been called: the additional settings
    // we want to change are important enough that we don't want to skip them.
    if (FAILED(mInitResult) && mInitResult != RPC_E_TOO_LATE) {
      return;
    }

    lock.SetInitState(ProcessInitState::PartialSecurityInitialized);
  }

  if (prevInitState < ProcessInitState::PartialGlobalOptions) {
    RefPtr<IGlobalOptions> globalOpts;
    mInitResult = wrapped::CoCreateInstance(
        CLSID_GlobalOptions, nullptr, CLSCTX_INPROC_SERVER, IID_IGlobalOptions,
        getter_AddRefs(globalOpts));
    MOZ_ASSERT(SUCCEEDED(mInitResult));
    if (FAILED(mInitResult)) {
      return;
    }

    // Disable COM's catch-all exception handler
    mInitResult = globalOpts->Set(COMGLB_EXCEPTION_HANDLING,
                                  COMGLB_EXCEPTION_DONOT_HANDLE_ANY);
    MOZ_ASSERT(SUCCEEDED(mInitResult));
    if (FAILED(mInitResult)) {
      return;
    }

    lock.SetInitState(ProcessInitState::PartialGlobalOptions);
  }

  // Disable the BSTR cache (as it never invalidates, thus leaking memory)
  // (This function is itself idempotent, so we do not concern ourselves with
  // tracking whether or not we've already called it.)
  ::SetOaNoCache();

  lock.SetInitState(ProcessInitState::FullyInitialized);
}

#if defined(MOZILLA_INTERNAL_API)
/**
 * Guaranteed to run *after* the COM (and possible sandboxing) initialization
 * has successfully completed and stabilized. This method MUST BE IDEMPOTENT!
 */
/* static */ void ProcessRuntime::PostInit() {
  // Currently "roughed-in" but unused.
}
#endif  // defined(MOZILLA_INTERNAL_API)

/* static */
DWORD
ProcessRuntime::GetClientThreadId() {
  DWORD callerTid;
  HRESULT hr = ::CoGetCallerTID(&callerTid);
  // Don't return callerTid unless the call succeeded and returned S_FALSE,
  // indicating that the caller originates from a different process.
  if (hr != S_FALSE) {
    return 0;
  }

  return callerTid;
}

/* static */
HRESULT
ProcessRuntime::InitializeSecurity(const ProcessCategory aProcessCategory) {
  HANDLE rawToken = nullptr;
  BOOL ok = ::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &rawToken);
  if (!ok) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }
  nsAutoHandle token(rawToken);

  DWORD len = 0;
  ok = ::GetTokenInformation(token, TokenUser, nullptr, len, &len);
  DWORD win32Error = ::GetLastError();
  if (!ok && win32Error != ERROR_INSUFFICIENT_BUFFER) {
    return HRESULT_FROM_WIN32(win32Error);
  }

  auto tokenUserBuf = MakeUnique<BYTE[]>(len);
  TOKEN_USER& tokenUser = *reinterpret_cast<TOKEN_USER*>(tokenUserBuf.get());
  ok = ::GetTokenInformation(token, TokenUser, tokenUserBuf.get(), len, &len);
  if (!ok) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }

  len = 0;
  ok = ::GetTokenInformation(token, TokenPrimaryGroup, nullptr, len, &len);
  win32Error = ::GetLastError();
  if (!ok && win32Error != ERROR_INSUFFICIENT_BUFFER) {
    return HRESULT_FROM_WIN32(win32Error);
  }

  auto tokenPrimaryGroupBuf = MakeUnique<BYTE[]>(len);
  TOKEN_PRIMARY_GROUP& tokenPrimaryGroup =
      *reinterpret_cast<TOKEN_PRIMARY_GROUP*>(tokenPrimaryGroupBuf.get());
  ok = ::GetTokenInformation(token, TokenPrimaryGroup,
                             tokenPrimaryGroupBuf.get(), len, &len);
  if (!ok) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }

  SECURITY_DESCRIPTOR sd;
  if (!::InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }

  BYTE systemSid[SECURITY_MAX_SID_SIZE];
  DWORD systemSidSize = sizeof(systemSid);
  if (!::CreateWellKnownSid(WinLocalSystemSid, nullptr, systemSid,
                            &systemSidSize)) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }

  BYTE adminSid[SECURITY_MAX_SID_SIZE];
  DWORD adminSidSize = sizeof(adminSid);
  if (!::CreateWellKnownSid(WinBuiltinAdministratorsSid, nullptr, adminSid,
                            &adminSidSize)) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }

  const bool allowAppContainers =
      aProcessCategory == ProcessCategory::GeckoBrowserParent &&
      IsWin8OrLater();

  BYTE appContainersSid[SECURITY_MAX_SID_SIZE];
  DWORD appContainersSidSize = sizeof(appContainersSid);
  if (allowAppContainers) {
    if (!::CreateWellKnownSid(WinBuiltinAnyPackageSid, nullptr,
                              appContainersSid, &appContainersSidSize)) {
      return HRESULT_FROM_WIN32(::GetLastError());
    }
  }

  // Grant access to SYSTEM, Administrators, the user, and when running as the
  // browser process on Windows 8+, all app containers.
  const size_t kMaxInlineEntries = 4;
  mozilla::Vector<EXPLICIT_ACCESS_W, kMaxInlineEntries> entries;

  Unused << entries.append(EXPLICIT_ACCESS_W{
      COM_RIGHTS_EXECUTE,
      GRANT_ACCESS,
      NO_INHERITANCE,
      {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_USER,
       reinterpret_cast<LPWSTR>(systemSid)}});

  Unused << entries.append(EXPLICIT_ACCESS_W{
      COM_RIGHTS_EXECUTE,
      GRANT_ACCESS,
      NO_INHERITANCE,
      {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID,
       TRUSTEE_IS_WELL_KNOWN_GROUP, reinterpret_cast<LPWSTR>(adminSid)}});

  Unused << entries.append(EXPLICIT_ACCESS_W{
      COM_RIGHTS_EXECUTE,
      GRANT_ACCESS,
      NO_INHERITANCE,
      {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_USER,
       reinterpret_cast<LPWSTR>(tokenUser.User.Sid)}});

  if (allowAppContainers) {
    Unused << entries.append(
        EXPLICIT_ACCESS_W{COM_RIGHTS_EXECUTE,
                          GRANT_ACCESS,
                          NO_INHERITANCE,
                          {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID,
                           TRUSTEE_IS_WELL_KNOWN_GROUP,
                           reinterpret_cast<LPWSTR>(appContainersSid)}});
  }

  PACL rawDacl = nullptr;
  win32Error =
      ::SetEntriesInAclW(entries.length(), entries.begin(), nullptr, &rawDacl);
  if (win32Error != ERROR_SUCCESS) {
    return HRESULT_FROM_WIN32(win32Error);
  }

  UniquePtr<ACL, LocalFreeDeleter> dacl(rawDacl);

  if (!::SetSecurityDescriptorDacl(&sd, TRUE, dacl.get(), FALSE)) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }

  if (!::SetSecurityDescriptorOwner(&sd, tokenUser.User.Sid, FALSE)) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }

  if (!::SetSecurityDescriptorGroup(&sd, tokenPrimaryGroup.PrimaryGroup,
                                    FALSE)) {
    return HRESULT_FROM_WIN32(::GetLastError());
  }

  return wrapped::CoInitializeSecurity(
      &sd, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT,
      RPC_C_IMP_LEVEL_IDENTIFY, nullptr, EOAC_NONE, nullptr);
}

}  // namespace mscom
}  // namespace mozilla