c311dfd234d585c2ab426890d1e453d97b604657
[platform/framework/web/crosswalk.git] / src / content / common / sandbox_win.cc
1 // Copyright (c) 2012 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.
4
5 #include "content/common/sandbox_win.h"
6
7 #include <string>
8
9 #include "base/base_switches.h"
10 #include "base/command_line.h"
11 #include "base/debug/profiler.h"
12 #include "base/debug/trace_event.h"
13 #include "base/files/file_util.h"
14 #include "base/hash.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/path_service.h"
17 #include "base/process/launch.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/win/iat_patch_function.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/win/scoped_process_information.h"
23 #include "base/win/windows_version.h"
24 #include "content/public/common/content_client.h"
25 #include "content/public/common/content_switches.h"
26 #include "content/public/common/sandbox_init.h"
27 #include "content/public/common/sandboxed_process_launcher_delegate.h"
28 #include "sandbox/win/src/process_mitigations.h"
29 #include "sandbox/win/src/sandbox.h"
30 #include "sandbox/win/src/sandbox_nt_util.h"
31 #include "sandbox/win/src/win_utils.h"
32 #include "ui/gfx/win/dpi.h"
33
34 static sandbox::BrokerServices* g_broker_services = NULL;
35 static sandbox::TargetServices* g_target_services = NULL;
36
37 namespace content {
38 namespace {
39
40 // The DLLs listed here are known (or under strong suspicion) of causing crashes
41 // when they are loaded in the renderer. Note: at runtime we generate short
42 // versions of the dll name only if the dll has an extension.
43 // For more information about how this list is generated, and how to get off
44 // of it, see:
45 // https://sites.google.com/a/chromium.org/dev/Home/third-party-developers
46 const wchar_t* const kTroublesomeDlls[] = {
47   L"adialhk.dll",                 // Kaspersky Internet Security.
48   L"acpiz.dll",                   // Unknown.
49   L"airfoilinject3.dll",          // Airfoil.
50   L"akinsofthook32.dll",          // Akinsoft Software Engineering.
51   L"assistant_x64.dll",           // Unknown.
52   L"avcuf64.dll",                 // Bit Defender Internet Security x64.
53   L"avgrsstx.dll",                // AVG 8.
54   L"babylonchromepi.dll",         // Babylon translator.
55   L"btkeyind.dll",                // Widcomm Bluetooth.
56   L"cmcsyshk.dll",                // CMC Internet Security.
57   L"cmsetac.dll",                 // Unknown (suspected malware).
58   L"cooliris.dll",                // CoolIris.
59   L"dockshellhook.dll",           // Stardock Objectdock.
60   L"easyhook32.dll",              // GDIPP and others.
61   L"googledesktopnetwork3.dll",   // Google Desktop Search v5.
62   L"fwhook.dll",                  // PC Tools Firewall Plus.
63   L"hookprocesscreation.dll",     // Blumentals Program protector.
64   L"hookterminateapis.dll",       // Blumentals and Cyberprinter.
65   L"hookprintapis.dll",           // Cyberprinter.
66   L"imon.dll",                    // NOD32 Antivirus.
67   L"ioloHL.dll",                  // Iolo (System Mechanic).
68   L"kloehk.dll",                  // Kaspersky Internet Security.
69   L"lawenforcer.dll",             // Spyware-Browser AntiSpyware (Spybro).
70   L"libdivx.dll",                 // DivX.
71   L"lvprcinj01.dll",              // Logitech QuickCam.
72   L"madchook.dll",                // Madshi (generic hooking library).
73   L"mdnsnsp.dll",                 // Bonjour.
74   L"moonsysh.dll",                // Moon Secure Antivirus.
75   L"mpk.dll",                     // KGB Spy.
76   L"npdivx32.dll",                // DivX.
77   L"npggNT.des",                  // GameGuard 2008.
78   L"npggNT.dll",                  // GameGuard (older).
79   L"oawatch.dll",                 // Online Armor.
80   L"pavhook.dll",                 // Panda Internet Security.
81   L"pavlsphook.dll",              // Panda Antivirus.
82   L"pavshook.dll",                // Panda Antivirus.
83   L"pavshookwow.dll",             // Panda Antivirus.
84   L"pctavhook.dll",               // PC Tools Antivirus.
85   L"pctgmhk.dll",                 // PC Tools Spyware Doctor.
86   L"prntrack.dll",                // Pharos Systems.
87   L"protector.dll",               // Unknown (suspected malware).
88   L"radhslib.dll",                // Radiant Naomi Internet Filter.
89   L"radprlib.dll",                // Radiant Naomi Internet Filter.
90   L"rapportnikko.dll",            // Trustware Rapport.
91   L"rlhook.dll",                  // Trustware Bufferzone.
92   L"rooksdol.dll",                // Trustware Rapport.
93   L"rndlpepperbrowserrecordhelper.dll", // RealPlayer.
94   L"rpchromebrowserrecordhelper.dll",   // RealPlayer.
95   L"r3hook.dll",                  // Kaspersky Internet Security.
96   L"sahook.dll",                  // McAfee Site Advisor.
97   L"sbrige.dll",                  // Unknown.
98   L"sc2hook.dll",                 // Supercopier 2.
99   L"sdhook32.dll",                // Spybot - Search & Destroy Live Protection.
100   L"sguard.dll",                  // Iolo (System Guard).
101   L"smum32.dll",                  // Spyware Doctor version 6.
102   L"smumhook.dll",                // Spyware Doctor version 5.
103   L"ssldivx.dll",                 // DivX.
104   L"syncor11.dll",                // SynthCore Midi interface.
105   L"systools.dll",                // Panda Antivirus.
106   L"tfwah.dll",                   // Threatfire (PC tools).
107   L"wblind.dll",                  // Stardock Object desktop.
108   L"wbhelp.dll",                  // Stardock Object desktop.
109   L"winstylerthemehelper.dll"     // Tuneup utilities 2006.
110 };
111
112 // Adds the policy rules for the path and path\ with the semantic |access|.
113 // If |children| is set to true, we need to add the wildcard rules to also
114 // apply the rule to the subfiles and subfolders.
115 bool AddDirectory(int path, const wchar_t* sub_dir, bool children,
116                   sandbox::TargetPolicy::Semantics access,
117                   sandbox::TargetPolicy* policy) {
118   base::FilePath directory;
119   if (!PathService::Get(path, &directory))
120     return false;
121
122   if (sub_dir)
123     directory = base::MakeAbsoluteFilePath(directory.Append(sub_dir));
124
125   sandbox::ResultCode result;
126   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
127                            directory.value().c_str());
128   if (result != sandbox::SBOX_ALL_OK)
129     return false;
130
131   std::wstring directory_str = directory.value() + L"\\";
132   if (children)
133     directory_str += L"*";
134   // Otherwise, add the version of the path that ends with a separator.
135
136   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
137                            directory_str.c_str());
138   if (result != sandbox::SBOX_ALL_OK)
139     return false;
140
141   return true;
142 }
143
144 // Adds the policy rules for the path and path\* with the semantic |access|.
145 // We need to add the wildcard rules to also apply the rule to the subkeys.
146 bool AddKeyAndSubkeys(std::wstring key,
147                       sandbox::TargetPolicy::Semantics access,
148                       sandbox::TargetPolicy* policy) {
149   sandbox::ResultCode result;
150   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
151                            key.c_str());
152   if (result != sandbox::SBOX_ALL_OK)
153     return false;
154
155   key += L"\\*";
156   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
157                            key.c_str());
158   if (result != sandbox::SBOX_ALL_OK)
159     return false;
160
161   return true;
162 }
163
164 // Compares the loaded |module| file name matches |module_name|.
165 bool IsExpandedModuleName(HMODULE module, const wchar_t* module_name) {
166   wchar_t path[MAX_PATH];
167   DWORD sz = ::GetModuleFileNameW(module, path, arraysize(path));
168   if ((sz == arraysize(path)) || (sz == 0)) {
169     // XP does not set the last error properly, so we bail out anyway.
170     return false;
171   }
172   if (!::GetLongPathName(path, path, arraysize(path)))
173     return false;
174   base::FilePath fname(path);
175   return (fname.BaseName().value() == module_name);
176 }
177
178 // Adds a single dll by |module_name| into the |policy| blacklist.
179 // If |check_in_browser| is true we only add an unload policy only if the dll
180 // is also loaded in this process.
181 void BlacklistAddOneDll(const wchar_t* module_name,
182                         bool check_in_browser,
183                         sandbox::TargetPolicy* policy) {
184   HMODULE module = check_in_browser ? ::GetModuleHandleW(module_name) : NULL;
185   if (!module) {
186     // The module could have been loaded with a 8.3 short name. We check
187     // the three most common cases: 'thelongname.dll' becomes
188     // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
189     std::wstring name(module_name);
190     size_t period = name.rfind(L'.');
191     DCHECK_NE(std::string::npos, period);
192     DCHECK_LE(3U, (name.size() - period));
193     if (period <= 8)
194       return;
195     for (int ix = 0; ix < 3; ++ix) {
196       const wchar_t suffix[] = {'~', ('1' + ix), 0};
197       std::wstring alt_name = name.substr(0, 6) + suffix;
198       alt_name += name.substr(period, name.size());
199       if (check_in_browser) {
200         module = ::GetModuleHandleW(alt_name.c_str());
201         if (!module)
202           return;
203         // We found it, but because it only has 6 significant letters, we
204         // want to make sure it is the right one.
205         if (!IsExpandedModuleName(module, module_name))
206           return;
207       }
208       // Found a match. We add both forms to the policy.
209       policy->AddDllToUnload(alt_name.c_str());
210     }
211   }
212   policy->AddDllToUnload(module_name);
213   DVLOG(1) << "dll to unload found: " << module_name;
214   return;
215 }
216
217 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
218 // Eviction of injected DLLs is done by the sandbox so that the injected module
219 // does not get a chance to execute any code.
220 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy* policy) {
221   for (int ix = 0; ix != arraysize(kTroublesomeDlls); ++ix)
222     BlacklistAddOneDll(kTroublesomeDlls[ix], true, policy);
223 }
224
225 // Returns the object path prepended with the current logon session.
226 base::string16 PrependWindowsSessionPath(const base::char16* object) {
227   // Cache this because it can't change after process creation.
228   static uintptr_t s_session_id = 0;
229   if (s_session_id == 0) {
230     HANDLE token;
231     DWORD session_id_length;
232     DWORD session_id = 0;
233
234     CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token));
235     CHECK(::GetTokenInformation(token, TokenSessionId, &session_id,
236         sizeof(session_id), &session_id_length));
237     CloseHandle(token);
238     if (session_id)
239       s_session_id = session_id;
240   }
241
242   return base::StringPrintf(L"\\Sessions\\%d%ls", s_session_id, object);
243 }
244
245 // Checks if the sandbox should be let to run without a job object assigned.
246 bool ShouldSetJobLevel(const base::CommandLine& cmd_line) {
247   if (!cmd_line.HasSwitch(switches::kAllowNoSandboxJob))
248     return true;
249
250   // Windows 8 allows nested jobs so we don't need to check if we are in other
251   // job.
252   if (base::win::GetVersion() >= base::win::VERSION_WIN8)
253     return true;
254
255   BOOL in_job = true;
256   // Either there is no job yet associated so we must add our job,
257   if (!::IsProcessInJob(::GetCurrentProcess(), NULL, &in_job))
258     NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
259   if (!in_job)
260     return true;
261
262   // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
263   JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = {0};
264   if (!::QueryInformationJobObject(NULL,
265                                    JobObjectExtendedLimitInformation, &job_info,
266                                    sizeof(job_info), NULL)) {
267     NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
268     return true;
269   }
270   if (job_info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)
271     return true;
272
273   return false;
274 }
275
276 // Adds the generic policy rules to a sandbox TargetPolicy.
277 bool AddGenericPolicy(sandbox::TargetPolicy* policy) {
278   sandbox::ResultCode result;
279
280   // Renderers need to copy sections for plugin DIBs and GPU.
281   // GPU needs to copy sections to renderers.
282   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
283                            sandbox::TargetPolicy::HANDLES_DUP_ANY,
284                            L"Section");
285   if (result != sandbox::SBOX_ALL_OK)
286     return false;
287
288   // Add the policy for the client side of a pipe. It is just a file
289   // in the \pipe\ namespace. We restrict it to pipes that start with
290   // "chrome." so the sandboxed process cannot connect to system services.
291   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
292                            sandbox::TargetPolicy::FILES_ALLOW_ANY,
293                            L"\\??\\pipe\\chrome.*");
294   if (result != sandbox::SBOX_ALL_OK)
295     return false;
296
297   // Add the policy for the server side of nacl pipe. It is just a file
298   // in the \pipe\ namespace. We restrict it to pipes that start with
299   // "chrome.nacl" so the sandboxed process cannot connect to
300   // system services.
301   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
302                            sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
303                            L"\\\\.\\pipe\\chrome.nacl.*");
304   if (result != sandbox::SBOX_ALL_OK)
305     return false;
306
307   // Allow the server side of sync sockets, which are pipes that have
308   // the "chrome.sync" namespace and a randomly generated suffix.
309   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
310                            sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
311                            L"\\\\.\\pipe\\chrome.sync.*");
312   if (result != sandbox::SBOX_ALL_OK)
313     return false;
314
315   // Add the policy for debug message only in debug
316 #ifndef NDEBUG
317   base::FilePath app_dir;
318   if (!PathService::Get(base::DIR_MODULE, &app_dir))
319     return false;
320
321   wchar_t long_path_buf[MAX_PATH];
322   DWORD long_path_return_value = GetLongPathName(app_dir.value().c_str(),
323                                                  long_path_buf,
324                                                  MAX_PATH);
325   if (long_path_return_value == 0 || long_path_return_value >= MAX_PATH)
326     return false;
327
328   base::FilePath debug_message(long_path_buf);
329   debug_message = debug_message.AppendASCII("debug_message.exe");
330   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
331                            sandbox::TargetPolicy::PROCESS_MIN_EXEC,
332                            debug_message.value().c_str());
333   if (result != sandbox::SBOX_ALL_OK)
334     return false;
335 #endif  // NDEBUG
336
337   AddGenericDllEvictionPolicy(policy);
338   return true;
339 }
340
341 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy* policy) {
342   sandbox::ResultCode result;
343   // Renderers need to share events with plugins.
344   result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
345                            sandbox::TargetPolicy::HANDLES_DUP_ANY,
346                            L"Event");
347   if (result != sandbox::SBOX_ALL_OK)
348     return false;
349
350   // Win8+ adds a device DeviceApi that we don't need.
351   if (base::win::GetVersion() > base::win::VERSION_WIN7)
352     result = policy->AddKernelObjectToClose(L"File", L"\\Device\\DeviceApi");
353   if (result != sandbox::SBOX_ALL_OK)
354     return false;
355
356   // Close the proxy settings on XP.
357   if (base::win::GetVersion() <= base::win::VERSION_SERVER_2003)
358     result = policy->AddKernelObjectToClose(L"Key",
359                  L"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\" \
360                      L"CurrentVersion\\Internet Settings");
361   if (result != sandbox::SBOX_ALL_OK)
362     return false;
363
364
365   sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
366   if (base::win::GetVersion() > base::win::VERSION_XP) {
367     // On 2003/Vista the initial token has to be restricted if the main
368     // token is restricted.
369     initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
370   }
371
372   policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
373   // Prevents the renderers from manipulating low-integrity processes.
374   policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
375   policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
376
377   if (sandbox::SBOX_ALL_OK !=  policy->SetAlternateDesktop(true)) {
378     DLOG(WARNING) << "Failed to apply desktop security to the renderer";
379   }
380
381   return true;
382 }
383
384 // Updates the command line arguments with debug-related flags. If debug flags
385 // have been used with this process, they will be filtered and added to
386 // command_line as needed.
387 void ProcessDebugFlags(base::CommandLine* command_line) {
388   const base::CommandLine& current_cmd_line =
389       *base::CommandLine::ForCurrentProcess();
390   std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
391   if (current_cmd_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
392     // Look to pass-on the kWaitForDebugger flag.
393     std::string value = current_cmd_line.GetSwitchValueASCII(
394         switches::kWaitForDebuggerChildren);
395     if (value.empty() || value == type) {
396       command_line->AppendSwitch(switches::kWaitForDebugger);
397     }
398     command_line->AppendSwitchASCII(switches::kWaitForDebuggerChildren, value);
399   }
400 }
401
402 // This code is test only, and attempts to catch unsafe uses of
403 // DuplicateHandle() that copy privileged handles into sandboxed processes.
404 #ifndef OFFICIAL_BUILD
405 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
406
407 typedef BOOL (WINAPI *DuplicateHandleFunctionPtr)(HANDLE source_process_handle,
408                                                   HANDLE source_handle,
409                                                   HANDLE target_process_handle,
410                                                   LPHANDLE target_handle,
411                                                   DWORD desired_access,
412                                                   BOOL inherit_handle,
413                                                   DWORD options);
414
415 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle;
416
417 NtQueryObject g_QueryObject = NULL;
418
419 static const char* kDuplicateHandleWarning =
420     "You are attempting to duplicate a privileged handle into a sandboxed"
421     " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
422     " contact security@chromium.org for assistance.";
423
424 void CheckDuplicateHandle(HANDLE handle) {
425   // Get the object type (32 characters is safe; current max is 14).
426   BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
427   OBJECT_TYPE_INFORMATION* type_info =
428       reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
429   ULONG size = sizeof(buffer) - sizeof(wchar_t);
430   NTSTATUS error;
431   error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
432   CHECK(NT_SUCCESS(error));
433   type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
434
435   // Get the object basic information.
436   OBJECT_BASIC_INFORMATION basic_info;
437   size = sizeof(basic_info);
438   error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
439                         &size);
440   CHECK(NT_SUCCESS(error));
441
442   CHECK(!(basic_info.GrantedAccess & WRITE_DAC)) <<
443       kDuplicateHandleWarning;
444
445   if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
446     const ACCESS_MASK kDangerousMask =
447         ~static_cast<DWORD>(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE);
448     CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
449         kDuplicateHandleWarning;
450   }
451 }
452
453 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
454                                  HANDLE source_handle,
455                                  HANDLE target_process_handle,
456                                  LPHANDLE target_handle,
457                                  DWORD desired_access,
458                                  BOOL inherit_handle,
459                                  DWORD options) {
460   // Duplicate the handle so we get the final access mask.
461   if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
462                                    target_process_handle, target_handle,
463                                    desired_access, inherit_handle, options))
464     return FALSE;
465
466   // We're not worried about broker handles or not crossing process boundaries.
467   if (source_process_handle == target_process_handle ||
468       target_process_handle == ::GetCurrentProcess())
469     return TRUE;
470
471   // Only sandboxed children are placed in jobs, so just check them.
472   BOOL is_in_job = FALSE;
473   if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
474     // We need a handle with permission to check the job object.
475     if (ERROR_ACCESS_DENIED == ::GetLastError()) {
476       HANDLE temp_handle;
477       CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
478                                         target_process_handle,
479                                         ::GetCurrentProcess(),
480                                         &temp_handle,
481                                         PROCESS_QUERY_INFORMATION,
482                                         FALSE, 0));
483       base::win::ScopedHandle process(temp_handle);
484       CHECK(::IsProcessInJob(process.Get(), NULL, &is_in_job));
485     }
486   }
487
488   if (is_in_job) {
489     // We never allow inheritable child handles.
490     CHECK(!inherit_handle) << kDuplicateHandleWarning;
491
492     // Duplicate the handle again, to get the final permissions.
493     HANDLE temp_handle;
494     CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
495                                       ::GetCurrentProcess(), &temp_handle,
496                                       0, FALSE, DUPLICATE_SAME_ACCESS));
497     base::win::ScopedHandle handle(temp_handle);
498
499     // Callers use CHECK macro to make sure we get the right stack.
500     CheckDuplicateHandle(handle.Get());
501   }
502
503   return TRUE;
504 }
505 #endif
506
507 }  // namespace
508
509 void SetJobLevel(const base::CommandLine& cmd_line,
510                  sandbox::JobLevel job_level,
511                  uint32 ui_exceptions,
512                  sandbox::TargetPolicy* policy) {
513   if (ShouldSetJobLevel(cmd_line)) {
514 #ifdef _WIN64
515     policy->SetJobMemoryLimit(4ULL * 1024 * 1024 * 1024);
516 #endif
517     policy->SetJobLevel(job_level, ui_exceptions);
518   } else {
519     policy->SetJobLevel(sandbox::JOB_NONE, 0);
520   }
521 }
522
523 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
524 // Just have to figure out what needs to be warmed up first.
525 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
526   // TODO(cpu): Add back the BaseNamedObjects policy.
527   base::string16 object_path = PrependWindowsSessionPath(
528       L"\\BaseNamedObjects\\windows_shell_global_counters");
529   policy->AddKernelObjectToClose(L"Section", object_path.data());
530 }
531
532 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
533   // TODO(abarth): DCHECK(CalledOnValidThread());
534   //               See <http://b/1287166>.
535   DCHECK(broker_services);
536   DCHECK(!g_broker_services);
537   sandbox::ResultCode result = broker_services->Init();
538   g_broker_services = broker_services;
539
540   // In non-official builds warn about dangerous uses of DuplicateHandle.
541 #ifndef OFFICIAL_BUILD
542   BOOL is_in_job = FALSE;
543   CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
544   // In a Syzygy-profiled binary, instrumented for import profiling, this
545   // patch will end in infinite recursion on the attempted delegation to the
546   // original function.
547   if (!base::debug::IsBinaryInstrumented() &&
548       !is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
549     HMODULE module = NULL;
550     wchar_t module_name[MAX_PATH];
551     CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
552                               reinterpret_cast<LPCWSTR>(InitBrokerServices),
553                               &module));
554     DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
555     if (result && (result != MAX_PATH)) {
556       ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
557       result = g_iat_patch_duplicate_handle.Patch(
558           module_name, "kernel32.dll", "DuplicateHandle",
559           DuplicateHandlePatch);
560       CHECK(result == 0);
561       g_iat_orig_duplicate_handle =
562           reinterpret_cast<DuplicateHandleFunctionPtr>(
563               g_iat_patch_duplicate_handle.original_function());
564     }
565   }
566 #endif
567
568   return sandbox::SBOX_ALL_OK == result;
569 }
570
571 bool InitTargetServices(sandbox::TargetServices* target_services) {
572   DCHECK(target_services);
573   DCHECK(!g_target_services);
574   sandbox::ResultCode result = target_services->Init();
575   g_target_services = target_services;
576   return sandbox::SBOX_ALL_OK == result;
577 }
578
579 bool ShouldUseDirectWrite() {
580   // If the flag is currently on, and we're on Win7 or above, we enable
581   // DirectWrite. Skia does not require the additions to DirectWrite in QFE
582   // 2670838, but a simple 'better than XP' check is not enough.
583   if (base::win::GetVersion() < base::win::VERSION_WIN7)
584     return false;
585
586   base::win::OSInfo::VersionNumber os_version =
587       base::win::OSInfo::GetInstance()->version_number();
588   if ((os_version.major == 6) && (os_version.minor == 1)) {
589     // We can't use DirectWrite for pre-release versions of Windows 7.
590     if (os_version.build < 7600)
591       return false;
592   }
593
594   // If forced off, don't use it.
595   const base::CommandLine& command_line =
596       *base::CommandLine::ForCurrentProcess();
597   if (command_line.HasSwitch(switches::kDisableDirectWrite))
598     return false;
599
600 #if !defined(NACL_WIN64)
601   // Can't use GDI on HiDPI.
602   if (gfx::GetDPIScale() > 1.0f)
603     return true;
604 #endif
605
606   // Otherwise, check the field trial.
607   const std::string group_name =
608       base::FieldTrialList::FindFullName("DirectWrite");
609   return group_name != "Disabled";
610 }
611
612 base::ProcessHandle StartSandboxedProcess(
613     SandboxedProcessLauncherDelegate* delegate,
614     base::CommandLine* cmd_line) {
615   const base::CommandLine& browser_command_line =
616       *base::CommandLine::ForCurrentProcess();
617   std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
618
619   TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
620
621   // Propagate the --allow-no-job flag if present.
622   if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
623       !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
624     cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
625   }
626
627   ProcessDebugFlags(cmd_line);
628
629   // Prefetch hints on windows:
630   // Using a different prefetch profile per process type will allow Windows
631   // to create separate pretetch settings for browser, renderer etc.
632   cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
633
634   if ((delegate && !delegate->ShouldSandbox()) ||
635       browser_command_line.HasSwitch(switches::kNoSandbox) ||
636       cmd_line->HasSwitch(switches::kNoSandbox)) {
637     base::ProcessHandle process = 0;
638     base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
639     g_broker_services->AddTargetPeer(process);
640     return process;
641   }
642
643   sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
644
645   sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
646                                          sandbox::MITIGATION_BOTTOM_UP_ASLR |
647                                          sandbox::MITIGATION_DEP |
648                                          sandbox::MITIGATION_DEP_NO_ATL_THUNK |
649                                          sandbox::MITIGATION_SEHOP;
650
651  if (base::win::GetVersion() >= base::win::VERSION_WIN8 &&
652      type_str == switches::kRendererProcess &&
653      browser_command_line.HasSwitch(
654         switches::kEnableWin32kRendererLockDown)) {
655     if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_WIN32K_LOCKDOWN,
656                         sandbox::TargetPolicy::FAKE_USER_GDI_INIT,
657                         NULL) != sandbox::SBOX_ALL_OK) {
658       return 0;
659     }
660     mitigations |= sandbox::MITIGATION_WIN32K_DISABLE;
661   }
662
663   if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
664     return 0;
665
666   mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
667                 sandbox::MITIGATION_DLL_SEARCH_ORDER;
668
669   if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
670     return 0;
671
672   SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
673
674   bool disable_default_policy = false;
675   base::FilePath exposed_dir;
676   if (delegate)
677     delegate->PreSandbox(&disable_default_policy, &exposed_dir);
678
679   if (!disable_default_policy && !AddPolicyForSandboxedProcess(policy))
680     return 0;
681
682   if (type_str == switches::kRendererProcess) {
683     if (ShouldUseDirectWrite()) {
684       AddDirectory(base::DIR_WINDOWS_FONTS,
685                   NULL,
686                   true,
687                   sandbox::TargetPolicy::FILES_ALLOW_READONLY,
688                   policy);
689     }
690   } else {
691     // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
692     // this subprocess. See
693     // http://code.google.com/p/chromium/issues/detail?id=25580
694     cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
695   }
696
697   sandbox::ResultCode result;
698   if (!exposed_dir.empty()) {
699     result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
700                              sandbox::TargetPolicy::FILES_ALLOW_ANY,
701                              exposed_dir.value().c_str());
702     if (result != sandbox::SBOX_ALL_OK)
703       return 0;
704
705     base::FilePath exposed_files = exposed_dir.AppendASCII("*");
706     result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
707                              sandbox::TargetPolicy::FILES_ALLOW_ANY,
708                              exposed_files.value().c_str());
709     if (result != sandbox::SBOX_ALL_OK)
710       return 0;
711   }
712
713   if (!AddGenericPolicy(policy)) {
714     NOTREACHED();
715     return 0;
716   }
717
718   if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
719     // If stdout/stderr point to a Windows console, these calls will
720     // have no effect.
721     policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
722     policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
723   }
724
725   if (delegate) {
726     bool success = true;
727     delegate->PreSpawnTarget(policy, &success);
728     if (!success)
729       return 0;
730   }
731
732   TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
733
734   PROCESS_INFORMATION temp_process_info = {};
735   result = g_broker_services->SpawnTarget(
736                cmd_line->GetProgram().value().c_str(),
737                cmd_line->GetCommandLineString().c_str(),
738                policy, &temp_process_info);
739   policy->Release();
740   base::win::ScopedProcessInformation target(temp_process_info);
741
742   TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
743
744   if (sandbox::SBOX_ALL_OK != result) {
745     if (result == sandbox::SBOX_ERROR_GENERIC)
746       DPLOG(ERROR) << "Failed to launch process";
747     else
748       DLOG(ERROR) << "Failed to launch process. Error: " << result;
749     return 0;
750   }
751
752   if (delegate)
753     delegate->PostSpawnTarget(target.process_handle());
754
755   ResumeThread(target.thread_handle());
756   TRACE_EVENT_END_ETW("StartProcessWithAccess", 0, type_str);
757   return target.TakeProcessHandle();
758 }
759
760 bool BrokerDuplicateHandle(HANDLE source_handle,
761                            DWORD target_process_id,
762                            HANDLE* target_handle,
763                            DWORD desired_access,
764                            DWORD options) {
765   // If our process is the target just duplicate the handle.
766   if (::GetCurrentProcessId() == target_process_id) {
767     return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
768                                ::GetCurrentProcess(), target_handle,
769                                desired_access, FALSE, options);
770
771   }
772
773   // Try the broker next
774   if (g_target_services &&
775       g_target_services->DuplicateHandle(source_handle, target_process_id,
776                                          target_handle, desired_access,
777                                          options) == sandbox::SBOX_ALL_OK) {
778     return true;
779   }
780
781   // Finally, see if we already have access to the process.
782   base::win::ScopedHandle target_process;
783   target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
784                                     target_process_id));
785   if (target_process.IsValid()) {
786     return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
787                                 target_process.Get(), target_handle,
788                                 desired_access, FALSE, options);
789   }
790
791   return false;
792 }
793
794 bool BrokerAddTargetPeer(HANDLE peer_process) {
795   return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
796 }
797
798 }  // namespace content