Security in the Jupyter Server#
Since access to the Jupyter Server means access to running arbitrary code,it is important to restrict access to the server.For this reason, Jupyter Server uses a token-based authentication that ison by default.
Note
If you enable a password for your server,token authentication is not enabled by default.
When token authentication is enabled, the server uses a token to authenticate requests.This token can be provided to login to the server in three ways:
in the
Authorization
header, e.g.:Authorization:tokenabcdef...
In a URL parameter, e.g.:
https://my-server/tree/?token=abcdef...
In the password field of the login form that will be shown to you if you are not logged in.
When you start a Jupyter server with token authentication enabled (default),a token is generated to use for authentication.This token is logged to the terminal, so that you can copy/paste the URL into your browser:
[I 11:59:16.597 ServerApp] The Jupyter Server is running at:[I 11:59:16.597 ServerApp]http://localhost:8888/?token=c8de56fa4deed24899803e93c227592aef6538f93025fe01[I 11:59:16.597 ServerApp]http://127.0.0.1:8888/?token=c8de56fa4deed24899803e93c227592aef6538f93025fe01[I 11:59:16.597 ServerApp] To access the server, open this file in a browser: file:///Users/username/Library/Jupyter/runtime/jpserver-46320-open.htmlOr copy and paste one of these URLs: http://localhost:8888/?token=c8de56fa4deed24899803e93c227592aef6538f93025fe01 http://127.0.0.1:8888/?token=c8de56fa4deed24899803e93c227592aef6538f93025fe01
Copy either of the HTTP URLs and paste it into your browser to see the server running with amessage - “A Jupyter Server is running.” If you are using the file link,opening it in your browser should automatically redirect you to the Jupyter server launch page,including the authentication token. In case it doesn’t redirect automatically, you’llfind an HTTP link on the page; clicking this link will take you to the Jupyter server landing page.
At any later time, you can see the tokens and URLs for all of your running servers withjupyter server list:
$ jupyter server listCurrently running servers:http://localhost:8888/?token=abc... :: /home/you/notebookshttps://0.0.0.0:9999/?token=123... :: /tmp/publichttp://localhost:8889/ :: /tmp/has-password
For servers with token-authentication enabled, the URL in the above listing will include the token,so you can copy and paste that URL into your browser to login.If a server has no token (e.g. it has a password or has authentication disabled),the URL will not include the token argument.Once you have visited this URL,a cookie will be set in your browser and you won’t need to use the token again,unless you switch browsers, clear your cookies, or start a Jupyter server on a new port.
Alternatives to token authentication#
If a generated token doesn’t work well for you,you can set a password for your server.jupyter server password will prompt you for a password,and store the hashed password in yourjupyter_server_config.json
.
It is possible disable authentication altogether by setting the token and password to empty strings,but this isNOT RECOMMENDED, unless authentication or access restrictions are handled at a different layer in your web application:
c.ServerApp.token=""c.ServerApp.password=""
Authentication and Authorization#
Added in version 2.0.
There are two steps to deciding whether to allow a given request to be happen.
The first step is “Authentication” (identifying who is making the request).This is handled by thejupyter_server.auth.IdentityProvider
.
Whether a given user is allowed to take a specific action is called “Authorization”,and is handled separately, by anAuthorizer
.
These two classes may work together,as the information returned by the IdentityProvider is given to the Authorizer when it makes its decisions.
Authentication always takes precedence because if no user is authenticated,no authorization checks need to be made,as all requests requiringauthorization must first completeauthentication.
Identity Providers#
Thejupyter_server.auth.IdentityProvider
class is responsible for the “authentication” step,identifying the user making the request,and constructing information about them.
It principally implements two methods.
- classjupyter_server.auth.IdentityProvider(**kwargs)#
Interface for providing identity management and authentication.
Two principle methods:
get_user()
returns aUser
objectfor successful authentication, or None for no-identity-found.identity_model()
turns aUser
into a JSONable dict.The default is to usedataclasses.asdict()
,and usually shouldn’t need override.
Additional methods can customize authentication.
Added in version 2.0.
- get_user(handler)#
Get the authenticated user for a request
Must return a
jupyter_server.auth.User
,though it may be a subclass.Return None if the request is not authenticated.
_may_ be a coroutine
- Return type:
User | None | t.Awaitable[User | None]
The first isjupyter_server.auth.IdentityProvider.get_user()
.This method is given a RequestHandler, and is responsible for deciding whether there is an authenticated user making the request.If the request is authenticated, it should return ajupyter_server.auth.User
object representing the authenticated user.It should return None if the request is not authenticated.
The default implementation accepts token or password authentication.
This User object will be available asself.current_user
in any request handler.Request methods decorated with tornado’s@web.authenticated
decoratorwill only be allowed if this method returns something.
The User object will be a Pythondataclasses.dataclass
-jupyter_server.auth.User
:
- classjupyter_server.auth.User(username,name='',display_name='',initials=None,avatar_url=None,color=None)#
Object representing a User
This or a subclass should be returned from IdentityProvider.get_user
A custom IdentityProvidermay return a custom subclass.
The next method an identity provider has isidentity_model()
.identity_model(user)
is responsible for transforming the user object returned from.get_user()
into a standard identity model dictionary,for use in the/api/me
endpoint.
If your user object is a simple username string or a dict with ausername
field,you may not need to implement this method, as the default implementation will suffice.
Any required fields missing from the dict returned by this method will be filled-out with defaults.Onlyusername
is strictly required, if that is all the information the identity provider has available.
Missing will be derived according to:
if
name
is missing, useusername
if
display_name
is missing, usename
Other required fields will be filled withNone
.
Identity Model#
The identity model is the model accessed at/api/me
, and describes the currently authenticated user.
It has the following fields:
- username
(string)Unique string identifying the user.Must be non-empty.
- name
(string)For-humans name of the user.May be the same as
username
in systems where only usernames are available.- display_name
(string)Alternate rendering of name for display, such as a nickname.Often the same as
name
.- initials
(string or null)Short string of initials.Initials should not be derived automatically due to localization issues.May be
null
if unavailable.- avatar_url
(string or null)URL of an avatar image to be used for the user.May be
null
if unavailable.- color
(string or null)A CSS color string to use as a preferred color,such as for collaboration cursors.May be
null
if unavailable.
The default implementation of the identity provider is stateless, meaning it doesn’t store user informationon the server side. Instead, it utilizes session cookies to generate and store random user information on theclient side.
When a user logs in or authenticates, the server generates a session cookie that is stored on the client side.This session cookie is used to keep track of the identity model between requests. If the client does notsupport session cookies or fails to send the cookie in subsequent requests, the server will treat each requestas coming from a new anonymous user and generate a new set of random user information for each request.
To ensure proper functionality of the identity model and to maintain user context between requests, it’simportant for clients to support session cookies and send it in subsequent requests. Failure to do so mayresult in the server generating a new anonymous user for each request, leading to loss of user context.
Authorization#
Authorization is the second step in allowing an action,after a user has beenauthenticated by the IdentityProvider.
Authorization in Jupyter Server serves to provide finer grained control of access to itsAPI resources. With authentication, requests are accepted if the current user is known bythe server. Thus it can restrain access to specific users, but there is no way to give allowedusers more or less permissions. Jupyter Server provides a thin and extensible authorization layerwhich checks if the current user is authorized to make a specific request.
- classjupyter_server.auth.Authorizer(**kwargs)#
Base class for authorizing access to resourcesin the Jupyter Server.
All authorizers used in Jupyter Servershould inherit from this base class and, at the very minimum,implement an
is_authorized
method with thesame signature as in this base class.The
is_authorized
method is called by the@authorized
decoratorin JupyterHandler. If it returns True, the incoming requestto the server is accepted; if it returns False, the serverreturns a 403 (Forbidden) error code.The authorization check will only be applied to requeststhat have already been authenticated.
Added in version 2.0.
- is_authorized(handler,user,action,resource)#
A method to determine if
user
is authorized to performaction
(read, write, or execute) on theresource
type.- Parameters:
user (jupyter_server.auth.User) – An object representing the authenticated user,as returned by
jupyter_server.auth.IdentityProvider.get_user()
.action (str) – the category of action for the current request: read, write, or execute.
resource (str) – the type of resource (i.e. contents, kernels, files, etc.) the user is requesting.
- Returns:
True if user authorized to make request; False, otherwise
- Return type:
This is done by calling ais_authorized(handler,user,action,resource)
method before eachrequest handler. Each request is labeled as either a “read”, “write”, or “execute”action
:
“read” wraps all
GET
andHEAD
requests.In general, read permissions grants access to read but not modify anything about the given resource.“write” wraps all
POST
,PUT
,PATCH
, andDELETE
requests.In general, write permissions grants access to modify the given resource.“execute” wraps all requests to ZMQ/Websocket channels (terminals and kernels).Execute is a special permission that usually corresponds to arbitrary execution,such as via a kernel or terminal.These permissions should generally be considered sufficient to perform actions equivalentto ~all other permissions via other means.
Theresource
being accessed refers to the resource name in the Jupyter Server’s API endpoints.In most cases, this is the field after/api/
.For instance, values forresource
in the endpoints provided by the base Jupyter Server package,and the corresponding permissions:
resource | read | write | execute | endpoints |
---|---|---|---|---|
resource name | what can you do with read permissions? | what can you do with write permissions? | what can you do with execute permissions, if anything? |
|
api | read server status (last activity, number of kernels, etc.), OpenAPI specification |
| ||
csp | report content-security-policy violations |
| ||
config | read frontend configuration, such as for notebook extensions | modify frontend configuration |
| |
contents | read files | modify files (create, modify, delete) |
| |
kernels | list kernels, get status of kernels | start, stop, and restart kernels | Connect to kernel websockets, send/recv kernel messages.This generally means arbitrary code execution,and should usually be considered equivalent to having all other permissions. |
|
kernelspecs | read, list information about available kernels |
| ||
nbconvert | render notebooks to other formats via nbconvert.Note: depending on server-side configuration,this *could* involve execution. |
| ||
server | Shutdown the server |
| ||
sessions | list current sessions (association of documents to kernels) | create, modify, and delete existing sessions,which includes starting, stopping, and deleting kernels. |
| |
terminals | list running terminals and their last activity | start new terminals, stop running terminals | Connect to terminal websockets, execute code in a shell.This generally means arbitrary code execution,and should usually be considered equivalent to having all other permissions. |
|
Extensions may define their own resources.Extension resources should start withextension_name:
to avoid namespace conflicts.
Ifis_authorized(...)
returnsTrue
, the request is made; otherwise, aHTTPError(403)
(403 means “Forbidden”) error is raised, and the request is blocked.
By default, authorization is turned off—i.e.is_authorized()
always returnsTrue
andall authenticated users are allowed to make all types of requests. To turn-on authorization, passa class that inherits fromAuthorizer
to theServerApp.authorizer_class
parameter, implementing ais_authorized()
method with your desired authorization logic, asfollows:
fromjupyter_server.authimportAuthorizerclassMyAuthorizationManager(Authorizer):"""Class for authorizing access to resources in the Jupyter Server. All authorizers used in Jupyter Server should inherit from AuthorizationManager and, at the very minimum, override and implement an `is_authorized` method with the following signature. The `is_authorized` method is called by the `@authorized` decorator in JupyterHandler. If it returns True, the incoming request to the server is accepted; if it returns False, the server returns a 403 (Forbidden) error code. """defis_authorized(self,handler:JupyterHandler,user:Any,action:str,resource:str)->bool:"""A method to determine if `user` is authorized to perform `action` (read, write, or execute) on the `resource` type. Parameters ------------ user : usually a dict or string A truthy model representing the authenticated user. A username string by default, but usually a dict when integrating with an auth provider. action : str the category of action for the current request: read, write, or execute. resource : str the type of resource (i.e. contents, kernels, files, etc.) the user is requesting. Returns True if user authorized to make request; otherwise, returns False. """returnTrue# implement your authorization logic here
Theis_authorized()
method will automatically be called whenever a handler is decorated with@authorized
(fromjupyter_server.auth
), similarly to the@authenticated
decorator for authentication (fromtornado.web
).
Security in notebook documents#
As Jupyter Server become more popular for sharing and collaboration,the potential for malicious people to attempt to exploit the notebookfor their nefarious purposes increases. IPython 2.0 introduced asecurity model to prevent execution of untrusted code without explicituser input.
The problem#
The whole point of Jupyter is arbitrary code execution. We have nodesire to limit what can be done with a notebook, which would negativelyimpact its utility.
Unlike other programs, a Jupyter notebook document includes output.Unlike other documents, that output exists in a context that can executecode (via Javascript).
The security problem we need to solve is that no code should executejust because a user hasopened a notebook thatthey did notwrite. Like any other program, once a user decides to execute code ina notebook, it is considered trusted, and should be allowed to doanything.
Our security model#
Untrusted HTML is always sanitized
Untrusted Javascript is never executed
HTML and Javascript in Markdown cells are never trusted
Outputs generated by the user are trusted
Any other HTML or Javascript (in Markdown cells, output generated byothers) is never trusted
The central question of trust is “Did the current user do this?”
The details of trust#
When a notebook is executed and saved, a signature is computed from adigest of the notebook’s contents plus a secret key. This is stored in adatabase, writable only by the current user. By default, this is located at:
~/.local/share/jupyter/nbsignatures.db# Linux~/Library/Jupyter/nbsignatures.db# OS X%APPDATA%/jupyter/nbsignatures.db# Windows
Each signature represents a series of outputs which were produced by code thecurrent user executed, and are therefore trusted.
When you open a notebook, the server computes its signature, and checks if it’sin the database. If a match is found, HTML and Javascriptoutput in the notebook will be trusted at load, otherwise it will beuntrusted.
Any output generated during an interactive session is trusted.
Updating trust#
A notebook’s trust is updated when the notebook is saved. If there areany untrusted outputs still in the notebook, the notebook will not betrusted, and no signature will be stored. If all untrusted outputs havebeen removed (either viaClearOutput
or re-execution), then thenotebook will become trusted.
While trust is updated per output, this is only for the duration of asingle session. A newly loaded notebook file is either trusted or not in itsentirety.
Explicit trust#
Sometimes re-executing a notebook to generate trusted output is not anoption, either because dependencies are unavailable, or it would take along time. Users can explicitly trust a notebook in two ways:
At the command-line, with:
jupytertrust/path/to/notebook.ipynb
After loading the untrusted notebook, with
File/TrustNotebook
These two methods simply load the notebook, compute a new signature, and addthat signature to the user’s database.
Reporting security issues#
If you find a security vulnerability in Jupyter, either a failure of thecode to properly implement the model described here, or a failure of themodel itself, please report it tosecurity@ipython.org.
If you prefer to encrypt your security reports,you can usethisPGPpublickey
.
Affected use cases#
Some use cases that work in Jupyter 1.0 became less convenient in2.0 as a result of the security changes. We do our best to minimizethese annoyances, but security is always at odds with convenience.
Javascript and CSS in Markdown cells#
While never officially supported, it had become common practice to puthidden Javascript or CSS styling in Markdown cells, so that they wouldnot be visible on the page. Since Markdown cells are now sanitized (byGoogle Caja), all Javascript(including click event handlers, etc.) and CSS will be stripped.
We plan to provide a mechanism for notebook themes, but in the meantimestyling the notebook can only be done via eithercustom.css
or CSSin HTML output. The latter only have an effect if the notebook istrusted, because otherwise the output will be sanitized just likeMarkdown.
Collaboration#
When collaborating on a notebook, people probably want to see theoutputs produced by their colleagues’ most recent executions. Since eachcollaborator’s key will differ, this will result in each share startingin an untrusted state. There are three basic approaches to this:
re-run notebooks when you get them (not always viable)
explicitly trust notebooks via
jupytertrust
or the notebook menu(annoying, but easy)share a notebook signatures database, and use configuration dedicated to thecollaboration while working on the project.
To share a signatures database among users, you can configure:
c.NotebookNotary.data_dir="/path/to/signature_dir"
to specify a non-default path to the SQLite database (of notebook hashes,essentially).