Author Archives: Google Security PR

Towards native security defenses for the web ecosystem



With the recent launch of Chrome 83, and the upcoming release of Mozilla Firefox 79, web developers are gaining powerful new security mechanisms to protect their applications from common web vulnerabilities. In this post we share how our Information Security Engineering team is deploying Trusted Types, Content Security Policy, Fetch Metadata Request Headers and the Cross-Origin Opener Policy across Google to help guide and inspire other developers to similarly adopt these features to protect their applications.

History

Since the advent of modern web applications, such as email clients or document editors accessible in your browser, developers have been dealing with common web vulnerabilities which may allow user data to fall prey to attackers. While the web platform provides robust isolation for the underlying operating system, the isolation between web applications themselves is a different story. Issues such as XSS, CSRF and cross-site leaks have become unfortunate facets of web development, affecting almost every website at some point in time.

These vulnerabilities are unintended consequences of some of the web's most wonderful characteristics: composability, openness, and ease of development. Simply put, the original vision of the web as a mesh of interconnected documents did not anticipate the creation of a vibrant ecosystem of web applications handling private data for billions of people across the globe. Consequently, the security capabilities of the web platform meant to help developers safeguard their users' data have evolved slowly and provided only partial protections from common flaws.

Web developers have traditionally compensated for the platform's shortcomings by building additional security engineering tools and processes to protect their applications from common flaws; such infrastructure has often proven costly to develop and maintain. As the web continues to change to offer developers more impressive capabilities, and web applications become more critical to our lives, we find ourselves in increasing need of more powerful, all-encompassing security mechanisms built directly into the web platform.

Over the past two years, browser makers and security engineers from Google and other companies have collaborated on the design and implementation of several major security features to defend against common web flaws. These mechanisms, which we focus on in this post, protect against injections and offer isolation capabilities, addressing two major, long-standing sources of insecurity on the web.

Injection Vulnerabilities

In the design of systems, mixing code and data is one of the canonical security anti-patterns, causing software vulnerabilities as far back as in the 1980s. It is the root cause of vulnerabilities such as SQL injection and command injection, allowing the compromise of databases and application servers.

On the web, application code has historically been intertwined with page data. HTML markup such as <script> elements or event handler attributes (onclick or onload) allow JavaScript execution; even the familiar URL can carry code and result in script execution when navigating to a javascript: link. While sometimes convenient, the upshot of this design is that – unless the application takes care to protect itself – data used to compose an HTML page can easily inject unwanted scripts and take control of the application in the user's browser.

Addressing this problem in a principled manner requires allowing the application to separate its data from code; this can be done by enabling two new security features: Trusted Types and Content Security Policy based on script nonces.

Trusted Types
Main article: web.dev/trusted-types by Krzysztof Kotowicz

JavaScript functions used by developers to build web applications often rely on parsing arbitrary structure out of strings. A string which seems to contain data can be turned directly into code when passed to a common API, such as innerHTML. This is the root cause of most DOM-based XSS vulnerabilities.

Trusted Types make JavaScript code safe-by-default by restricting risky operations, such as generating HTML or creating scripts, to require a special object – a Trusted Type. The browser will ensure that any use of dangerous DOM functions is allowed only if the right object is provided to the function. As long as an application produces these objects safely in a central Trusted Types policy, it will be free of DOM-based XSS bugs.

You can enable Trusted Types by setting the following response header:
We have recently launched Trusted Types for all users of My Google Activity and are working with dozens of product teams across Google as well as JavaScript framework owners to make their code support this important safety mechanism.

Trusted Types are supported in Chrome 83 and other Chromium-based browsers, and a polyfill is available for other user agents.

Content Security Policy based on script nonces
Main article: Reshaping web defenses with strict Content Security Policy

Content Security Policy (CSP) allows developers to require every <script> on the page to contain a secret value unknown to attackers. The script nonce attribute, set to an unpredictable number for every page load, acts as a guarantee that a given script is under the control of the application: even if part of the page is injected by an attacker, the browser will refuse to execute any injected script which doesn't identify itself with the correct nonce. This mitigates the impact of any server-side injection bugs, such as reflected XSS and stored XSS.

