Source: https://w3c.github.io/webappsec-secure-contexts/
Timestamp: 2019-04-20 20:53:57+00:00

Document:
Copyright © 2019 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and document use rules apply.
This specification defines "secure contexts", thereby allowing user agent implementers and specification authors to enable certain features only when certain minimum standards of authentication and confidentiality are met.
3.1 Is an environment settings object contextually secure?
3.2 Is origin potentially trustworthy?
3.3 Is url potentially trustworthy?
As the web platform is extended to enable more useful and powerful applications, it becomes increasingly important to ensure that the features which enable those applications are enabled only in contexts which meet a minimum security level. As an extension of the TAG’s recommendations in [SECURING-WEB], this document describes threat models for feature abuse on the web (see §4.1 Threat Models) and outlines normative requirements which should be incorporated into documents specifying new features (see §7 Implementation Considerations).
The most obvious of the requirements discussed here is that application code with access to sensitive or private data be delivered confidentially over authenticated channels that guarantee data integrity. Delivering code securely cannot ensure that an application will always meet a user’s security and privacy requirements, but it is a necessary precondition.
Less obviously, application code delivered over an authenticated and confidential channel isn’t enough in and of itself to limit the use of powerful features by non-secure contexts. As §4.2 Ancestral Risk explains, cooperative frames can be abused to bypass otherwise solid restrictions on a feature. The algorithms defined below ensure that these bypasses are difficult and user-visible.
http://example.com/ opened in a top-level browsing context is not a secure context, as it was not delivered over an authenticated and encrypted channel.
https://example.com/ opened in a top-level browsing context is a secure context, as it was delivered over an authenticated and encrypted channel.
If https://example.com/ opened in a top-level browsing context opens https://sub.example.com/ in a frame, then both are secure contexts, as both were delivered over authenticated and encrypted channels.
If https://example.com/ was somehow able to frame http://non-secure.example.com/ (perhaps the user has overridden mixed content checking?), the top-level frame would remain secure, but the framed content is not a secure context.
If, on the other hand, https://example.com/ is framed inside of http://non-secure.example.com/, then it is not a secure context, as its ancestor is not delivered over an authenticated and encrypted channel.
If https://example.com/ in a top-level browsing context runs https://example.com/worker.js, then both the document and the worker are secure contexts.
If http://non-secure.example.com/ in a top-level browsing context frames https://example.com/, which runs https://example.com/worker.js, then neither the framed document nor the worker are secure contexts.
Multiple contexts may attach to a Shared Worker. If a secure context creates a Shared Worker, then it is a secure context, and may only be attached to by other secure contexts. If a non-secure context creates a Shared Worker, then it is not a secure context, and may only be attached to by other non-secure contexts.
If https://example.com/ in a top-level browsing context runs https://example.com/worker.js as a Shared Worker, then both the document and the worker are considered secure contexts.
https://example.com/ nested in http://non-secure.example.com/ may not connect to the secure worker, as it is not a secure context.
Likewise, if https://example.com/ nested in http://non-secure.example.com/ runs https://example.com/worker.js as a Shared Worker, then both the document and the worker are considered non-secure.
Service Workers are always secure contexts. Only secure contexts may register them, and they may only have clients which are secure contexts.
If https://example.com/ in a top-level browsing context registers https://example.com/service.js, then both the document and the Service Worker are considered secure contexts.
Environment settings objects are considered to be secure contexts if they are contextually secure as defined in §3.1 Is an environment settings object contextually secure?, and non-secure contexts otherwise.
Likewise, a global object (Window, WorkerGlobalScope, etc.) is considered to be a secure context if its relevant settings object is contextually secure as defined in §3.1 Is an environment settings object contextually secure?, and a non-secure context otherwise.
// This call will succeed in all contexts.
// This operation will not be exposed to a non-secure context.
// The same applies here: the operation will not be exposed to a non-secure context.
// This interface will not be exposed to non-secure contexts.
Specification authors are encouraged to use this attribute when defining new features.
This flag asserts that content in a browsing context will be treated as a non-secure context, even if it would otherwise be considered secure.
The sandboxed secure browsing context flag, unless tokens contains the allow-secure-context keyword.
The SharedWorker constructor will throw a SecurityError exception if a secure context attempts to attach to an Worker which is not a secure context, and if a non-secure context attempts to attach to a Worker which is a secure context.
The isSecureContext attribute’s getter returns true if this global object's relevant settings object is contextually secure, and false otherwise.
3.1. Is an environment settings object contextually secure?
Let global be settings’s global object.
Assert: Workers must be same-origin with the context that created them, so document’s relevant settings object's origin and HTTPS state is the same as global’s relevant settings object's origin and HTTPS state.
If document’s relevant settings object is not contextually secure, return "Not Secure".
Note: Given the assertion above, if we’ve reached this step, the worker must have been created from a secure context, and therefore must itself be a secure context.
Assert: global is a Window.
Let document be settings’s responsible document.
document’s active sandboxing flag set contains the sandboxed secure browsing context flag.
Note: This check is "at risk". See §2.2.1 Sandboxing for details.
document has a parent browsing context (context), and context’s active document's relevant settings object is not contextually secure.
settings’s HTTPS state is "deprecated".
document’s active sandboxing flag set includes the sandboxed origin browsing context flag, and §3.3 Is url potentially trustworthy? returns "Not Trustworthy" when executed upon settings’s creation URL.
Note: We check the creation URL here because sandboxed content that is treated as being in an opaque origin (e.g. <iframe sandbox="allow-secure-context" src="http://127.0.0.1/">) would otherwise be treated as non-trustworthy by §3.2 Is origin potentially trustworthy?. Since sandboxing is a strict reduction in the content’s capabilities, and therefore in the risk it poses, we look at the origin of its URL to determine whether we would have considered it trustworthy had it not been sandboxed.
document’s active sandboxing flag set does not include the sandboxed origin browsing context flag, and §3.2 Is origin potentially trustworthy? returns "Not Trustworthy" when executed upon settings’s origin.
3.2. Is origin potentially trustworthy?
A potentially trustworthy origin is one which a user agent can generally trust as delivering data securely.
This algorithms considers certain hosts, scheme, and origins as potentially trustworthy, even though they might not be authenticated and encrypted in the traditional sense. In particular, the user agent SHOULD treat file URLs as potentially trustworthy. In principle the user agent could treat local files as untrustworthy, but, given the information that is available to the user agent at runtime, the resources appear to have been transported securely from disk to the user agent. Additionally, treating such resources as potentially trustworthy is convenient for developers building an application before deploying it to the public.
This developer-friendlyness is not without risk, however. User agents which prioritize security over such niceties MAY choose to more strictly assign trust in a way which excludes file.
On the other hand, the user agent MAY choose to extend this trust to other, vendor-specific URL schemes like app: or chrome-extension: which it can determine a priori to be trusted (see §7.1 Packaged Applications for detail).
Given an origin (origin), the following algorithm returns "Potentially Trustworthy" or "Not Trustworthy" as appropriate.
If origin is an opaque origin, return "Not Trustworthy".
Assert: origin is a tuple origin.
If origin’s scheme is either "https" or "wss", return "Potentially Trustworthy".
Note: This is meant to be analog to the a priori authenticated URL concept in [MIX].
If origin’s host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy".
If origin’s host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy".
Note: See §5.2 localhost for details on the requirements here.
If origin’s scheme component is file, return "Potentially Trustworthy".
If origin’s scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy".
Note: See §7.1 Packaged Applications for detail here.
If origin has been configured as a trustworthy origin, return "Potentially Trustworthy".
Note: See §7.2 Development Environments for detail here.
Note: Neither origin’s domain nor port has any effect on whether or not it is considered to be a secure context.
3.3. Is url potentially trustworthy?
If url’s scheme is "data", return "Not Trustworthy".
Note: This aligns the definition of a secure context with the de facto "data: URL as opaque origin" behavior that a majority of today’s browsers have agreed upon, rather than the de jure "data: URL inherits origin" behavior defined in HTML.
If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy".
Return the result of executing §3.2 Is origin potentially trustworthy? on url’s origin.
Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were created. Therefore, blobs created in a trustworthy origin will themselves be potentially trustworthy.
Granting permissions to unauthenticated origins is, in the presence of a network attacker, equivalent to granting the permissions to any origin. The state of the Internet is such that we must indeed assume that a network attacker is present. Generally, network attackers fall into 2 classes: passive and active.
A "Passive Network Attacker" is a party who is able to observe traffic flows but who lacks the ability or chooses not to modify traffic at the layers which this specification is concerned with.
Surveillance of networks in this manner "subverts the intent of communicating parties without the agreement of these parties" and one "cannot defend against the most nefarious actors while allowing monitoring by other actors no matter how benevolent some might consider them to be." [RFC7258] Therefore, the algorithms defined in this document require mechanisms that provide for the privacy of data at the application layer, not simply integrity.
An "Active Network Attacker" has all the capabilities of a "Passive Network Attacker" and is additionally able to modify, block or replay any data transiting the network. These capabilities are available to potential adversaries at many levels of capability, from compromised devices offering or simply participating in public wireless networks, to Internet Service Providers indirectly introducing security and privacy vulnerabilities while manipulating traffic for financial gain ([VERIZON] and [COMCAST] are recent examples), to parties with direct intent to compromise security or privacy who are able to target individual users, organizations or even entire populations.
The Is an environment settings object contextually secure? algorithm walks through all the ancestors of a particular context in order to determine whether or not the context itself is secure. Why wouldn’t we consider a securely-delivered document in an iframe to be secure, in and of itself?
The short answer is that this model would enable abuse. Chrome’s implementation of [WEBCRYPTOAPI] was an early experiment in locking APIs to secure contexts, and it did not walk through a context’s ancestors. The assumption was that locking the API to a resouce which was itself delivered securely would be enough to ensure secure usage. The result, however, was that entities like Netflix built iframe- and postMessage()-based shims that exposed the API to non-secure contexts. The restriction was little more than a speed-bump, slowing down non-secure access to the API, but completely ineffective in preventing such access.
While the algorithms in this document do not perfectly isolate non-secure contexts from secure contexts (as discussed in §5.1 Incomplete Isolation), the ancestor checks provide a fairly robust protection for the guarantees of authentication, confidentiality, and integrity that such contexts ought to provide.
The ability to read and modify sensitive data (personally-identifying information, credentials, payment instruments, and so on). [CREDENTIAL-MANAGEMENT-1] is an example of an API that handles sensitive data.
The ability to read and modify input from sensors on a user’s device (camera, microphone, and GPS being particularly noteworthy, but certainly including less obviously dangerous sensors like the accelerometer). [GEOLOCATION-API] and [MEDIACAPTURE-STREAMS] are historical examples of features that use sensor input.
The ability to access information about other devices to which a user has access. [DISCOVERY-API] and [WEB-BLUETOOTH] are good examples.
The ability to track users using temporary or persistent identifiers, including identifiers which reset themselves after some period of time (e.g. window.sessionStorage), identifiers the user can manually reset (e.g. [ENCRYPTED-MEDIA], Cookies [RFC6265], and [IndexedDB]), as well as identifying hardware features the user can’t easily reset.
The ability to introduce some state for an origin which persists across browsing sessions. [SERVICE-WORKERS] is a great example.
The ability to manipulate a user agent’s native UI in some way which removes, obscures, or manipulates details relevant to a user’s understanding of their context. [FULLSCREEN] is a good example.
The ability to introduce some functionality for which user permission will be required.
This list is non-exhaustive, but should give you a feel for the types of risks we should consider when writing or implementing specifications.
Note: While restricting a feature itself to secure contexts is critical, we ought not forget that facilities that carry such information (such as new network access mechanisms, or other generic functions with access to network data) are equally sensitive.
The secure context definition in this document does not completely isolate a "secure" view on an origin from a "non-secure" view on the same origin. Exfiltration will still be possible via increasingly esoteric mechanisms such as the contents of localStorage/sessionStorage, storage events, BroadcastChannel, and others.
Section 6.3 of [RFC6761] lays out the resolution of localhost. and names falling within .localhost. as special, and suggests that local resolvers SHOULD/MAY treat them specially. For better or worse, resolvers often ignore these suggestions, and will send localhost to the network for resolution in a number of circumstances.
Given that uncertainty, user agents MAY treat localhost names as having potentially trustworthy origins if and only if they also adhere to the localhost name resolution rules spelled out in [let-localhost-be-localhost] (which boil down to ensuring that localhost never resolves to a non-loopback address).
The secure context definition in this document does not in itself have any privacy impact. It does, however, enable other features which do have interesting privacy implications to lock themselves into contexts which ensures that specific guarantees can be made regarding integrity, authenticity, and confidentiality.
From a privacy perspective, specification authors are encouraged to consider requiring secure contexts for the features they define.
A user agent that support packaged applications MAY consider as "secure" specific URL schemes whose contents are authenticated by the user agent. For example, FirefoxOS application resources are referred to by a URL whose scheme component is app:. Likewise, Chrome’s extensions and apps live on chrome-extension: schemes. These could reasonably be considered trusted origins.
In order to support developers who run staging servers on non-loopback hosts, the user agent MAY allow users to configure specific sets of origins as trustworthy, even though §3.2 Is origin potentially trustworthy? would normally return "Not Trustworthy".
[insert something appropriate here: perhaps a Promise could be rejected with a SecurityError, an error callback could be called, a permission request denied, etc.].
Authors could alternatively ensure that sensitive APIs are only exposed to secure contexts by guarding them with the [SecureContext] attribute.
The list above clearly includes some existing functionality that is currently available to the web over non-secure channels. We recommend that such legacy functionality be modified to begin requiring a secure context as quickly as is reasonably possible [W3C-PROCESS].
If such a feature is not widely implemented, we recommend that the specification be immediately modified to include a restriction to secure contexts.
If such a feature is widely implemented, but not yet in wide use, we recommend that it be quickly restricted to secure contexts by adding a check as described in §7.3 Restricting New Features to existing implementations, and modifying the specification accordingly.
If such a feature is in wide use, we recommend that the existing functionality be deprecated; the specification should be modified to note that it does not conform to the restrictions outlined in this document, and a plan should be developed to both offer a conformant version of the feature and to migrate existing users into that new version.
Modify the specification to include checks against secure context before executing the algorithms for getCurrentPosition() and watchPosition().
If the current settings object is not a secure context, then the algorithm should be aborted, and the errorCallback invoked with a code of PERMISSION_DENIED.
The user agent should announce clear intentions to disable the API for non-secure contexts on a specific date, and warn developers accordingly (via console messages, for example).
This document is largely based on the Chrome Security team’s work on [POWERFUL-NEW-FEATURES]. Chris Palmer, Ryan Sleevi, and David Dorwin have been particularly engaged. Anne van Kesteren, Jonathan Watt, Boris Zbarsky, and Henri Sivonen have also provided very helpful feedback.

References: §4
 §7
 §4
 §3
 §3
 §2
 §3
 §3
 §3
 §7
 §5
 §7
 §7
 §3
 §5
 §3
 §7