Security

Security Hardening

RESTHeart Ulabase

Introduction

This page lists what to check before a RESTHeart deployment is exposed, and the features that protect it from common attacks.

Important
The checks on this page cover RESTHeart. The operating system, the network and MongoDB need their own.

Checklist

Best practice

Priority

Impact

Update the admin user password

Mandatory

Action required

Disable the root role

Suggested

Configuration required

Disable the auto-creation of the admin user

Suggested

Configuration required

Use HTTPS

Mandatory

Action required

Secure connection to MongoDB

Mandatory

Action required

Make sure password are stored in an encrypted form

Mandatory

No action required if the default authenticator is used

Enforce strong passwords

Mandatory

Configuration required

Enable bruteForceAttackGuard

Suggested

Configuration required

Enable originVetoer

Suggested

Configuration required

Define and test the ACL

Mandatory

Action required

Use only aggregations and forbid the filter query parameter

Suggested

No action required since v9.16

The password and the one-time tokens cannot be queried

Mandatory

No action required

Blacklist the operators that run JavaScript

Mandatory

No action required

Keep the values bound into a query as values

Mandatory

No action required since v9.17

Define role-specific GraphQL applications

Mandatory

Action required

Update the admin user password

At first startup RESTHeart creates the user admin with the password secret.

Warning
Change this password before anything else. The role admin is the root role of mongoAclAuthorizer, so this user can execute any request.

To change it:

$ curl -i -u admin:secret -X PATCH localhost:8080/users/admin -H "Content-Type: application/json" -d '{ "password": "my-strong-password" }'

To create users, roles and permissions, see User Management.

Disable the auto-creation of the admin user

At startup mongoRealmAuthenticator creates the user admin if it does not exist. A deployment that deleted admin therefore gets it back at the next restart, with the password secret.

Disable the auto-creation:

mongoRealmAuthenticator:
# other options omitted
# clients with root-role can execute any request
create-user: false # <---- disable auto-creation of the admin user
create-user-document: '{"_id": "admin", "password": "secret", "roles": ["admin"]}'

Disable the root role

By default mongoAclAuthorizer defines a root role.

mongoAclAuthorizer:
    # other options omitted
    # clients with root-role can execute any request
    root-role: admin
Warning
A user with this role can execute any request: it can read and delete every database and collection.

Once the ACL is in place, disable the root role:

mongoAclAuthorizer:
    # other options omitted
    # root role disabled!
    root-role: null

Use HTTPS

Warning
Without TLS, credentials and tokens travel in clear text.

Terminate TLS in a reverse proxy, such as Nginx or an API gateway, or enable only the https-listener of RESTHeart: see Configure TLS.

Secure connection to MongoDB

Connect to MongoDB over TLS: see Secure connection to MongoDB.

Give the MongoDB user of RESTHeart only the permissions RESTHeart needs: see Restrict permissions of MongoDb User.

Make sure password are stored in an encrypted form

mongoRealmAuthenticator, the authenticator to use in production, stores each password as a bcrypt hash with its default configuration:

mongoRealmAuthenticator:
    # omitting other options
    bcrypt-hashed-password: true
    bcrypt-complexity: 12

fileRealmAuthenticator does not hash passwords. Use it only for development and tests.

Important
A custom Authenticator must hash the passwords it stores.

Enforce strong passwords

When users set their own password, some choose a weak one, like 123456. mongoRealmAuthenticator can refuse a write to a user document with a password below a minimum strength:

mongoRealmAuthenticator:
    # omitting other options
    enforce-minimum-password-strength: false
    # Integer from 0 to 4
    # 0 Weak        (guesses < 3^10)
    # 1 Fair        (guesses < 6^10)
    # 2 Good        (guesses < 8^10)
    # 3 Strong      (guesses < 10^10)
    # 4 Very strong (guesses >= 10^10)
    minimum-password-strength: 3

bruteForceAttackGuard

bruteForceAttackGuard slows down password guessing. It answers 429 Too Many Requests in two cases, both counted over the last 10 seconds:

  • more than max-failed-attempts failed requests for the same user from the same ip;

  • more than max-failed-attempts-per-ip failed requests from the same ip, whatever the user.

The count per user matters for the users who share an ip, behind a carrier-grade NAT or a corporate proxy: the failures of one do not block the others. See Brute Force Attack Guard.