CSP can be enabled by setting the following HTTP response header:
This header requires all scripts in your HTML templating system to include a nonce attribute with a value matching the one in the response header:
Our CSP Evaluator tool can help you configure a strong policy. To help deploy a production-quality CSP in your application, check out this presentation and the documentation on csp.withgoogle.com.

Since the initial launch of CSP at Google, we have deployed strong policies on 75% of outgoing traffic from our applications, including in our flagship products such as GMail and Google Docs & Drive. CSP has mitigated the exploitation of over 30 high-risk XSS flaws across Google in the past two years.

Nonce-based CSP is supported in Chrome, Firefox, Microsoft Edge and other Chromium-based browsers. Partial support for this variant of CSP is also available in Safari.

Isolation Capabilities

Many kinds of web flaws are exploited by an attacker's site forcing an unwanted interaction with another web application. Preventing these issues requires browsers to offer new mechanisms to allow applications to restrict such behaviors. Fetch Metadata Request Headers enable building server-side restrictions when processing incoming HTTP requests; the Cross-Origin Opener Policy is a client-side mechanism which protects the application's windows from unwanted DOM interactions.

Fetch Metadata Request Headers
Main article: web.dev/fetch-metadata by Lukas Weichselbaum

A common cause of web security problems is that applications don't receive information about the source of a given HTTP request, and thus aren't able to distinguish benign self-initiated web traffic from unwanted requests sent by other websites. This leads to vulnerabilities such as cross-site request forgery (CSRF) and web-based information leaks (XS-leaks).

