1.. _working_remotely:
2
3Running a public Jupyter Server
4===============================
5
6
7The Jupyter Server uses a :ref:`two-process kernel
8architecture <ipython:ipythonzmq>` based on ZeroMQ_, as well as Tornado_ for
9serving HTTP requests.
10
11.. note::
12   By default, Jupyter Server runs locally at 127.0.0.1:8888
13   and is accessible only from `localhost`. You may access the
14   server from the browser using `http://127.0.0.1:8888`.
15
16This document describes how you can
17:ref:`secure a Jupyter server <Jupyter_server_security>` and how to
18:ref:`run it on a public interface <jupyter_public_server>`.
19
20.. important::
21
22    **This is not the multi-user server you are looking for**. This document
23    describes how you can run a public server with a single user. This should
24    only be done by someone who wants remote access to their personal machine.
25    Even so, doing this requires a thorough understanding of the set-ups
26    limitations and security implications. If you allow multiple users to
27    access a Jupyter server as it is described in this document, their
28    commands may collide, clobber and overwrite each other.
29
30    If you want a multi-user server, the official solution is  JupyterHub_.
31    To use JupyterHub, you need a Unix server (typically Linux) running
32    somewhere that is accessible to your users on a network. This may run over
33    the public internet, but doing so introduces additional
34    `security concerns <https://jupyterhub.readthedocs.io/en/latest/getting-started/security-basics.html>`_.
35
36
37
38.. _ZeroMQ: https://zeromq.org/
39
40.. _Tornado: with Found to http://www.tornadoweb.org/en/stable/
41
42.. _JupyterHub: https://jupyterhub.readthedocs.io/en/latest/
43
44.. _Jupyter_server_security:
45
46Securing a Jupyter server
47-------------------------
48
49You can protect your Jupyter server with a simple single password. As of
50notebook 5.0 this can be done automatically. To set up a password manually you
51can configure the :attr:`ServerApp.password` setting in
52:file:`jupyter_server_config.py`.
53
54
55Prerequisite: A Jupyter server configuration file
56~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
57
58Check to see if you have a Jupyter server configuration file,
59:file:`jupyter_server_config.py`. The default location for this file
60is your Jupyter folder located in your home directory:
61
62    - Windows: :file:`C:\\Users\\USERNAME\\.jupyter\\jupyter_server_config.py`
63    - OS X: :file:`/Users/USERNAME/.jupyter/jupyter_server_config.py`
64    - Linux: :file:`/home/USERNAME/.jupyter/jupyter_server_config.py`
65
66If you don't already have a Jupyter folder, or if your Jupyter folder doesn't contain
67a Jupyter server configuration file, run the following command::
68
69  $ jupyter server --generate-config
70
71This command will create the Jupyter folder if necessary, and create a Jupyter
72server configuration file, :file:`jupyter_server_config.py`, in this folder.
73
74
75Automatic Password setup
76~~~~~~~~~~~~~~~~~~~~~~~~
77
78As of notebook 5.3, the first time you log-in using a token, the server should
79give you the opportunity to setup a password from the user interface.
80
81You will be presented with a form asking for the current _token_, as well as
82your _new_ _password_ ; enter both and click on ``Login and setup new password``.
83
84Next time you need to log in you'll be able to use the new password instead of
85the login token, otherwise follow the procedure to set a password from the
86command line.
87
88The ability to change the password at first login time may be disabled by
89integrations by setting the ``--ServerApp.allow_password_change=False``
90
91
92Starting at notebook version 5.0, you can enter and store a password for your
93server with a single command. :command:`jupyter server password` will
94prompt you for your password and record the hashed password in your
95:file:`jupyter_server_config.json`.
96
97.. code-block:: bash
98
99    $ jupyter server password
100    Enter password:  ****
101    Verify password: ****
102    [JupyterPasswordApp] Wrote hashed password to /Users/you/.jupyter/jupyter_server_config.json
103
104This can be used to reset a lost password; or if you believe your credentials
105have been leaked and desire to change your password. Changing your password will
106invalidate all logged-in sessions after a server restart.
107
108.. _hashed-pw:
109
110Preparing a hashed password
111~~~~~~~~~~~~~~~~~~~~~~~~~~~
112
113You can prepare a hashed password manually, using the function
114:func:`notebook.auth.security.passwd`:
115
116.. code-block:: ipython
117
118    In [1]: from jupyter_server.auth import passwd
119    In [2]: passwd()
120    Enter password:
121    Verify password:
122    Out[2]: 'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
123
124.. caution::
125
126  :func:`~notebook.auth.security.passwd` when called with no arguments
127  will prompt you to enter and verify your password such as
128  in the above code snippet. Although the function can also
129  be passed a string as an argument such as ``passwd('mypassword')``, please
130  **do not** pass a string as an argument inside an IPython session, as it
131  will be saved in your input history.
132
133Adding hashed password to your notebook configuration file
134~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
135You can then add the hashed password to your
136:file:`jupyter_server_config.py`. The default location for this file
137:file:`jupyter_server_config.py` is in your Jupyter folder in your home
138directory, ``~/.jupyter``, e.g.::
139
140    c.ServerApp.password = u'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
141
142Automatic password setup will store the hash in ``jupyter_server_config.json``
143while this method stores the hash in ``jupyter_server_config.py``. The ``.json``
144configuration options take precedence over the ``.py`` one, thus the manual
145password may not take effect if the Json file has a password set.
146
147
148Using SSL for encrypted communication
149~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
150When using a password, it is a good idea to also use SSL with a web
151certificate, so that your hashed password is not sent unencrypted by your
152browser.
153
154.. important::
155   Web security is rapidly changing and evolving. We provide this document
156   as a convenience to the user, and recommend that the user keep current on
157   changes that may impact security, such as new releases of OpenSSL.
158   The Open Web Application Security Project (`OWASP`_) website is a good resource
159   on general security issues and web practices.
160
161You can start the notebook to communicate via a secure protocol mode by setting
162the ``certfile`` option to your self-signed certificate, i.e. ``mycert.pem``,
163with the command::
164
165    $ jupyter server --certfile=mycert.pem --keyfile mykey.key
166
167.. tip::
168
169    A self-signed certificate can be generated with ``openssl``.  For example,
170    the following command will create a certificate valid for 365 days with
171    both the key and certificate data written to the same file::
172
173        $ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mykey.key -out mycert.pem
174
175When starting the notebook server, your browser may warn that your self-signed
176certificate is insecure or unrecognized.  If you wish to have a fully
177compliant self-signed certificate that will not raise warnings, it is possible
178(but rather involved) to create one, as explained in detail in this
179`tutorial`_. Alternatively, you may use `Let's Encrypt`_ to acquire a free SSL
180certificate and follow the steps in :ref:`using-lets-encrypt` to set up a
181public server.
182
183.. _OWASP: https://www.owasp.org/index.php/Main_Page
184.. _tutorial: https://arstechnica.com/information-technology/2009/12/how-to-get-set-with-a-secure-sertificate-for-free/
185
186.. _jupyter_public_server:
187
188Running a public notebook server
189--------------------------------
190
191If you want to access your notebook server remotely via a web browser,
192you can do so by running a public notebook server. For optimal security
193when running a public notebook server, you should first secure the
194server with a password and SSL/HTTPS as described in
195:ref:`jupyter_server_security`.
196
197Start by creating a certificate file and a hashed password, as explained in
198:ref:`jupyter_server_security`.
199
200If you don't already have one, create a
201config file for the notebook using the following command line::
202
203  $ jupyter server --generate-config
204
205In the ``~/.jupyter`` directory, edit the notebook config file,
206``jupyter_server_config.py``.  By default, the notebook config file has
207all fields commented out. The minimum set of configuration options that
208you should uncomment and edit in :file:`jupyter_server_config.py` is the
209following::
210
211     # Set options for certfile, ip, password, and toggle off
212     # browser auto-opening
213     c.ServerApp.certfile = u'/absolute/path/to/your/certificate/mycert.pem'
214     c.ServerApp.keyfile = u'/absolute/path/to/your/certificate/mykey.key'
215     # Set ip to '*' to bind on all interfaces (ips) for the public server
216     c.ServerApp.ip = '*'
217     c.ServerApp.password = u'sha1:bcd259ccf...<your hashed password here>'
218     c.ServerApp.open_browser = False
219
220     # It is a good idea to set a known, fixed port for server access
221     c.ServerApp.port = 9999
222
223You can then start the notebook using the ``jupyter server`` command.
224
225.. _using-lets-encrypt:
226
227Using Let's Encrypt
228~~~~~~~~~~~~~~~~~~~
229`Let's Encrypt`_ provides free SSL/TLS certificates. You can also set up a
230public server using a `Let's Encrypt`_ certificate.
231
232:ref:`jupyter_public_server` will be similar when using a Let's Encrypt
233certificate with a few configuration changes. Here are the steps:
234
2351. Create a `Let's Encrypt certificate <https://letsencrypt.org/getting-started/>`_.
2362. Use :ref:`hashed-pw` to create one.
2373. If you don't already have config file for the notebook, create one
238   using the following command:
239
240   .. code-block:: bash
241
242       $ jupyter server --generate-config
243
2444. In the ``~/.jupyter`` directory, edit the notebook config file,
245``jupyter_server_config.py``.  By default, the notebook config file has
246all fields commented out. The minimum set of configuration options that
247you should to uncomment and edit in :file:`jupyter_server_config.py` is the
248following::
249
250     # Set options for certfile, ip, password, and toggle off
251     # browser auto-opening
252     c.ServerApp.certfile = u'/absolute/path/to/your/certificate/fullchain.pem'
253     c.ServerApp.keyfile = u'/absolute/path/to/your/certificate/privkey.pem'
254     # Set ip to '*' to bind on all interfaces (ips) for the public server
255     c.ServerApp.ip = '*'
256     c.ServerApp.password = u'sha1:bcd259ccf...<your hashed password here>'
257     c.ServerApp.open_browser = False
258
259     # It is a good idea to set a known, fixed port for server access
260     c.ServerApp.port = 9999
261
262You can then start the notebook using the ``jupyter server`` command.
263
264.. important::
265
266    **Use 'https'.**
267    Keep in mind that when you enable SSL support, you must access the
268    notebook server over ``https://``, not over plain ``http://``.  The startup
269    message from the server prints a reminder in the console, but *it is easy
270    to overlook this detail and think the server is for some reason
271    non-responsive*.
272
273    **When using SSL, always access the notebook server with 'https://'.**
274
275You may now access the public server by pointing your browser to
276``https://your.host.com:9999`` where ``your.host.com`` is your public server's
277domain.
278
279.. _`Let's Encrypt`: https://letsencrypt.org
280
281
282Firewall Setup
283~~~~~~~~~~~~~~
284
285To function correctly, the firewall on the computer running the jupyter
286notebook server must be configured to allow connections from client
287machines on the access port ``c.ServerApp.port`` set in
288:file:`jupyter_server_config.py` to allow connections to the
289web interface.  The firewall must also allow connections from
290127.0.0.1 (localhost) on ports from 49152 to 65535.
291These ports are used by the server to communicate with the notebook kernels.
292The kernel communication ports are chosen randomly by ZeroMQ, and may require
293multiple connections per kernel, so a large range of ports must be accessible.
294
295Running the notebook with a customized URL prefix
296-------------------------------------------------
297
298The notebook dashboard, which is the landing page with an overview
299of the notebooks in your working directory, is typically found and accessed
300at the default URL ``http://localhost:8888/``.
301
302If you prefer to customize the URL prefix for the notebook dashboard, you can
303do so through modifying ``jupyter_server_config.py``. For example, if you
304prefer that the notebook dashboard be located with a sub-directory that
305contains other ipython files, e.g. ``http://localhost:8888/ipython/``,
306you can do so with configuration options like the following (see above for
307instructions about modifying ``jupyter_server_config.py``):
308
309.. code-block:: python
310
311    c.ServerApp.base_url = '/ipython/'
312
313Embedding the notebook in another website
314-----------------------------------------
315
316Sometimes you may want to embed the notebook somewhere on your website,
317e.g. in an IFrame. To do this, you may need to override the
318Content-Security-Policy to allow embedding. Assuming your website is at
319`https://mywebsite.example.com`, you can embed the notebook on your website
320with the following configuration setting in
321:file:`jupyter_server_config.py`:
322
323.. code-block:: python
324
325    c.ServerApp.tornado_settings = {
326        'headers': {
327            'Content-Security-Policy': "frame-ancestors https://mywebsite.example.com 'self' "
328        }
329    }
330
331When embedding the notebook in a website using an iframe,
332consider putting the notebook in single-tab mode.
333Since the notebook opens some links in new tabs by default,
334single-tab mode keeps the notebook from opening additional tabs.
335Adding the following to :file:`~/.jupyter/custom/custom.js` will enable
336single-tab mode:
337
338.. code-block:: javascript
339
340    define(['base/js/namespace'], function(Jupyter){
341        Jupyter._target = '_self';
342    });
343
344
345Using a gateway server for kernel management
346--------------------------------------------
347
348You are now able to redirect the management of your kernels to a Gateway Server
349(i.e., `Jupyter Kernel Gateway <https://jupyter-kernel-gateway.readthedocs.io/en/latest/>`_ or
350`Jupyter Enterprise Gateway <https://jupyter-enterprise-gateway.readthedocs.io/en/latest/>`_)
351simply by specifying a Gateway url via the following command-line option:
352
353    .. code-block:: bash
354
355        $ jupyter notebook --gateway-url=http://my-gateway-server:8888
356
357the environment:
358
359    .. code-block:: bash
360
361        JUPYTER_GATEWAY_URL=http://my-gateway-server:8888
362
363or in :file:`jupyter_notebook_config.py`:
364
365   .. code-block:: python
366
367      c.GatewayClient.url = http://my-gateway-server:8888
368
369When provided, all kernel specifications will be retrieved from the specified Gateway server and all
370kernels will be managed by that server.  This option enables the ability to target kernel processes
371against managed clusters while allowing for the notebook's management to remain local to the Notebook
372server.
373
374Known issues
375------------
376
377Proxies
378~~~~~~~
379
380When behind a proxy, especially if your system or browser is set to autodetect
381the proxy, the notebook web application might fail to connect to the server's
382websockets, and present you with a warning at startup. In this case, you need
383to configure your system not to use the proxy for the server's address.
384
385For example, in Firefox, go to the Preferences panel, Advanced section,
386Network tab, click 'Settings...', and add the address of the Jupyter server
387to the 'No proxy for' field.
388
389Content-Security-Policy (CSP)
390~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
391
392Certain `security guidelines
393<https://infosec.mozilla.org/guidelines/web_security.html#content-security-policy>`_
394recommend that servers use a Content-Security-Policy (CSP) header to prevent
395cross-site scripting vulnerabilities, specifically limiting to ``default-src:
396https:`` when possible.  This directive causes two problems with Jupyter.
397First, it disables execution of inline javascript code, which is used
398extensively by Jupyter.  Second, it limits communication to the https scheme,
399and prevents WebSockets from working because they communicate via the wss
400scheme (or ws for insecure communication).  Jupyter uses WebSockets for
401interacting with kernels, so when you visit a server with such a CSP, your
402browser will block attempts to use wss, which will cause you to see
403"Connection failed" messages from jupyter notebooks, or simply no response
404from jupyter terminals.  By looking in your browser's javascript console, you
405can see any error messages that will explain what is failing.
406
407To avoid these problem, you need to add ``'unsafe-inline'`` and ``connect-src
408https: wss:`` to your CSP header, at least for pages served by jupyter.  (That
409is, you can leave your CSP unchanged for other parts of your website.)  Note
410that multiple CSP headers are allowed, but successive CSP headers can only
411restrict the policy; they cannot loosen it.  For example, if your server sends
412both of these headers
413
414    Content-Security-Policy "default-src https: 'unsafe-inline'"
415    Content-Security-Policy "connect-src https: wss:"
416
417the first policy will already eliminate wss connections, so the second has no
418effect.  Therefore, you can't simply add the second header; you have to
419actually modify your CSP header to look more like this:
420
421    Content-Security-Policy "default-src https: 'unsafe-inline'; connect-src https: wss:"
422
423
424
425Docker CMD
426~~~~~~~~~~
427
428Using ``jupyter server`` as a
429`Docker CMD <https://docs.docker.com/engine/reference/builder/#cmd>`_ results in
430kernels repeatedly crashing, likely due to a lack of `PID reaping
431<https://blog.phusion.nl/2015/01/20/docker-and-the-pid-1-zombie-reaping-problem/>`_.
432To avoid this, use the `tini <https://github.com/krallin/tini>`_ ``init`` as your
433Dockerfile `ENTRYPOINT`::
434
435  # Add Tini. Tini operates as a process subreaper for jupyter. This prevents
436  # kernel crashes.
437  ENV TINI_VERSION v0.6.0
438  ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /usr/bin/tini
439  RUN chmod +x /usr/bin/tini
440  ENTRYPOINT ["/usr/bin/tini", "--"]
441
442  EXPOSE 8888
443  CMD ["jupyter", "server", "--port=8888", "--no-browser", "--ip=0.0.0.0"]
444