Important
Behind a reverse proxy, the proxy must set the X-Forwarded-For header with the client ip, and the option trust-x-forwarded-for must be true.
# defends from brute force password cracking attacks
# by returning `429 Too Many Requests` when more than
# `max-failed-attempts` wrong requests
# are received in last 10 seconds from the same ip
bruteForceAttackGuard:
    enabled: false
    # if true, the source ip is obtained from X-Forwarded-For header
    # this requires that header being set by the proxy, dangerous otherwise
    trust-x-forwarded-for: false
    # max number of failed attempts per ip and user in 10 seconds sliding window
    # before returning 429 Too Many Requests to that ip for that user
    max-failed-attempts: 5
    # max number of failed attempts per ip whatever the user
    max-failed-attempts-per-ip: 50

originVetoer

The originVetoer authorizer protects from CSRF attacks: it refuses a request whose Origin header is not in a whitelist. An allowed origin is an exact value or a pattern.

Note
It is disabled by default. To enable it, add the configuration below to restheart.yml with the origins to allow.

Configuration Example

originVetoer:
  enabled: true
  whitelist:
    - https://restheart.org
    - https://restheart.com
  whitelist-patterns:
    - https://*.mydomain.com
    - http://localhost:*
  allow-missing-origin: true
  ignore-paths:
    - /public/*

Configuration Properties

  • whitelist
    A list of exact origins or prefixes. Requests with an Origin header that matches (or starts with) any entry in this list are allowed.

    whitelist:
      - https://restheart.org
      - https://restheart.com
  • whitelist-patterns
    A list of glob-like patterns for allowed origins. Use * as a wildcard for any sequence of characters.

    Note

    Available from RESTHeart version 8.5.0+

    Examples: - https://.mydomain.com allows any subdomain of mydomain.com - http://localhost: allows any port on localhost

    +

    whitelist-patterns:
      - https://*.mydomain.com
      - http://localhost:*
  • ignore-paths
    (Optional) A list of path patterns to ignore. Requests to these paths are accepted without checking the Origin header.

    ignore-paths:
      - /public/*
      - /health
  • allow-missing-origin
    (Optional, default: true since 9.6) When true, requests with no Origin header (i.e. non-browser clients such as curl, CLIs, backend integrations) are allowed through. Browser requests are still validated against the whitelist.

    Note

    A request without Origin cannot be a CSRF attack: a browser always sends Origin on the requests CSRF uses, the cross-site ones that are not a GET and every request with a CORS preflight. With true, clients that are not browsers reach RESTHeart too.

    Set to false to restore pre-9.6 behavior (missing Origin is always denied):

    allow-missing-origin: false

How It Works

  1. If the request path matches any ignore-paths entry, the request is accepted without checking the Origin header.

  2. If neither whitelist nor whitelist-patterns is defined, all origins are accepted.

  3. If the Origin header is missing, the request is allowed if allow-missing-origin is true (the default since 9.6), otherwise rejected.

  4. The Origin header is checked against the whitelist (exact/prefix match).

  5. If not matched, the Origin header is checked against the whitelist-patterns (wildcard match).

  6. If the origin does not match any entry, the request is rejected.

Example

originVetoer:
  enabled: true
  whitelist:
    - https://restheart.org
    - https://restheart.com
  whitelist-patterns:
    - https://*.mydomain.com
    - http://localhost:*
  allow-missing-origin: true
  ignore-paths:
    - /public/*

With this configuration:

Define and test the ACL

With mongoAclAuthorizer each role gets its own permissions. Write them so that a role can execute only the requests it needs:

  • allow only the query parameters the request uses, with qparams-whitelist;

  • hide the fields the role must not see, with projectResponse;

  • set on the server the properties the client must not choose, with mergeRequest;

  • limit the documents the role reads and writes, with readFilter and writeFilter.

This permission does all of it for the creation of a document:

{
    "_id": "userCanCreateDocumentsInOwnCollection",
    "description": [
        "**** DESCRIPTION PROPERTY IS NOT REQUIRED, HERE ONLY FOR DOCUMENTATION PURPOSES",
        "allow role 'user' to create documents under /{userid}",
        "the request content must contain 'title' and 'content' <- bson-request-contains(title, content)",
        "the request content cannot contain any property other than 'title' and 'content' <- bson-request-whitelist(title, content)",
        "no qparams can be specified <- qparams-whitelist()",
        "the property 'author' and 'status' are added to the request at server-side <- mergeRequest",
        "the property 'log' with some request values is added to the request at server-side <- mergeRequest"
    ],
    "roles": ["user"],
    "priority": 100,
    "predicate": "method(POST) and path-template('/{userid}') and equals(@user._id, ${userid}) and bson-request-whitelist(title, content) and bson-request-contains(title, content) and qparams-whitelist()",
    "mongo": {
      "mergeRequest": {
        "author": "@user._id",
        "status": "draft",
        "log": "@request"
      }
    }
  }

The format is described in Format of permission.

Note
For a rule the permission language cannot express, write a custom Vetoer or a request Interceptor.

Test the ACL with a user of each role: the requests the role needs must pass, and the others must get 403.

Use only aggregations and forbid the filter query parameter

With the filter query parameter a client writes its own MongoDB query. This is handy during development. In production it lets the client ask what the application never meant to answer, such as a condition on a field the permission hides.

Since v9.16 a permission refuses filter, sort and sort_by on reads, unless it sets allowFilter. Keep this default. Declare the queries of the application as aggregations: the client then sends only the values of their variables.

Before v9.16, add qparams-blacklist(filter, sort, sort_by) to the predicate of each permission.

The password and the one-time tokens cannot be queried

A query can reveal a field that the response hides. A condition on the field tells which documents match, and a sort on it tells the order of its values.

Two interceptors, enabled by default, refuse with 403 a request that queries one of these fields. They run before the request is executed:

Interceptor Collection Fields

denyFilterOnUserPwd

the users collection of mongoRealmAuthenticator

the password

denyFilterOnAccountTokens (since v9.17)

auth_invitations

token

denyFilterOnAccountTokens (since v9.17)

the users collection

emailVerificationToken, passwordResetToken, inviteToken

Both check the filter, sort and sort_by parameters at any depth: nested documents, $or, $and and $nor, and the field used as a path in an expression, such as "$password" under $expr.

Both apply to every method. A bulk PATCH or DELETE with a condition on one of these fields is refused too: the number of documents it matches would answer as a read does.

Note
Before v9.17 denyFilterOnUserPwd checked only the keys of nested documents, and only on a GET. A condition inside $or, a field path in $expr, a sort, and the filter of a bulk write were not refused. The tokens of the accounts had no check.

denyFilterOnAccountTokens applies to a collection with those names in any database. To disable it:

denyFilterOnAccountTokens:
  enabled: false

For the other fields a permission hides with projectResponse, keep allowFilter off and do not grant bulk writes on the collection.

Blacklist the operators that run JavaScript

The $where, $function and $accumulator operators run JavaScript on the MongoDB server. A client must never reach them. A client can write operators in three places, and each one is checked by default:

  • the filter query parameter, by the filterOperatorsBlacklist plugin;

  • the keys query parameter, by the same plugin: a projection accepts aggregation expressions, $function included;

  • the aggregation pipeline of a PATCH request, by the updatePipelineSecurityChecker interceptor, against the same aggregationSecurity blacklists that guard the aggregations declared on a collection. A pipeline with $function, or with a blacklisted stage such as $lookup, is refused with 403.

A deployment that allows filter can blacklist the other operators it does not use with filterOperatorsBlacklist: see its configuration.

Note
filterOperatorsBlacklist is enabled by default and blacklists $where, $function and $accumulator, anywhere in filter and keys. Before 9.11.0 the default list held $where only; before 9.11.1 keys and the PATCH pipeline were not checked.

Keep the values bound into a query as values

Aggregations, change streams, GraphQL mappings and permission filters take values from the request: variables, arguments, the body. Whoever defines them writes the query, and the client supplies only values.

Since v9.17 RESTHeart enforces it. A value that carries a MongoDB operator is refused, or matches no document. A string starting with $ is bound as a string, so MongoDB does not read it as a field path.

The checks are on by default. Leave them on:

Define role-specific GraphQL applications

The GraphQL API is read-only, so the risk is one: a role reads data it should not see. A GraphQL client chooses the fields and the relations it reads, among those the schema offers. An app therefore exposes to every caller everything its schema and its mappings reach.

Define one app for each kind of caller, each bound to its own URI and with mappings that read only what that caller may see. Then grant each role only the URIs of its apps in the ACL.

To hide single fields by role in one app, see @visible. To scope a mapping to the caller, use the predefined variables, such as @user._id.

Warning
What an app exposes depends on the filters in its mappings. Test each app with a user of each role.