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.
5 #include "content/common/sandbox_mac.h"
7 #import <Cocoa/Cocoa.h>
9 #include <CoreFoundation/CFTimeZone.h>
14 #include <sys/param.h>
16 #include "base/basictypes.h"
17 #include "base/command_line.h"
18 #include "base/compiler_specific.h"
19 #include "base/file_util.h"
20 #include "base/mac/bundle_locations.h"
21 #include "base/mac/mac_util.h"
22 #include "base/mac/scoped_cftyperef.h"
23 #include "base/mac/scoped_nsautorelease_pool.h"
24 #include "base/mac/scoped_nsobject.h"
25 #include "base/rand_util.h"
26 #include "base/strings/string16.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/stringprintf.h"
30 #include "base/strings/sys_string_conversions.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "base/sys_info.h"
33 #include "content/public/common/content_client.h"
34 #include "content/public/common/content_switches.h"
35 #include "grit/content_resources.h"
36 #include "third_party/icu/source/common/unicode/uchar.h"
37 #include "ui/base/layout.h"
38 #include "ui/gl/gl_surface.h"
43 // Is the sandbox currently active.
44 bool gSandboxIsActive = false;
46 struct SandboxTypeToResourceIDMapping {
47 SandboxType sandbox_type;
48 int sandbox_profile_resource_id;
51 // Mapping from sandbox process types to resource IDs containing the sandbox
52 // profile for all process types known to content.
53 SandboxTypeToResourceIDMapping kDefaultSandboxTypeToResourceIDMapping[] = {
54 { SANDBOX_TYPE_RENDERER, IDR_RENDERER_SANDBOX_PROFILE },
55 { SANDBOX_TYPE_WORKER, IDR_WORKER_SANDBOX_PROFILE },
56 { SANDBOX_TYPE_UTILITY, IDR_UTILITY_SANDBOX_PROFILE },
57 { SANDBOX_TYPE_GPU, IDR_GPU_SANDBOX_PROFILE },
58 { SANDBOX_TYPE_PPAPI, IDR_PPAPI_SANDBOX_PROFILE },
61 COMPILE_ASSERT(arraysize(kDefaultSandboxTypeToResourceIDMapping) == \
62 size_t(SANDBOX_TYPE_AFTER_LAST_TYPE), \
63 sandbox_type_to_resource_id_mapping_incorrect);
65 // Try to escape |c| as a "SingleEscapeCharacter" (\n, etc). If successful,
66 // returns true and appends the escape sequence to |dst|.
67 bool EscapeSingleChar(char c, std::string* dst) {
68 const char *append = NULL;
101 // Errors quoting strings for the Sandbox profile are always fatal, report them
102 // in a central place.
103 NOINLINE void FatalStringQuoteException(const std::string& str) {
104 // Copy bad string to the stack so it's recorded in the crash dump.
105 char bad_string[256] = {0};
106 base::strlcpy(bad_string, str.c_str(), arraysize(bad_string));
107 DLOG(FATAL) << "String quoting failed " << bad_string;
113 NSString* Sandbox::AllowMetadataForPath(const base::FilePath& allowed_path) {
114 // Collect a list of all parent directories.
115 base::FilePath last_path = allowed_path;
116 std::vector<base::FilePath> subpaths;
117 for (base::FilePath path = allowed_path;
118 path.value() != last_path.value();
119 path = path.DirName()) {
120 subpaths.push_back(path);
124 // Iterate through all parents and allow stat() on them explicitly.
125 NSString* sandbox_command = @"(allow file-read-metadata ";
126 for (std::vector<base::FilePath>::reverse_iterator i = subpaths.rbegin();
127 i != subpaths.rend();
129 std::string subdir_escaped;
130 if (!QuotePlainString(i->value(), &subdir_escaped)) {
131 FatalStringQuoteException(i->value());
135 NSString* subdir_escaped_ns =
136 base::SysUTF8ToNSString(subdir_escaped.c_str());
138 [sandbox_command stringByAppendingFormat:@"(literal \"%@\")",
142 return [sandbox_command stringByAppendingString:@")"];
146 bool Sandbox::QuotePlainString(const std::string& src_utf8, std::string* dst) {
149 const char* src = src_utf8.c_str();
150 int32_t length = src_utf8.length();
151 int32_t position = 0;
152 while (position < length) {
154 U8_NEXT(src, position, length, c); // Macro increments |position|.
159 if (c < 128) { // EscapeSingleChar only handles ASCII.
160 char as_char = static_cast<char>(c);
161 if (EscapeSingleChar(as_char, dst)) {
166 if (c < 32 || c > 126) {
167 // Any characters that aren't printable ASCII get the \u treatment.
168 unsigned int as_uint = static_cast<unsigned int>(c);
169 base::StringAppendF(dst, "\\u%04X", as_uint);
173 // If we got here we know that the character in question is strictly
174 // in the ASCII range so there's no need to do any kind of encoding
176 dst->push_back(static_cast<char>(c));
182 bool Sandbox::QuoteStringForRegex(const std::string& str_utf8,
184 // Characters with special meanings in sandbox profile syntax.
185 const char regex_special_chars[] = {
206 // Anchor regex at start of path.
209 const char* src = str_utf8.c_str();
210 int32_t length = str_utf8.length();
211 int32_t position = 0;
212 while (position < length) {
214 U8_NEXT(src, position, length, c); // Macro increments |position|.
219 // The Mac sandbox regex parser only handles printable ASCII characters.
221 if (c < 32 || c > 125) {
225 for (size_t i = 0; i < arraysize(regex_special_chars); ++i) {
226 if (c == regex_special_chars[i]) {
227 dst->push_back('\\');
232 dst->push_back(static_cast<char>(c));
235 // Make sure last element of path is interpreted as a directory. Leaving this
236 // off would allow access to files if they start with the same name as the
238 dst->append("(/|$)");
243 // Warm up System APIs that empirically need to be accessed before the Sandbox
245 // This method is layed out in blocks, each one containing a separate function
246 // that needs to be warmed up. The OS version on which we found the need to
247 // enable the function is also noted.
248 // This function is tested on the following OS versions:
252 void Sandbox::SandboxWarmup(int sandbox_type) {
253 base::mac::ScopedNSAutoreleasePool scoped_pool;
255 { // CGColorSpaceCreateWithName(), CGBitmapContextCreate() - 10.5.6
256 base::ScopedCFTypeRef<CGColorSpaceRef> rgb_colorspace(
257 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB));
259 // Allocate a 1x1 image.
261 base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate(
268 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host));
270 // Load in the color profiles we'll need (as a side effect).
271 (void) base::mac::GetSRGBColorSpace();
272 (void) base::mac::GetSystemColorSpace();
274 // CGColorSpaceCreateSystemDefaultCMYK - 10.6
275 base::ScopedCFTypeRef<CGColorSpaceRef> cmyk_colorspace(
276 CGColorSpaceCreateWithName(kCGColorSpaceGenericCMYK));
279 { // [-NSColor colorUsingColorSpaceName] - 10.5.6
280 NSColor* color = [NSColor controlTextColor];
281 [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
284 { // localtime() - 10.5.6
289 { // Gestalt() tries to read /System/Library/CoreServices/SystemVersion.plist
292 base::SysInfo::OperatingSystemVersionNumbers(&tmp, &tmp, &tmp);
295 { // CGImageSourceGetStatus() - 10.6
296 // Create a png with just enough data to get everything warmed up...
297 char png_header[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
298 NSData* data = [NSData dataWithBytes:png_header
299 length:arraysize(png_header)];
300 base::ScopedCFTypeRef<CGImageSourceRef> img(
301 CGImageSourceCreateWithData((CFDataRef)data, NULL));
302 CGImageSourceGetStatus(img);
306 // Allow access to /dev/urandom.
307 base::GetUrandomFD();
310 // Process-type dependent warm-up.
311 if (sandbox_type == SANDBOX_TYPE_UTILITY) {
312 // CFTimeZoneCopyZone() tries to read /etc and /private/etc/localtime - 10.8
313 // Needed by Media Galleries API Picasa - crbug.com/151701
314 CFTimeZoneCopySystem();
317 if (sandbox_type == SANDBOX_TYPE_GPU) {
318 // Preload either the desktop GL or the osmesa so, depending on the
320 gfx::GLSurface::InitializeOneOff();
325 NSString* Sandbox::BuildAllowDirectoryAccessSandboxString(
326 const base::FilePath& allowed_dir,
327 SandboxVariableSubstitions* substitutions) {
328 // A whitelist is used to determine which directories can be statted
329 // This means that in the case of an /a/b/c/d/ directory, we may be able to
330 // stat the leaf directory, but not its parent.
331 // The extension code in Chrome calls realpath() which fails if it can't call
332 // stat() on one of the parent directories in the path.
333 // The solution to this is to allow statting the parent directories themselves
334 // but not their contents. We need to add a separate rule for each parent
337 // The sandbox only understands "real" paths. This resolving step is
338 // needed so the caller doesn't need to worry about things like /var
339 // being a link to /private/var (like in the paths CreateNewTempDirectory()
341 base::FilePath allowed_dir_canonical = GetCanonicalSandboxPath(allowed_dir);
343 NSString* sandbox_command = AllowMetadataForPath(allowed_dir_canonical);
344 sandbox_command = [sandbox_command
345 substringToIndex:[sandbox_command length] - 1]; // strip trailing ')'
347 // Finally append the leaf directory. Unlike its parents (for which only
348 // stat() should be allowed), the leaf directory needs full access.
349 (*substitutions)["ALLOWED_DIR"] =
350 SandboxSubstring(allowed_dir_canonical.value(),
351 SandboxSubstring::REGEX);
354 stringByAppendingString:@") (allow file-read* file-write*"
355 " (regex #\"@ALLOWED_DIR@\") )"];
356 return sandbox_command;
359 // Load the appropriate template for the given sandbox type.
360 // Returns the template as an NSString or nil on error.
361 NSString* LoadSandboxTemplate(int sandbox_type) {
362 // We use a custom sandbox definition to lock things down as tightly as
364 int sandbox_profile_resource_id = -1;
366 // Find resource id for sandbox profile to use for the specific sandbox type.
368 i < arraysize(kDefaultSandboxTypeToResourceIDMapping);
370 if (kDefaultSandboxTypeToResourceIDMapping[i].sandbox_type ==
372 sandbox_profile_resource_id =
373 kDefaultSandboxTypeToResourceIDMapping[i].sandbox_profile_resource_id;
377 if (sandbox_profile_resource_id == -1) {
378 // Check if the embedder knows about this sandbox process type.
379 bool sandbox_type_found =
380 GetContentClient()->GetSandboxProfileForSandboxType(
381 sandbox_type, &sandbox_profile_resource_id);
382 CHECK(sandbox_type_found) << "Unknown sandbox type " << sandbox_type;
385 base::StringPiece sandbox_definition =
386 GetContentClient()->GetDataResource(
387 sandbox_profile_resource_id, ui::SCALE_FACTOR_NONE);
388 if (sandbox_definition.empty()) {
389 LOG(FATAL) << "Failed to load the sandbox profile (resource id "
390 << sandbox_profile_resource_id << ")";
394 base::StringPiece common_sandbox_definition =
395 GetContentClient()->GetDataResource(
396 IDR_COMMON_SANDBOX_PROFILE, ui::SCALE_FACTOR_NONE);
397 if (common_sandbox_definition.empty()) {
398 LOG(FATAL) << "Failed to load the common sandbox profile";
402 base::scoped_nsobject<NSString> common_sandbox_prefix_data(
403 [[NSString alloc] initWithBytes:common_sandbox_definition.data()
404 length:common_sandbox_definition.length()
405 encoding:NSUTF8StringEncoding]);
407 base::scoped_nsobject<NSString> sandbox_data(
408 [[NSString alloc] initWithBytes:sandbox_definition.data()
409 length:sandbox_definition.length()
410 encoding:NSUTF8StringEncoding]);
412 // Prefix sandbox_data with common_sandbox_prefix_data.
413 return [common_sandbox_prefix_data stringByAppendingString:sandbox_data];
417 bool Sandbox::PostProcessSandboxProfile(
418 NSString* sandbox_template,
419 NSArray* comments_to_remove,
420 SandboxVariableSubstitions& substitutions,
421 std::string *final_sandbox_profile_str) {
422 NSString* sandbox_data = [[sandbox_template copy] autorelease];
424 // Remove comments, e.g. ;10.7_OR_ABOVE .
425 for (NSString* to_remove in comments_to_remove) {
426 sandbox_data = [sandbox_data stringByReplacingOccurrencesOfString:to_remove
430 // Split string on "@" characters.
431 std::vector<std::string> raw_sandbox_pieces;
432 if (Tokenize([sandbox_data UTF8String], "@", &raw_sandbox_pieces) == 0) {
433 DLOG(FATAL) << "Bad Sandbox profile, should contain at least one token ("
434 << [sandbox_data UTF8String]
439 // Iterate over string pieces and substitute variables, escaping as necessary.
440 size_t output_string_length = 0;
441 std::vector<std::string> processed_sandbox_pieces(raw_sandbox_pieces.size());
442 for (std::vector<std::string>::iterator it = raw_sandbox_pieces.begin();
443 it != raw_sandbox_pieces.end();
445 std::string new_piece;
446 SandboxVariableSubstitions::iterator replacement_it =
447 substitutions.find(*it);
448 if (replacement_it == substitutions.end()) {
451 // Found something to substitute.
452 SandboxSubstring& replacement = replacement_it->second;
453 switch (replacement.type()) {
454 case SandboxSubstring::PLAIN:
455 new_piece = replacement.value();
458 case SandboxSubstring::LITERAL:
459 if (!QuotePlainString(replacement.value(), &new_piece))
460 FatalStringQuoteException(replacement.value());
463 case SandboxSubstring::REGEX:
464 if (!QuoteStringForRegex(replacement.value(), &new_piece))
465 FatalStringQuoteException(replacement.value());
469 output_string_length += new_piece.size();
470 processed_sandbox_pieces.push_back(new_piece);
473 // Build final output string.
474 final_sandbox_profile_str->reserve(output_string_length);
476 for (std::vector<std::string>::iterator it = processed_sandbox_pieces.begin();
477 it != processed_sandbox_pieces.end();
479 final_sandbox_profile_str->append(*it);
485 // Turns on the OS X sandbox for this process.
488 bool Sandbox::EnableSandbox(int sandbox_type,
489 const base::FilePath& allowed_dir) {
490 // Sanity - currently only SANDBOX_TYPE_UTILITY supports a directory being
492 if (sandbox_type < SANDBOX_TYPE_AFTER_LAST_TYPE &&
493 sandbox_type != SANDBOX_TYPE_UTILITY) {
494 DCHECK(allowed_dir.empty())
495 << "Only SANDBOX_TYPE_UTILITY allows a custom directory parameter.";
498 NSString* sandbox_data = LoadSandboxTemplate(sandbox_type);
503 SandboxVariableSubstitions substitutions;
504 if (!allowed_dir.empty()) {
505 // Add the sandbox commands necessary to access the given directory.
506 // Note: this function must be called before PostProcessSandboxProfile()
507 // since the string it inserts contains variables that need substitution.
508 NSString* allowed_dir_sandbox_command =
509 BuildAllowDirectoryAccessSandboxString(allowed_dir, &substitutions);
511 if (allowed_dir_sandbox_command) { // May be nil if function fails.
512 sandbox_data = [sandbox_data
513 stringByReplacingOccurrencesOfString:@";ENABLE_DIRECTORY_ACCESS"
514 withString:allowed_dir_sandbox_command];
518 NSMutableArray* tokens_to_remove = [NSMutableArray array];
520 // Enable verbose logging if enabled on the command line. (See common.sb
522 const CommandLine* command_line = CommandLine::ForCurrentProcess();
523 bool enable_logging =
524 command_line->HasSwitch(switches::kEnableSandboxLogging);;
525 if (enable_logging) {
526 [tokens_to_remove addObject:@";ENABLE_LOGGING"];
529 bool lion_or_later = base::mac::IsOSLionOrLater();
531 // Without this, the sandbox will print a message to the system log every
532 // time it denies a request. This floods the console with useless spew.
533 if (!enable_logging) {
534 substitutions["DISABLE_SANDBOX_DENIAL_LOGGING"] =
535 SandboxSubstring("(with no-log)");
537 substitutions["DISABLE_SANDBOX_DENIAL_LOGGING"] = SandboxSubstring("");
540 // Splice the path of the user's home directory into the sandbox profile
541 // (see renderer.sb for details).
542 std::string home_dir = [NSHomeDirectory() fileSystemRepresentation];
544 base::FilePath home_dir_canonical =
545 GetCanonicalSandboxPath(base::FilePath(home_dir));
547 substitutions["USER_HOMEDIR_AS_LITERAL"] =
548 SandboxSubstring(home_dir_canonical.value(),
549 SandboxSubstring::LITERAL);
552 // >=10.7 Sandbox rules.
553 [tokens_to_remove addObject:@";10.7_OR_ABOVE"];
556 substitutions["COMPONENT_BUILD_WORKAROUND"] = SandboxSubstring("");
557 #if defined(COMPONENT_BUILD)
558 // dlopen() fails without file-read-metadata access if the executable image
559 // contains LC_RPATH load commands. The components build uses those.
560 // See http://crbug.com/127465
561 if (base::mac::IsOSSnowLeopard()) {
562 base::FilePath bundle_executable = base::mac::NSStringToFilePath(
563 [base::mac::MainBundle() executablePath]);
564 NSString* sandbox_command = AllowMetadataForPath(
565 GetCanonicalSandboxPath(bundle_executable));
566 substitutions["COMPONENT_BUILD_WORKAROUND"] =
567 SandboxSubstring(base::SysNSStringToUTF8(sandbox_command));
571 // All information needed to assemble the final profile has been collected.
572 // Merge it all together.
573 std::string final_sandbox_profile_str;
574 if (!PostProcessSandboxProfile(sandbox_data, tokens_to_remove, substitutions,
575 &final_sandbox_profile_str)) {
579 // Initialize sandbox.
580 char* error_buff = NULL;
581 int error = sandbox_init(final_sandbox_profile_str.c_str(), 0, &error_buff);
582 bool success = (error == 0 && error_buff == NULL);
583 DLOG_IF(FATAL, !success) << "Failed to initialize sandbox: "
587 sandbox_free_error(error_buff);
588 gSandboxIsActive = success;
593 bool Sandbox::SandboxIsCurrentlyActive() {
594 return gSandboxIsActive;
598 base::FilePath Sandbox::GetCanonicalSandboxPath(const base::FilePath& path) {
599 int fd = HANDLE_EINTR(open(path.value().c_str(), O_RDONLY));
601 DPLOG(FATAL) << "GetCanonicalSandboxPath() failed for: "
605 file_util::ScopedFD file_closer(&fd);
607 base::FilePath::CharType canonical_path[MAXPATHLEN];
608 if (HANDLE_EINTR(fcntl(fd, F_GETPATH, canonical_path)) != 0) {
609 DPLOG(FATAL) << "GetCanonicalSandboxPath() failed for: "
614 return base::FilePath(canonical_path);
617 } // namespace content