Fetch Metadata headers, which the browser attaches to outgoing HTTP requests, solve this problem by providing the application with trustworthy information about the provenance of requests sent to the server: the source of the request, its type (for example, whether it's a navigation or resource request), and other security-relevant metadata.

By checking the values of these new HTTP headers (Sec-Fetch-Site, Sec-Fetch-Mode and Sec-Fetch-Dest), applications can build flexible server-side logic to reject untrusted requests, similar to the following:
We provided a detailed explanation of this logic and adoption considerations at web.dev/fetch-metadata. Importantly, Fetch Metadata can both complement and facilitate the adoption of Cross-Origin Resource Policy which offers client-side protection against unexpected subresource loads; this header is described in detail at resourcepolicy.fyi.

At Google, we've enabled restrictions using Fetch Metadata headers in several major products such as Google Photos, and are following up with a large-scale rollout across our application ecosystem.

Fetch Metadata headers are currently sent by Chrome and Chromium-based browsers and are available in development versions of Firefox.

Cross-Origin Opener Policy
Main article: web.dev/coop-coep by Eiji Kitamura

By default, the web permits some interactions with browser windows belonging to another application: any site can open a pop-up to your webmail client and send it messages via the postMessage API, navigate it to another URL, or obtain information about its frames. All of these capabilities can lead to information leak vulnerabilities:
Cross-Origin Opener Policy (COOP) allows you to lock down your application to prevent such interactions. To enable COOP in your application, set the following HTTP response header:
If your application opens other sites as pop-ups, you may need to set the header value to same-origin-allow-popups instead; see this document for details.

We are currently testing Cross-Origin Opener Policy in several Google applications, and we're looking forward to enabling it broadly in the coming months.

COOP is available starting in Chrome 83 and in Firefox 79.

The Future

Creating a strong and vibrant web requires developers to be able to guarantee the safety of their users' data. Adding security mechanisms to the web platform – building them directly into browsers – is an important step forward for the ecosystem: browsers can help developers understand and control aspects of their sites which affect their security posture. As users update to recent versions of their favorite browsers, they will gain protections from many of the security flaws that have affected web applications in the past.

While the security features described in this post are not a panacea, they offer fundamental building blocks that help developers build secure web applications. We're excited about the continued deployment of these mechanisms across Google, and we're looking forward to collaborating with browser makers and the web standards community to improve them in the future.

For more information about web security mechanisms and the bugs they prevent, see the Securing Web Apps with Modern Platform Features Google I/O talk (video).

The Advanced Protection Program comes to Google Nest



The Advanced Protection Program is our strongest level of Google Account security for people at high risk of targeted online attacks, such as journalists, activists, business leaders, and people working on elections. Anyone can sign up to automatically receive extra safeguards against phishing, malware, and fraudulent access to their data.

Since we launched, one of our goals has been to bring Advanced Protection’s features to other Google products. Over the years, we’ve incorporated many of them into GSuite, Google Cloud Platform, Chrome, and most recently, Android. We want as many users as possible to benefit from the additional levels of security that the Program provides.

Today we’re announcing one of the top requests we’ve received: to bring the Advanced Protection Program to Nest.  Now people can seamlessly use their Google Accounts with both Advanced Protection and Google Nest devices -- previously, a user could use their Google Account on only one of these at a time.

Feeling safe at home has never been more important and Nest has announced a variety of new security features this year, including using reCAPTCHA Enterprise, to significantly lower the likelihood of automated attacks. Today’s improvement adds yet another layer of protection for people with Nest devices.

For more information about using Advanced Protection with Google Nest devices, check out this article in our help center.

Protecting Chrome users in Kazakhstan



When making secure connections, Chrome trusts certificates that have been locally installed on a user's computer or mobile device. This allows users to run tools to inspect and debug connections during website development, or for corporate environments to intercept and monitor internal traffic. It is not appropriate for this mechanism to be used to intercept traffic on the public internet.

In response to recent actions by the Kazakhstan government, Chrome, along with other browsers, has taken steps to protect users from the interception or modification of TLS connections made to websites.

Chrome will be blocking the certificate the Kazakhstan government required users to install:

Common Name
Qaznet Trust Network
SHA-256 Fingerprint
00:30:9C:73:6D:D6:61:DA:6F:1E:B2:41:73:AA:84:99:44:C1:68:A4:3A:15:
BF:FD:19:2E:EC:FD:B6:F8:DB:D2
SHA-256 of Subject Public Key Info
B5:BA:8D:D7:F8:95:64:C2:88:9D:3D:64:53:C8:49:98:C7:78:24:91:9B:64:
EA:08:35:AA:62:98:65:91:BE:50


The certificate has been added to CRLSet. No action is needed by users to be protected. In addition, the certificate will be added to a blocklist in the Chromium source code and thus should be included in other Chromium based browsers in due course.

New Research: Lessons from Password Checkup in action



Back in February, we announced the Password Checkup extension for Chrome to help keep all your online accounts safe from hijacking. The extension displays a warning whenever you sign in to a site using one of over 4 billion usernames and passwords that Google knows to be unsafe due to a third-party data breach. Since our launch, over 650,000 people have participated in our early experiment. In the first month alone, we scanned 21 million usernames and passwords and flagged over 316,000 as unsafe---1.5% of sign-ins scanned by the extension.
Today, we are sharing our most recent lessons from the launch and announcing an updated set of features for the Password Checkup extension. Our full research study, available here, will be presented this week as part of the USENIX Security Symposium.

Which accounts are most at risk?

Hijackers routinely attempt to sign in to sites across the web with every credential exposed by a third-party breach. If you use strong, unique passwords for all your accounts, this risk disappears. Based on anonymous telemetry reported by the Password Checkup extension, we found that users reused breached, unsafe credentials for some of their most sensitive financial, government, and email accounts. This risk was even more prevalent on shopping sites (where users may save credit card details), news, and entertainment sites.

In fact, outside the most popular web sites, users are 2.5X more likely to reuse vulnerable passwords, putting their account at risk of hijacking.
Anonymous telemetry reported by Password Checkup extension shows that users most often reuse vulnerable passwords on shopping, news, and entertainment sites.


Helping users re-secure their unsafe passwords

Our research shows that users opt to reset 26% of the unsafe passwords flagged by the Password Checkup extension. Even better, 60% of new passwords are secure against guessing attacks—meaning it would take an attacker over a hundred million guesses before identifying the new password.
Improving the Password Checkup extension

Today, we are also releasing two new features for the Password Checkup extension. The first is a direct feedback mechanism where users can inform us about any issues that they are facing via a quick comment box. The second gives users even more control over their data. It allows users to opt-out of the anonymous telemetry that the extension reports, including the number of lookups that surface an unsafe credential, whether an alert leads to a password change, and the domain involved for improving site coverage. By design, the Password Checkup extension ensures that Google never learns your username or password, regardless of whether you enable telemetry, but we still want to provide this option if users would prefer not to share this information.


We're continuing to improve the Password Checkup extension and exploring ways to implement its technology into Google products. For help keeping all your online accounts safe from hijacking, you can install the Password Checkup extension here today.

Awarding Google Cloud Vulnerability Research



Today, we’re excited to announce a yearly Google Cloud Platform (GCP) VRP Prize to promote security research of GCP. A prize of $100,000.00 will be paid to the reporter of the best vulnerability affecting GCP reported through our Vulnerability Reward Program (g.co/vulnz) and having a public write-up (nominations will be received here).

We’ve received vulnerability reports for various application security flaws in GCP over the years, but we felt research of our Cloud platform has been under-represented in our Vulnerability Reward Program. So, with the GCP VRP Prize, we hope to encourage even more researchers to focus on GCP products and help us identify even more security vulnerabilities.

Note that we will continue to pay hundreds of thousands of dollars to our top bug hunters through our Vulnerability Research Grants Program even when no bugs are found, and to reward up to tens of thousands of dollars per bug to the most impactful findings. This prize is meant to create an additional incentive for more people to focus on public, open security research on GCP who would otherwise not participate in the reward program.

This competition draws on our previous contests, such as Pwnium and the Project Zero Prize, and rather than focusing bug hunters on collecting vulnerabilities for complex bug chains, we are attempting a slightly different twist and selecting a single winner out of all vulnerabilities we receive. That said, this approach comes with its own challenges, such as: defining the right incentives for bug hunters (both in terms of research as well as their communications with our team when reporting vulnerabilities); or ensuring there are no conflicting incentives, either when our own team is looking for similar vulnerabilities (since we aren't eligible for collecting the prize).

For the rest of the year, we will be seeking feedback from our top bug hunters and the security community to help define what vulnerabilities are the most significant, and we hope we can work together to find the best way to incentivize, recognize, and reward open security research. To further incentivize research in 2019, we will be issuing GCP VRP grants summing up to $100,000 to our top 2018 researchers.

Head over here for the full details on the contest. Note that if you have budget constraints for access to testing environments, you can use the free tier of GCP.

We look forward to our Vulnerability Rewards Programs resulting in even more GCP customer protection in the following years thanks to the hard work of the security research community. Follow us on @GoogleVRP.

Google Public DNS over HTTPS (DoH) supports RFC 8484 standard



Ever since we launched Google Public DNS in 2009, our priority has been the security of DNS resolution. In 2016, we launched a unique and innovative experimental service -- DNS over HTTPS, now known as DoH. Today we are announcing general availability for our standard DoH service. Now our users can resolve DNS using DoH at the dns.google domain with the same anycast addresses (like 8.8.8.8) as regular DNS service, with lower latency from our edge PoPs throughout the world.

General availability of DoH includes full RFC 8484 support at a new URL path, and continued support for the JSON API launched in 2016. The new endpoints are:

  • https://dns.google/dns-query (RFC 8484 – GET and POST)
  • https://dns.google/resolve (JSON API – GET)
We are deprecating internet-draft DoH support on the /experimental URL path and DoH service from dns.google.com, and will turn down support for them in a few months.

With Google Public DNS, we’re committed to providing fast, private, and secure DNS resolution through both DoH and DNS over TLS (DoT). We plan to support the JSON API until there is a comparable standard for webapp-friendly DoH.


What the new DoH service means for developers

To use our DoH service, developers should configure their applications to use the new DoH endpoints and properly handle HTTP 4xx error and 3xx redirection status codes.
  • Applications should use dns.google instead of dns.google.com. Applications can query dns.google at well-known Google Public DNS addresses, without needing an extra DNS lookup.
  • Developers using the older /experimental internet-draft DoH API need to switch to the new /dns-query URL path and confirm full RFC 8484 compliance. The older API accepts queries using features from early drafts of the DoH standard that are rejected by the new API.
  • Developers using the JSON API can use two new GET parameters that can be used for DNS/DoH proxies or DNSSEC-aware applications.
Redirection of /experimental and dns.google.com

The /experimental API will be turned down in 30 days and HTTP requests for it will get an HTTP redirect to an equivalent https://dns.google/dns-query URI. Developers should make sure DoH applications handle HTTP redirects by retrying at the URI specified in the Location header.

Turning down the dns.google.com domain will take place in three stages.
  1. The first stage (in 45 days) will update the dns.google.com domain name to return 8.8.8.8 and other Google Public DNS anycast addresses, but continue to return DNS responses to queries sent to former addresses of dns.google.com. This will provide a transparent transition for most clients.
  2. The second stage (in 90 days) will return HTTP redirects to dns.google for queries sent to former addresses of dns.google.com.
  3. The final stage (in 12 months) will send HTTP redirects to dns.google for any queries sent to the anycast addresses using the dns.google.com domain.
We will post timelines for redirections on the public‑dns‑announce forum and on the DoH migration page. You can find further technical details in our DoH documentation, and if you have a question or problem with our DoH service, you can create an issue on our tracker or ask on our discussion group. As always, please provide as much information as possible to help us investigate the problem!

Better protection against Man in the Middle phishing attacks



We’re constantly working to improve our phishing protections to keep your information secure. Last year, we announced that we would require JavaScript to be enabled in your browser when you sign in so that we can run a risk assessment whenever credentials are entered on a sign-in page and block the sign-in if we suspect an attack. This is yet another layer of protection on top of existing safeguards like Safe Browsing warnings, Gmail spam filters, and account sign-in challenges.

However, one form of phishing, known as “man in the middle” (MITM), is hard to detect when an embedded browser framework (e.g., Chromium Embedded Framework - CEF) or another automation platform is being used for authentication. MITM intercepts the communications between a user and Google in real-time to gather the user’s credentials (including the second factor in some cases) and sign in. Because we can’t differentiate between a legitimate sign in and a MITM attack on these platforms, we will be blocking sign-ins from embedded browser frameworks starting in June. This is similar to the restriction on webview sign-ins announced in April 2016.

What developers need to know

The solution for developers currently using CEF for authentication is the same: browser-based OAuth authentication. Aside from being secure, it also enables users to see the full URL of the page where they are entering their credentials, reinforcing good anti-phishing practices. If you are a developer with an app that requires access to Google Account data, switch to using browser-based OAuth authentication today.

Better protection against Man in the Middle phishing attacks



We’re constantly working to improve our phishing protections to keep your information secure. Last year, we announced that we would require JavaScript to be enabled in your browser when you sign in so that we can run a risk assessment whenever credentials are entered on a sign-in page and block the sign-in if we suspect an attack. This is yet another layer of protection on top of existing safeguards like Safe Browsing warnings, Gmail spam filters, and account sign-in challenges.

However, one form of phishing, known as “man in the middle” (MITM), is hard to detect when an embedded browser framework (e.g., Chromium Embedded Framework - CEF) or another automation platform is being used for authentication. MITM intercepts the communications between a user and Google in real-time to gather the user’s credentials (including the second factor in some cases) and sign in. Because we can’t differentiate between a legitimate sign in and a MITM attack on these platforms, we will be blocking sign-ins from embedded browser frameworks starting in June. This is similar to the restriction on webview sign-ins announced in April 2016.

What developers need to know

The solution for developers currently using CEF for authentication is the same: browser-based OAuth authentication. Aside from being secure, it also enables users to see the full URL of the page where they are entering their credentials, reinforcing good anti-phishing practices. If you are a developer with an app that requires access to Google Account data, switch to using browser-based OAuth authentication today.

Gmail making email more secure with MTA-STS standard



We’re excited to announce that Gmail will become the first major email provider to follow the new SMTP MTA Strict Transport Security (MTA-STS) RFC 8461 and SMTP TLS Reporting RFC 8460 internet standards. Those new email security standards are the result of three years of collaboration within IETF, with contributions from Google and other large email providers.

SMTP alone is vulnerable to man-in-the-middle attacks

Like all mail providers, Gmail uses Simple Mail Transfer Protocol (SMTP) to send and receive mail messages. SMTP alone only provides best-effort security with opportunistic encryption, and many SMTP servers do not prevent certain types of malicious attacks intercepting email traffic in transit.

SMTP is therefore vulnerable to man-in-the-middle attacks. Man-in-the-middle is an attack where communication between two servers is intercepted and possibly changed without detection. Real attacks and prevention were highlighted in our research published in November 2015. MTA-STS will help prevent these types of attacks.

MTA-STS uses encryption and authentication to reduce vulnerabilities

A MTA-STS policy for your domain means that you request external mail servers sending messages to your domain to verify the SMTP connection is authenticated with a valid public certificate and encrypted with TLS 1.2 or higher. This can be combined with TLS reporting, that means your domain can request daily reports from external mail servers with information about the success or failure of emails sent to your domain according to MTA-STS policy.

Gmail is starting MTA-STS adherence. We hope others will follow

Gmail the first major provider to follow the new standard, initially launching in Beta on April 10th 2019. This means Gmail will honor MTA-STS and TLS reporting policies configured when sending emails to domains that have defined these policies. We hope many other email providers will soon adopt these new standards that make email communications more secure.

Email domain administrators should set up DNS records and web server endpoint to configure MTA-STS and TLS reporting policies for incoming emails. Use our Help Center to find out how to set up an MTA-STS policy with your DNS server. G Suite admins can use the G Suite Updates blog to see what MTA-STS means for G Suite domains.

Open-sourcing Sandboxed API



Many software projects process data which is externally generated, and thus potentially untrusted. For example, this could be the conversion of user-provided picture files into different formats, or even executing user-generated software code.
When a software library parsing such data is sufficiently complex, it might fall victim to certain types of security vulnerabilities: memory corruption bugs or certain other types of problems related to the parsing logic (e.g. path traversal issues). Those vulnerabilities can have serious security implications.

In order to mitigate those problems, developers frequently employ software isolation methods, a process commonly referred to as sandboxing. By using sandboxing methods, developers make sure that only resources (files, networking connections and other operating system resources) which are deemed necessary are accessible to the code involved in parsing user-generated content. In the worst-case scenario, when potential attackers gain remote code execution rights within the scope of a software project, a sandboxing technique can contain them, protecting the rest of the software infrastructure.

Sandboxing techniques must be highly resistant to attacks and sufficiently protect the rest of the operating system, yet must be sufficiently easy-to-use for software developers. Many popular software containment tools might not sufficiently isolate the rest of the OS, and those which do, might require time-consuming redefinition of security boundaries for each and every project that should be sandboxed.

Sandbox once, use anywhere

To help with this task, we are open-sourcing our battle-tested project called Sandboxed API. Sandboxed API makes it possible to create security policies for individual software libraries. This concept allows to create reusable and secure implementations of functionality residing within popular software libraries, yet is granular enough to protect the rest of used software infrastructure.

As Sandboxed API serves the purpose of accessing individual software functions inside a sandboxed library, we are also making publicly available our core sandboxing project, Sandbox2. This is now part of Sandboxed API and provides the underlying sandboxing primitives. It can be also used standalone to isolate arbitrary Linux processes, but is considered a lower-level API.

Overview

Sandboxed API is currently implemented for software libraries written in the C programming language (or providing C bindings), though we might add support for more programming runtimes in the future.

From a high-level perspective, Sandboxed API separates the library to be sandboxed and its callers into two separate OS processes: the host binary and the sandboxee. Actual library calls are then marshalled by an API object on the host side and send via interprocess communication to the sandboxee where an RPC stub unmarshals and forwards calls to the original library.

Both the API object (SAPI object) and the RPC stub are provided by the project, with the former being auto-generated by an interface generator. Users just need to provide a sandbox policy, a set of system calls that the underlying library is allowed to make, as well as the resources it is allowed to access and use. Once ready, a library based on sandboxed API can easily be reused in other projects.

The resulting API of the SAPI object is similar to the one of the original library. For example, when using zlib, the popular compression library, a code snippet like this compresses a chunk of data (error handling omitted for brevity):


void Compress(const std::string& chunk, std::string* out) {
 z_stream zst{};
 constexpr char kZlibVersion[] = "1.2.11";
 CHECK(deflateInit_(&zst, /*level=*/4, kZlibVersion, sizeof(zst)) == Z_OK);

 zst.avail_in = chunk.size();
 zst.next_in = reinterpret_cast<uint8_t*>(&chunk[0]);
 zst.avail_out = out->size();
 zst.next_out = reinterpret_cast<uint8_t*>(&(*out)[0]);
 CHECK(deflate(&zst, Z_FINISH) != Z_STREAM_ERROR);
 out->resize(zst.avail_out);

 deflateEnd(&zst);
}


Using Sandboxed API, this becomes:
void CompressSapi(const std::string& chunk, std::string* out) {
 sapi::Sandbox sandbox(sapi::zlib::zlib_sapi_embed_create());
 CHECK(sandbox.Init().ok());
 sapi::zlib::ZlibApi api(&sandbox);

 sapi::v::Array<uint8_t> s_chunk(&chunk[0], chunk.size());
 sapi::v::Array<uint8_t> s_out(&(*out)[0], out->size());
 CHECK(sandbox.Allocate(&s_chunk).ok() && sandbox.Allocate(&s_out).ok());
 sapi::v::Struct<sapi::zlib::z_stream> s_zst;
 
 constexpr char kZlibVersion[] = "1.2.11";
 sapi::v::Array<char> s_version(kZlibVersion, ABSL_ARRAYSIZE(kZlibVersion));
 CHECK(api.deflateInit_(s_zst.PtrBoth(), /*level=*/4, s_version.PtrBefore(),
                         sizeof(sapi::zlib::z_stream).ValueOrDie() == Z_OK));

 CHECK(sandbox.TransferToSandboxee(&s_chunk).ok());
 s_zst.mutable_data()->avail_in = chunk.size();
 s_zst.mutable_data()->next_in = reinterpet_cast<uint8_t*>(s_chunk.GetRemote());
 s_zst.mutable_data()->avail_out = out->size();
 s_zst.mutable_data()->next_out = reinterpret_cast<uint8_t*>(s_out.GetRemote());
 CHECK(api.deflate(s_zst.PtrBoth(), Z_FINISH).ValueOrDie() != Z_STREAM_ERROR);
 CHECK(sandbox.TransferFromSandboxee(&s_out).ok());
 out->resize(s_zst.data().avail_out);

 CHECK(api.deflateEnd(s_zst.PtrBoth()).ok());
}
As you can see, when using Sandboxed API there is extra code for setting up the sandbox itself and for transferring memory to and from the sandboxee, but other than that, the code flow stays the same.

Try for yourself

It only takes a few moments to get up and running with Sandboxed API. If Bazel is installed:
sudo apt-get install python-typing python-clang-7 libclang-7-dev linux-libc-dev
git clone github.com/google/sandboxed-api && cd sandboxed-api
bazel test //sandboxed_api/examples/stringop:main_stringop
This will download the necessary dependencies and run the project through its paces. More detailed instructions can be found in our Getting Started guide and be sure to check out the examples for Sandboxed API.

Where do we go from here?

Sandboxed API and Sandbox2 are used by many teams at Google. While the project is mature, we do have plans for the future beyond just maintaining it:

  • Support more operating systems - So far, only Linux is supported. We will look into bringing Sandboxed API to the Unix-like systems like the BSDs (FreeBSD, OpenBSD) and macOS. A Windows port is a bigger undertaking and will require some more groundwork to be done.
  • New sandboxing technologies - With things like hardware-virtualization becoming almost ubiquitous, confining code into VMs for sandboxing opens up new possibilities.
  • Build system - Right now, we are using Bazel to build everything, including dependencies. We acknowledge that this is not how everyone will want to use it, so CMake support is high on our priority list.
  • Spread the word - Use Sandboxed API to secure open source projects. If you want to get involved, this work is also eligible for the Patch Reward Program.
Get involved

We are constantly looking at improving Sandboxed API and Sandbox2 as well as adding more features: supporting more programming runtimes, different operating systems or alternative containment technologies.

Check out the Sandboxed API GitHub repository. We will be happy to consider your contributions and look forward to any suggestions to help improve and extend this code.