# Security Cylinder keeps its own surface small: it is one file, it depends only on Werkzeug, and it keeps nothing of one request for the next. The security of an app built on it mostly comes down to a handful of facts about how requests are routed. This page collects them into a checklist to go through before an app faces the internet. ## A file is public only where a handler serves it No file in a webapp directory is sent to a client unless a page handler sends it. Handler files are code: they run, and their source is never sent. Any other file, a Python file included, is sent only beneath a handler file that uses Cylinder's own [`static_file`](static-files.md), and a file anywhere else in the tree gets a `404`. So there is one thing to check before deploying: each handler that serves files, and what is beneath it. - Give the files for the browser a directory of their own, such as `assets`, and serve that. A handler beside the webapp directory that serves the whole site makes every file in it public. - Everything beneath a handler that serves files is something you mean to publish. The exceptions are under [What is never served](static-files.md#what-is-never-served). These still go beside the webapp directory, not inside it, so that no handler added later can publish them: - Python modules that your handlers import - databases, such as a `.sqlite` file - templates, if they contain logic or comments you would not publish - configuration, credentials, or key files - data exports, backups, or uploads from users The layouts in [Composing an application](composition.md) all keep them there. ## A tree handler answers for every path beneath it A handler serves its own path, and a URL that nobody wrote a page for gets a `404`. A [`.tree.` handler](routing.md#handlers-for-a-whole-tree) is the exception: it is the answer for any path under its own that has no closer match. Unless it checks, it returns `200` for URLs that do not exist. That is mostly a correctness problem, with a security edge: scanners see a section where every URL "works", caches store junk URLs, and an old path you thought was gone may still answer. Have each `.tree.` handler reject the shapes it does not serve: ```python def main(response, remainder, abort): if len(remainder) > 1: abort(404) ... ``` Where the shape of a URL is known, use a [placeholder](routing.md#placeholders) instead. It matches one segment and no more, so there is nothing to reject. See [Paths a handler does not serve](routing.md#paths-a-handler-does-not-serve). ## Nothing in a request is checked for you Cylinder passes a handler Werkzeug's `request` as it is. It has no schemas and no typed parameters, so it checks and converts nothing: a query parameter, a form field, a header, a cookie, and a JSON body are what the client sent. - Check each value in the handler that uses it: that it is there, that it is of the type you expect, and that it is in range. Turn down a request that fails with `abort(400)`, as [the handler that creates a user](json-apis.md#creating) does for its JSON body. - For a large API, a validation library does the same work. It is a library like any other: import it where it is used, or pass it in through [`app_map()`](composition.md#extra-parameters-on-main). ## A placeholder's value comes from the client The value a placeholder passes in, such as `user_id`, is one segment of the URL, decoded and otherwise untouched. It is as trustworthy as a query parameter, which is to say not at all. - Check it before using it. It can be any text of any length, and it is always a string. - Never build a filesystem path, a SQL statement, or a template name from it without the care you would give any other input. - A value in the URL is not a permission. `/users/123/settings` says which user is being asked about, not that the visitor is user `123`. Compare it with the logged-in user, in a hook named for the placeholder or in the handler. - A name takes its URL away from the placeholder. Once `users/admin.hook.early.py` exists, `/users/admin` is answered only by files named `admin`, and never by `{user_id}.page.get.py`. A hook written for one value therefore cannot be skipped, and that URL needs a page of its own. ## A hook runs for every method Every hook between the site root and a URL runs, so a hook added for one section cannot switch off a check made by a hook above it. And a hook is [not named for a method](hooks.md#hooks-and-http-methods), so no method is left out of a check that a hook makes, and no file beside a hook can answer in its place for one. - A hook that lets some requests through says which ones in its own code, such as `if request.method == "OPTIONS": return response`. Read every such line as an exception to the check. - Keep a hook as a file of its own. Cylinder [passes over links](static-files.md#what-is-never-served), so a hook that is a symbolic link does not run. To share a check between sections, import it from a module. - Confirm with a test that a protected section rejects an unauthenticated request, for each method it accepts. See [Every hook on the path runs](hooks.md#every-hook-on-the-path-runs). ## Put headers that must be on every response in a hook at the root Headers and cookies set before a request is aborted are [kept on the error response](errors.md#what-survives-an-abort), so a security header set in a hook is sent with error pages and redirects as well as with successful pages. That includes the `404` or `405` for a request that no page handler serves: the early hooks run before Cylinder turns the request down. Prefer a late hook at the root for headers that must not be missing or changed. It runs last on every response that the webapp answers, after every other hook, and it gets the final say over anything they or a handler set. A header that a hook sets is missing from two [plain `500`s](errors.md#cylinder-always-answers): one that is answered before the files of the request are known, as for a failure in `app_map()`, and one that takes the place of a response that cannot be sent at all, such as one with a `Location` that Werkzeug cannot read. A header that must be on those too is set in your proxy. The reverse also applies: a header set before an abort stays on the error response. Do not set `Cache-Control: public` or a similar success-only header before the last point where a handler might abort, or an error page could be cached. A late hook runs on error pages and redirects as well, so one that sets such a header should check `response.status_code` first. ## Choose the webapp from a fixed table `app_map()` decides which directory serves a request. If it serves different sites for different hostnames, look the hostname up in a dictionary you wrote: ```python SITES = {"foo.com": "foo", "bar.com": "bar"} def app_map(request): return "my_webapps", SITES.get(request.host, "bar") ``` Never build the webapp name or directory from a value in the request, such as the `Host` header or a query parameter. Those are chosen by the client, and a crafted value could point Cylinder at a directory you did not mean to serve. Cylinder looks the webapp name up in the directory as one name, so a name with a path in it names nothing there, which is a `500`, and cannot lead out of the directory. It can still name another webapp in it, and the directory is used as it is given. ## Redirect only where you mean to `abort(302, location)` sends the visitor wherever `location` says. A location that is built from the request can be made to leave the site: a browser reads `//evil.example` and `/\evil.example` as another host, and it drops a tab or a line break from a URL before it reads it. A link to your site that sends its visitor on to someone else's is what a phishing message wants. - Take a destination from the request, such as the `next` parameter that a login page returns to, only if it is one you expect. Look it up in a table, or accept nothing but a path that starts with a single `/` and is made of the characters your own paths use, such as letters, digits, `/`, `-`, and `_`. That leaves out the backslash, the tab, and the line break, which are the ways around a check for `//`. - `request.path` is the path with the client's percent-encoding undone. Before it goes into a `Location`, encode it again with `urllib.parse.quote()`, as [the hook that redirects a stray slash](hooks.md#example-redirecting-a-stray-slash) does. ## Do not show tracebacks to visitors Cylinder logs the traceback of an uncaught exception, and never sends it. Without a `500` error handler, the visitor gets Werkzeug's plain `500` page, which reveals nothing. If you write a `500` handler, have it send a generic message. The traceback is already in the log. See [Uncaught exceptions](errors.md#uncaught-exceptions). ## Sessions and cookies Cylinder leaves sessions to you. If you use the [example implementation](composition.md#sessions) or write your own: - Set `httponly=True` and, in production, `secure=True` on the session cookie. Consider `samesite="Lax"`. - Never accept a session ID that the server did not issue. The example does this. - Store session data on the server, or sign it. Do not trust data that round-trips through the browser. - Cylinder has no built-in protection against cross-site request forgery. A site that uses cookies for authentication and accepts form posts needs its own. An early hook is the place for the check. One that compares a token in a form field has to [opt in to reading the body](handlers.md#when-a-hook-or-an-error-handler-needs-the-body), and one that compares a token in a header does not. ## Behind a proxy If the app runs behind a reverse proxy, [tell it which forwarding headers to believe](deployment.md#behind-a-reverse-proxy): only the ones your proxies set, from the exact number of proxies you operate. Trusting forwarding headers that your own proxies do not set lets a client forge its address. The same goes for the header named in `request_id_header`. Name one only if your proxy [replaces what a client sends in it](operations.md#request-ids), or a client chooses the ID that its requests are logged under. Terminate HTTPS at the proxy or the WSGI server. Cylinder does not handle TLS. A rule in the proxy that names a path, such as one that keeps `/admin` to an office network, holds only if the proxy and the app agree on what the path is. Cylinder serves a URL in [one spelling only](routing.md#one-spelling-for-each-url), so `//admin`, `/admin/`, and `/./admin` are not other ways to reach `/admin`. One thing is settled before Cylinder sees a request: the WSGI server decodes a percent-encoded slash, `%2F`, so Cylinder cannot tell it from a plain one. Check that the proxy treats it as a slash too, or put the check in a [hook](hooks.md#example-protecting-a-section-of-a-site), which is matched the same way as the page it protects. ## Request size Cylinder does not limit the size of a request body. Set a limit in your proxy or WSGI server. What Cylinder does is keep everything but a page handler from [reading the body](handlers.md#only-a-page-handler-reads-the-request-body) unless it says so. A request that a hook turns away has not had its form decoded or its upload stored, by the hooks on the way in or by the error handler and the late hooks that answer it. Keep the reading in page handlers, behind the hooks that check who is asking, and read every `request.shallow = False` in a hook or an error handler as an exception to that. ## Reporting a vulnerability Please report security problems privately through the [repository's security page](https://github.com/plasmacan/cylinder/security), not in a public issue.