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/files/scoped_file.h"
21 #include "base/mac/bundle_locations.h"
22 #include "base/mac/mac_util.h"
23 #include "base/mac/scoped_cftyperef.h"
24 #include "base/mac/scoped_nsautorelease_pool.h"
25 #include "base/mac/scoped_nsobject.h"
26 #include "base/rand_util.h"
27 #include "base/strings/string16.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/stringprintf.h"
31 #include "base/strings/sys_string_conversions.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "base/sys_info.h"
34 #include "content/public/common/content_client.h"
35 #include "content/public/common/content_switches.h"
36 #include "grit/content_resources.h"
37 #include "third_party/icu/source/common/unicode/uchar.h"
38 #include "ui/base/layout.h"
39 #include "ui/gl/gl_surface.h"
44 // Is the sandbox currently active.
45 bool gSandboxIsActive = false;
47 struct SandboxTypeToResourceIDMapping {
48 SandboxType sandbox_type;
49 int sandbox_profile_resource_id;
52 // Mapping from sandbox process types to resource IDs containing the sandbox
53 // profile for all process types known to content.
54 SandboxTypeToResourceIDMapping kDefaultSandboxTypeToResourceIDMapping[] = {
55 { SANDBOX_TYPE_RENDERER, IDR_RENDERER_SANDBOX_PROFILE },
56 { SANDBOX_TYPE_WORKER, IDR_WORKER_SANDBOX_PROFILE },
57 { SANDBOX_TYPE_UTILITY, IDR_UTILITY_SANDBOX_PROFILE },
58 { SANDBOX_TYPE_GPU, IDR_GPU_SANDBOX_PROFILE },
59 { SANDBOX_TYPE_PPAPI, IDR_PPAPI_SANDBOX_PROFILE },
62 COMPILE_ASSERT(arraysize(kDefaultSandboxTypeToResourceIDMapping) == \
63 size_t(SANDBOX_TYPE_AFTER_LAST_TYPE), \
64 sandbox_type_to_resource_id_mapping_incorrect);
66 // Try to escape |c| as a "SingleEscapeCharacter" (\n, etc). If successful,
67 // returns true and appends the escape sequence to |dst|.
68 bool EscapeSingleChar(char c, std::string* dst) {
69 const char *append = NULL;
102 // Errors quoting strings for the Sandbox profile are always fatal, report them
103 // in a central place.
104 NOINLINE void FatalStringQuoteException(const std::string& str) {
105 // Copy bad string to the stack so it's recorded in the crash dump.
106 char bad_string[256] = {0};
107 base::strlcpy(bad_string, str.c_str(), arraysize(bad_string));
108 DLOG(FATAL) << "String quoting failed " << bad_string;
114 NSString* Sandbox::AllowMetadataForPath(const base::FilePath& allowed_path) {
115 // Collect a list of all parent directories.
116 base::FilePath last_path = allowed_path;
117 std::vector<base::FilePath> subpaths;
118 for (base::FilePath path = allowed_path;
119 path.value() != last_path.value();
120 path = path.DirName()) {
121 subpaths.push_back(path);
125 // Iterate through all parents and allow stat() on them explicitly.
126 NSString* sandbox_command = @"(allow file-read-metadata ";
127 for (std::vector<base::FilePath>::reverse_iterator i = subpaths.rbegin();
128 i != subpaths.rend();
130 std::string subdir_escaped;
131 if (!QuotePlainString(i->value(), &subdir_escaped)) {
132 FatalStringQuoteException(i->value());
136 NSString* subdir_escaped_ns =
137 base::SysUTF8ToNSString(subdir_escaped.c_str());
139 [sandbox_command stringByAppendingFormat:@"(literal \"%@\")",
143 return [sandbox_command stringByAppendingString:@")"];
147 bool Sandbox::QuotePlainString(const std::string& src_utf8, std::string* dst) {
150 const char* src = src_utf8.c_str();
151 int32_t length = src_utf8.length();
152 int32_t position = 0;
153 while (position < length) {
155 U8_NEXT(src, position, length, c); // Macro increments |position|.
160 if (c < 128) { // EscapeSingleChar only handles ASCII.
161 char as_char = static_cast<char>(c);
162 if (EscapeSingleChar(as_char, dst)) {
167 if (c < 32 || c > 126) {
168 // Any characters that aren't printable ASCII get the \u treatment.
169 unsigned int as_uint = static_cast<unsigned int>(c);
170 base::StringAppendF(dst, "\\u%04X", as_uint);
174 // If we got here we know that the character in question is strictly
175 // in the ASCII range so there's no need to do any kind of encoding
177 dst->push_back(static_cast<char>(c));
183 bool Sandbox::QuoteStringForRegex(const std::string& str_utf8,
185 // Characters with special meanings in sandbox profile syntax.
186 const char regex_special_chars[] = {
207 // Anchor regex at start of path.
210 const char* src = str_utf8.c_str();
211 int32_t length = str_utf8.length();
212 int32_t position = 0;
213 while (position < length) {
215 U8_NEXT(src, position, length, c); // Macro increments |position|.
220 // The Mac sandbox regex parser only handles printable ASCII characters.
222 if (c < 32 || c > 125) {
226 for (size_t i = 0; i < arraysize(regex_special_chars); ++i) {
227 if (c == regex_special_chars[i]) {
228 dst->push_back('\\');
233 dst->push_back(static_cast<char>(c));
236 // Make sure last element of path is interpreted as a directory. Leaving this
237 // off would allow access to files if they start with the same name as the
239 dst->append("(/|$)");
244 // Warm up System APIs that empirically need to be accessed before the Sandbox
246 // This method is layed out in blocks, each one containing a separate function
247 // that needs to be warmed up. The OS version on which we found the need to
248 // enable the function is also noted.
249 // This function is tested on the following OS versions:
253 void Sandbox::SandboxWarmup(int sandbox_type) {
254 base::mac::ScopedNSAutoreleasePool scoped_pool;
256 { // CGColorSpaceCreateWithName(), CGBitmapContextCreate() - 10.5.6
257 base::ScopedCFTypeRef<CGColorSpaceRef> rgb_colorspace(
258 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB));
260 // Allocate a 1x1 image.
262 base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate(
269 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host));
271 // Load in the color profiles we'll need (as a side effect).
272 (void) base::mac::GetSRGBColorSpace();
273 (void) base::mac::GetSystemColorSpace();
275 // CGColorSpaceCreateSystemDefaultCMYK - 10.6
276 base::ScopedCFTypeRef<CGColorSpaceRef> cmyk_colorspace(
277 CGColorSpaceCreateWithName(kCGColorSpaceGenericCMYK));
280 { // localtime() - 10.5.6
285 { // Gestalt() tries to read /System/Library/CoreServices/SystemVersion.plist
288 base::SysInfo::OperatingSystemVersionNumbers(&tmp, &tmp, &tmp);
291 { // CGImageSourceGetStatus() - 10.6
292 // Create a png with just enough data to get everything warmed up...
293 char png_header[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
294 NSData* data = [NSData dataWithBytes:png_header
295 length:arraysize(png_header)];
296 base::ScopedCFTypeRef<CGImageSourceRef> img(
297 CGImageSourceCreateWithData((CFDataRef)data, NULL));
298 CGImageSourceGetStatus(img);
302 // Allow access to /dev/urandom.
303 base::GetUrandomFD();
306 { // IOSurfaceLookup() - 10.7
307 // Needed by zero-copy texture update framework - crbug.com/323338
308 base::ScopedCFTypeRef<IOSurfaceRef> io_surface(IOSurfaceLookup(0));
311 // Process-type dependent warm-up.
312 if (sandbox_type == SANDBOX_TYPE_UTILITY) {
313 // CFTimeZoneCopyZone() tries to read /etc and /private/etc/localtime - 10.8
314 // Needed by Media Galleries API Picasa - crbug.com/151701
315 CFTimeZoneCopySystem();
318 if (sandbox_type == SANDBOX_TYPE_GPU) {
319 // Preload either the desktop GL or the osmesa so, depending on the
321 gfx::GLSurface::InitializeOneOff();
324 if (sandbox_type == SANDBOX_TYPE_PPAPI) {
325 // Preload AppKit color spaces used for Flash/ppapi. http://crbug.com/348304
326 NSColor* color = [NSColor controlTextColor];
327 [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
332 NSString* Sandbox::BuildAllowDirectoryAccessSandboxString(
333 const base::FilePath& allowed_dir,
334 SandboxVariableSubstitions* substitutions) {
335 // A whitelist is used to determine which directories can be statted
336 // This means that in the case of an /a/b/c/d/ directory, we may be able to
337 // stat the leaf directory, but not its parent.
338 // The extension code in Chrome calls realpath() which fails if it can't call
339 // stat() on one of the parent directories in the path.
340 // The solution to this is to allow statting the parent directories themselves
341 // but not their contents. We need to add a separate rule for each parent
344 // The sandbox only understands "real" paths. This resolving step is
345 // needed so the caller doesn't need to worry about things like /var
346 // being a link to /private/var (like in the paths CreateNewTempDirectory()
348 base::FilePath allowed_dir_canonical = GetCanonicalSandboxPath(allowed_dir);
350 NSString* sandbox_command = AllowMetadataForPath(allowed_dir_canonical);
351 sandbox_command = [sandbox_command
352 substringToIndex:[sandbox_command length] - 1]; // strip trailing ')'
354 // Finally append the leaf directory. Unlike its parents (for which only
355 // stat() should be allowed), the leaf directory needs full access.
356 (*substitutions)["ALLOWED_DIR"] =
357 SandboxSubstring(allowed_dir_canonical.value(),
358 SandboxSubstring::REGEX);
361 stringByAppendingString:@") (allow file-read* file-write*"
362 " (regex #\"@ALLOWED_DIR@\") )"];
363 return sandbox_command;
366 // Load the appropriate template for the given sandbox type.
367 // Returns the template as an NSString or nil on error.
368 NSString* LoadSandboxTemplate(int sandbox_type) {
369 // We use a custom sandbox definition to lock things down as tightly as
371 int sandbox_profile_resource_id = -1;
373 // Find resource id for sandbox profile to use for the specific sandbox type.
375 i < arraysize(kDefaultSandboxTypeToResourceIDMapping);
377 if (kDefaultSandboxTypeToResourceIDMapping[i].sandbox_type ==
379 sandbox_profile_resource_id =
380 kDefaultSandboxTypeToResourceIDMapping[i].sandbox_profile_resource_id;
384 if (sandbox_profile_resource_id == -1) {
385 // Check if the embedder knows about this sandbox process type.
386 bool sandbox_type_found =
387 GetContentClient()->GetSandboxProfileForSandboxType(
388 sandbox_type, &sandbox_profile_resource_id);
389 CHECK(sandbox_type_found) << "Unknown sandbox type " << sandbox_type;
392 base::StringPiece sandbox_definition =
393 GetContentClient()->GetDataResource(
394 sandbox_profile_resource_id, ui::SCALE_FACTOR_NONE);
395 if (sandbox_definition.empty()) {
396 LOG(FATAL) << "Failed to load the sandbox profile (resource id "
397 << sandbox_profile_resource_id << ")";
401 base::StringPiece common_sandbox_definition =
402 GetContentClient()->GetDataResource(
403 IDR_COMMON_SANDBOX_PROFILE, ui::SCALE_FACTOR_NONE);
404 if (common_sandbox_definition.empty()) {
405 LOG(FATAL) << "Failed to load the common sandbox profile";
409 base::scoped_nsobject<NSString> common_sandbox_prefix_data(
410 [[NSString alloc] initWithBytes:common_sandbox_definition.data()
411 length:common_sandbox_definition.length()
412 encoding:NSUTF8StringEncoding]);
414 base::scoped_nsobject<NSString> sandbox_data(
415 [[NSString alloc] initWithBytes:sandbox_definition.data()
416 length:sandbox_definition.length()
417 encoding:NSUTF8StringEncoding]);
419 // Prefix sandbox_data with common_sandbox_prefix_data.
420 return [common_sandbox_prefix_data stringByAppendingString:sandbox_data];
424 bool Sandbox::PostProcessSandboxProfile(
425 NSString* sandbox_template,
426 NSArray* comments_to_remove,
427 SandboxVariableSubstitions& substitutions,
428 std::string *final_sandbox_profile_str) {
429 NSString* sandbox_data = [[sandbox_template copy] autorelease];
431 // Remove comments, e.g. ;10.7_OR_ABOVE .
432 for (NSString* to_remove in comments_to_remove) {
433 sandbox_data = [sandbox_data stringByReplacingOccurrencesOfString:to_remove
437 // Split string on "@" characters.
438 std::vector<std::string> raw_sandbox_pieces;
439 if (Tokenize([sandbox_data UTF8String], "@", &raw_sandbox_pieces) == 0) {
440 DLOG(FATAL) << "Bad Sandbox profile, should contain at least one token ("
441 << [sandbox_data UTF8String]
446 // Iterate over string pieces and substitute variables, escaping as necessary.
447 size_t output_string_length = 0;
448 std::vector<std::string> processed_sandbox_pieces(raw_sandbox_pieces.size());
449 for (std::vector<std::string>::iterator it = raw_sandbox_pieces.begin();
450 it != raw_sandbox_pieces.end();
452 std::string new_piece;
453 SandboxVariableSubstitions::iterator replacement_it =
454 substitutions.find(*it);
455 if (replacement_it == substitutions.end()) {
458 // Found something to substitute.
459 SandboxSubstring& replacement = replacement_it->second;
460 switch (replacement.type()) {
461 case SandboxSubstring::PLAIN:
462 new_piece = replacement.value();
465 case SandboxSubstring::LITERAL:
466 if (!QuotePlainString(replacement.value(), &new_piece))
467 FatalStringQuoteException(replacement.value());
470 case SandboxSubstring::REGEX:
471 if (!QuoteStringForRegex(replacement.value(), &new_piece))
472 FatalStringQuoteException(replacement.value());
476 output_string_length += new_piece.size();
477 processed_sandbox_pieces.push_back(new_piece);
480 // Build final output string.
481 final_sandbox_profile_str->reserve(output_string_length);
483 for (std::vector<std::string>::iterator it = processed_sandbox_pieces.begin();
484 it != processed_sandbox_pieces.end();
486 final_sandbox_profile_str->append(*it);
492 // Turns on the OS X sandbox for this process.
495 bool Sandbox::EnableSandbox(int sandbox_type,
496 const base::FilePath& allowed_dir) {
497 // Sanity - currently only SANDBOX_TYPE_UTILITY supports a directory being
499 if (sandbox_type < SANDBOX_TYPE_AFTER_LAST_TYPE &&
500 sandbox_type != SANDBOX_TYPE_UTILITY) {
501 DCHECK(allowed_dir.empty())
502 << "Only SANDBOX_TYPE_UTILITY allows a custom directory parameter.";
505 NSString* sandbox_data = LoadSandboxTemplate(sandbox_type);
510 SandboxVariableSubstitions substitutions;
511 if (!allowed_dir.empty()) {
512 // Add the sandbox commands necessary to access the given directory.
513 // Note: this function must be called before PostProcessSandboxProfile()
514 // since the string it inserts contains variables that need substitution.
515 NSString* allowed_dir_sandbox_command =
516 BuildAllowDirectoryAccessSandboxString(allowed_dir, &substitutions);
518 if (allowed_dir_sandbox_command) { // May be nil if function fails.
519 sandbox_data = [sandbox_data
520 stringByReplacingOccurrencesOfString:@";ENABLE_DIRECTORY_ACCESS"
521 withString:allowed_dir_sandbox_command];
525 NSMutableArray* tokens_to_remove = [NSMutableArray array];
527 // Enable verbose logging if enabled on the command line. (See common.sb
529 const CommandLine* command_line = CommandLine::ForCurrentProcess();
530 bool enable_logging =
531 command_line->HasSwitch(switches::kEnableSandboxLogging);;
532 if (enable_logging) {
533 [tokens_to_remove addObject:@";ENABLE_LOGGING"];
536 bool lion_or_later = base::mac::IsOSLionOrLater();
538 // Without this, the sandbox will print a message to the system log every
539 // time it denies a request. This floods the console with useless spew.
540 if (!enable_logging) {
541 substitutions["DISABLE_SANDBOX_DENIAL_LOGGING"] =
542 SandboxSubstring("(with no-log)");
544 substitutions["DISABLE_SANDBOX_DENIAL_LOGGING"] = SandboxSubstring("");
547 // Splice the path of the user's home directory into the sandbox profile
548 // (see renderer.sb for details).
549 std::string home_dir = [NSHomeDirectory() fileSystemRepresentation];
551 base::FilePath home_dir_canonical =
552 GetCanonicalSandboxPath(base::FilePath(home_dir));
554 substitutions["USER_HOMEDIR_AS_LITERAL"] =
555 SandboxSubstring(home_dir_canonical.value(),
556 SandboxSubstring::LITERAL);
559 // >=10.7 Sandbox rules.
560 [tokens_to_remove addObject:@";10.7_OR_ABOVE"];
563 substitutions["COMPONENT_BUILD_WORKAROUND"] = SandboxSubstring("");
564 #if defined(COMPONENT_BUILD)
565 // dlopen() fails without file-read-metadata access if the executable image
566 // contains LC_RPATH load commands. The components build uses those.
567 // See http://crbug.com/127465
568 if (base::mac::IsOSSnowLeopard()) {
569 base::FilePath bundle_executable = base::mac::NSStringToFilePath(
570 [base::mac::MainBundle() executablePath]);
571 NSString* sandbox_command = AllowMetadataForPath(
572 GetCanonicalSandboxPath(bundle_executable));
573 substitutions["COMPONENT_BUILD_WORKAROUND"] =
574 SandboxSubstring(base::SysNSStringToUTF8(sandbox_command));
578 // All information needed to assemble the final profile has been collected.
579 // Merge it all together.
580 std::string final_sandbox_profile_str;
581 if (!PostProcessSandboxProfile(sandbox_data, tokens_to_remove, substitutions,
582 &final_sandbox_profile_str)) {
586 // Initialize sandbox.
587 char* error_buff = NULL;
588 int error = sandbox_init(final_sandbox_profile_str.c_str(), 0, &error_buff);
589 bool success = (error == 0 && error_buff == NULL);
590 DLOG_IF(FATAL, !success) << "Failed to initialize sandbox: "
594 sandbox_free_error(error_buff);
595 gSandboxIsActive = success;
600 bool Sandbox::SandboxIsCurrentlyActive() {
601 return gSandboxIsActive;
605 base::FilePath Sandbox::GetCanonicalSandboxPath(const base::FilePath& path) {
606 base::ScopedFD fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
607 if (!fd.is_valid()) {
608 DPLOG(FATAL) << "GetCanonicalSandboxPath() failed for: "
613 base::FilePath::CharType canonical_path[MAXPATHLEN];
614 if (HANDLE_EINTR(fcntl(fd.get(), F_GETPATH, canonical_path)) != 0) {
615 DPLOG(FATAL) << "GetCanonicalSandboxPath() failed for: "
620 return base::FilePath(canonical_path);
623 } // namespace content