Skip to main content

Database Access with Self-Hosted CockroachDB

Report an Issue

Teleport can provide secure access to CockroachDB via the Teleport Database Service. This allows for fine-grained access control through the Teleport RBAC system.

The Teleport Database Service proxies traffic from database clients to self-hosted databases in your infrastructure. Teleport maintains a certificate authority (CA) for database clients. You configure your database to trust the Teleport database client CA, and the Teleport Database Service presents certificates signed by this CA when proxying user traffic. With this setup, there is no need to store long-lived credentials for self-hosted databases.

Meanwhile, the Teleport Database Service verifies self-hosted databases by checking their TLS certificates against either the Teleport database CA or a custom CA used with the database.

In this guide, you will:

  1. Configure your CockroachDB database for Teleport access.
  2. Add the database to your Teleport cluster.
  3. Connect to the database via Teleport.

How it works​

The Teleport Database Service authenticates to your self-hosted CockroachDB database using mutual TLS. CockroachDB trusts the Teleport certificate authority for database clients, and presents a certificate signed by either the Teleport database CA or a custom CA. When a user initiates a database session, the Teleport Database Service presents a certificate signed by Teleport. The authenticated connection then proxies client traffic from the user.

Prerequisites​

  • A running Teleport cluster accessible at a hostname with a valid TLS certificate. If you want to get started with Teleport, sign up for a free trial or set up a demo environment.

  • The tctl and tsh clients.

    Installing tctl and tsh clients
    1. Determine the version of your Teleport cluster. The tctl and tsh clients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at /v1/webapi/find and use a JSON query tool to obtain your cluster version. Replace teleport.example.com:443 with the web address of your Teleport Proxy Service:

      TELEPORT_DOMAIN=teleport.example.com:443
      TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')"
    2. Follow the instructions for your platform to install tctl and tsh clients:

      Download the signed macOS .pkg installer for Teleport, which includes the tctl and tsh clients:

      curl -O https://cdn.teleport.dev/teleport-${TELEPORT_VERSION?}.pkg

      In Finder double-click the pkg file to begin installation.

      danger

      Using Homebrew to install Teleport is not supported. The Teleport package in Homebrew is not maintained by Teleport and we can't guarantee its reliability or security.

    Connecting with TLS routing disabled

    This guide's commands assume your Teleport cluster uses TLS routing (proxy_listener_mode: multiplex), where the tctl and tsh clients reach every Teleport service through the Proxy Service's web address on port 443. If you're not sure whether this applies to your cluster, check with whoever manages it.

    If your cluster uses separate listener ports instead, adjust ports as follows:

    • tsh commands (e.g., tsh login --proxy=...): continue using the Proxy Service web address on port 3080 (or 443 if behind a load balancer). Do not change these to port 3025.

    • Direct tctl or Auth Service API commands: use port 3025 for the Auth Service gRPC listener:

      tctl status --auth-server=teleport.example.com:3025
  • A self-hosted CockroachDB cluster.

  • A host, e.g., an Amazon EC2 instance, where you will run the Teleport Database Service, separate from the host(s) running the Teleport Auth Service and Proxy Service.

    Single-node Teleport clusters

    If you run the Database Service as a separate process on the same host as the Proxy Service, the reverse tunnel may fail to connect through the proxy's public address due to NAT hairpinning limitations in some cloud environments (notably GCP and certain on-prem setups). To resolve this, add your proxy domain to /etc/hosts pointing to 127.0.0.1:

    echo "127.0.0.1 teleport.example.com" | sudo tee -a /etc/hosts

    Alternatively, run all Teleport services in a single process (Auth Service, Proxy Service, and Database Service in one teleport.yaml) to avoid the reverse tunnel entirely.

  • Check that you can connect to your Teleport cluster and verify that you can run tctl and tsh commands using your current credentials.

    1. Assign teleport.example.com to the domain name of the Teleport Proxy Service in your cluster and [email protected] to your Teleport username.

    2. Authenticate to your Teleport cluster. This depends on whether your shell is interactive or not.

      In an interactive shell: Run the following command. By default, this triggers a multi-factor authentication prompt:

      tsh login --proxy=teleport.example.com --user=[email protected]
      tctl status

      Cluster teleport.example.com

      Version 20.0.0-dev

      CA pin sha256:abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678

      On non-interactive environments: If you are running tsh and tctl as an AI agent, in a CI/CD environment, or similar, make sure the TELEPORT_IDENTITY_FILE environment variable is assigned to a valid file path with credentials for your cluster. tsh and tctl read the file path from the environment variable and do not require a separate authentication step. If there is no identity file available, we recommend that you set up Machine ID to provision one automatically.

      When executing tctl commands with an identity file, you must pass the --auth-server flag to provide the Teleport Auth Service address, which is not included in the identity file. If you provide the Proxy Service address, tctl connects to the Proxy Service, which forwards traffic to and from the Teleport Auth Service. Update 443 to 3025 if you are contacting the Auth Service directly with tctl:

      tctl status --auth-server=teleport.example.com:443

      For tsh commands that read an identity file, you must pass the --proxy flag, which points tsh to the address of the Teleport Proxy Service:

      tsh status --proxy=teleport.example.com

      Ensure client commands can access your identity file. Replace path/to/identity/file with the path to your identity file:

      export TELEPORT_IDENTITY_FILE="${TELEPORT_IDENTITY_FILE:-path/to/identity/file}"

      Add the --auth-server or --proxy flags to all subsequent tctl and tsh commands.

    If you can connect to the cluster and run the tctl status command, you can use your current credentials to run subsequent tctl commands from your workstation. If you host your own Teleport cluster, you can also run tctl commands on the computer that hosts the Teleport Auth Service for full permissions.

  • A certificate authority to issue CockroachDB certificates for nodes in your CockroachDB cluster, including access to the CA certificate and private key.

    Why do I need my own CA?

    Distributed databases like CockroachDB use mTLS for node-to-node communication. Teleport requires that you have your own CA to issue certificates for node-to-node mTLS communication.

    Teleport uses a split-CA architecture for database access. The Teleport db CA issues server certificates and the db_client CA issues client certificates.

    Databases are configured to trust the Teleport db_client CA for client authentication, but not the db CA. Additionally, Teleport only issues ephemeral db_client CA certificates.

    When a CockroachDB node connects to another CockroachDB node, it must present a certificate that the other node trusts for client authentication. Since Teleport does not issue long-lived db_client certificates, the node needs to have a long-lived certificate issued by another CA that its peer node trusts.

    The split db and db_client CA architecture was introduced as a security fix in Teleport versions 14.3.7 and 15.

    See Database CA Migrations for more information.

  • Either the cockroach or psql command-line client installed on your workstation and available in your PATH. tsh uses one of these clients to connect to CockroachDB. If your CockroachDB nodes must serve Teleport-issued certificates, install the cockroach client, which you use to issue node client certificates in Serve Teleport-issued certificates from CockroachDB nodes.

Step 1/4. Set up the Teleport Database Service​

The Database Service requires a valid join token to join your Teleport cluster. Run the following tctl command and save the token output in /tmp/token on the server that will run the Database Service:

tctl tokens add --type=db --format=text
abcd123-insecure-do-not-use-this

Install and configure Teleport where you will run the Teleport Database Service:

To install Teleport binaries on your Linux server, the recommended installation method is the cluster install script. This script is served by your Teleport cluster's Proxy Service and automatically selects the correct version, edition, and installation mode to match your cluster.

  1. Remove any existing Teleport binaries on your system:

    sudo rm -f /usr/local/bin/{tsh,teleport,tctl,tbot,fdpass-teleport,teleport-update}
  2. Assign teleport.example.com:443 to your Teleport cluster hostname and port, but not the scheme (https://).

  3. Run your cluster's install script:

    curl "https://teleport.example.com:443/scripts/install.sh" | sudo bash

On the host where you will run the Teleport Database Service, start Teleport with the appropriate configuration.

Note that a single Teleport process can run multiple different services, for example multiple Database Service agents as well as the SSH Service or Application Service. The step below will overwrite an existing configuration file, so if you're running multiple services add --output=stdout to print the config in your terminal, and manually adjust /etc/teleport.yaml.

Generate a configuration file at /etc/teleport.yaml for the Database Service:

sudo teleport db configure create \ -o file \ --token=/tmp/token \ --proxy=teleport.example.com:443 \ --name=roach \ --protocol=cockroachdb \ --uri=roach.example.com:26257 \ --labels=env=dev

Start the Teleport Database Service. The instructions depend on how you installed the Teleport Database Service and whether your system supports systemd:

Configure the Teleport Database Service to start automatically when the host boots up by creating a systemd service for it. On the host where you will run the Teleport Database Service, enable and start Teleport:

sudo systemctl enable teleport
sudo systemctl start teleport

You can check the status of the Teleport Database Service with systemctl status teleport and view its logs with journalctl -fu teleport.

Tip

A single Teleport process can run multiple services, for example multiple Database Service instances as well as other services such as the SSH Service or Application Service.

Step 2/4. Create a Teleport user​

tip

To modify an existing user to provide access to the Database Service, see Database Access Controls

Create a local Teleport user with the built-in access role:

tctl users add \ --roles=access \ --db-users="*" \ --db-names="*" \ alice
FlagDescription
--rolesList of roles to assign to the user. The builtin access role allows them to connect to any database server registered with Teleport.
--db-usersList of database usernames the user will be allowed to use when connecting to the databases. A wildcard allows any user.
--db-namesList of logical databases (aka schemas) the user will be allowed to connect to within a database server. A wildcard allows any database.
warning

Database names are only enforced for PostgreSQL, MongoDB, and Cloud Spanner databases.

For more detailed information about database access controls and how to restrict access see RBAC documentation.

Step 3/4. Configure CockroachDB​

Create a CockroachDB user​

Teleport uses mutual TLS authentication with CockroachDB. Client certificate authentication is available to all CockroachDB users. If you don't have a CockroachDB user for Teleport to connect as, connect to your CockroachDB cluster and create one:

CREATE USER alice WITH PASSWORD NULL;

The WITH PASSWORD NULL clause prevents the user from using password auth and mandates client certificate auth.

Make sure to assign the user proper permissions within the database cluster. Refer to Create User in the CockroachDB documentation for more information.

Set up mutual TLS​

To set up mutual TLS authentication, you need to make sure that:

  • Teleport trusts certificates presented by CockroachDB nodes.
  • CockroachDB nodes trust client certificates signed by both your CockroachDB CA and your Teleport cluster's db_client CA.

CockroachDB nodes need to trust the Teleport db_client CA so that Teleport users can authenticate to your CockroachDB cluster as clients.

The CockroachDB CA needs to be trusted by each CockroachDB node so that nodes can authenticate themselves as clients to other nodes in the CockroachDB cluster. This is because CockroachDB uses mTLS for node-to-node communication.

In this guide, your CockroachDB CA continues to issue the server certificate, node.crt, for each CockroachDB node. An existing CockroachDB cluster already has node.crt issued for each node, so you only need to configure the CockroachDB nodes to trust your Teleport db_client CA. Your nodes keep serving the same certificates, so you don't have to configure other clients to trust a new CA.

If your CockroachDB nodes must serve certificates issued by Teleport's db CA instead, follow Serve Teleport-issued certificates from CockroachDB nodes in place of the rest of this section, then return to Load the new certificates.

  1. On your workstation, export Teleport's db_client CA certificate using tctl:

    tctl auth export --type=db-client > teleport-db-client-ca.crt
  2. Copy teleport-db-client-ca.crt to each CockroachDB node.

  3. On each CockroachDB node, create ca-client.crt in the node's certs directory. The file must contain your CockroachDB CA certificate followed by the Teleport db_client CA certificate. Assign /path/to/teleport-db-client-ca.crt to the location where you copied the file in the previous step:

    CERTS_DIR=/path/to/cockroachdb/certs/dir
    cat "${CERTS_DIR}/ca.crt" /path/to/teleport-db-client-ca.crt > "${CERTS_DIR}/ca-client.crt"

    This command replaces any existing ca-client.crt. If your nodes already use a ca-client.crt file, append the contents of teleport-db-client-ca.crt to the existing file instead.

  4. Configure the Teleport Database Service to trust your CockroachDB CA. Copy your CockroachDB CA certificate (ca.crt in the CockroachDB certs directory) to the host or workstation indicated below.

    Make the CockroachDB CA certificate available on the Teleport Database Service host, assigning /path/to/your/ca.crt to its path. Edit /etc/teleport.yaml to add a tls section to the roach database you configured in Step 1:

    db_service:
      enabled: true
      databases:
      - name: "roach"
        protocol: "cockroachdb"
        uri: "roach.example.com:26257"
        static_labels:
          "env": "dev"
        tls:
          ca_cert_file: "/path/to/your/ca.crt"
    

    Restart the Teleport Database Service to apply the change:

    sudo systemctl restart teleport

    The Teleport Database Service now trusts certificates presented by your CockroachDB nodes.

Load the new certificates​

Each CockroachDB node must load the updated files in its certs directory. Use one of the following methods on every node.

If a node is already running with the --certs-dir flag pointing to /path/to/cockroachdb/certs/dir, send a SIGHUP signal to the cockroach process to reload certificates without restarting the node. You must send SIGHUP as the same user that started the cockroach process:

pkill -SIGHUP -x cockroach

Otherwise, restart the node the way you normally start it (for example, with your service manager), and make sure that the cockroach start command includes --certs-dir=/path/to/cockroachdb/certs/dir in addition to the node's existing flags.

Step 4/4. Connect​

Log in to your Teleport cluster, assigning teleport.example.com to the address of your Teleport Proxy Service (for example, mytenant.teleport.sh for Teleport Enterprise Cloud). Your CockroachDB cluster should appear in the list of available databases:

tsh login --proxy=teleport.example.com --user=alice
tsh db ls

Name Description Allowed Users Labels Connect

----- ----------- ------------- ------- -------

roach [*] env=dev

To retrieve credentials for the database and connect to it, specify the CockroachDB user you created earlier. The Teleport user in this guide is allowed to connect as any database user, so the --db-user flag is required:

tsh db connect --db-user=alice roach

You can optionally specify the database name to use by default when connecting to the database server:

tsh db connect --db-user=alice --db-name=defaultdb roach

tsh db connect starts an interactive SQL session using the cockroach client, or psql if cockroach is not available in your PATH.

tip

To connect to the database using a tool of your choice (for example, a graphical database client), create a local tunnel and configure your client to use it.

tsh proxy db roach --tunnel --db-user=alice

See Database GUI Clients guide for more information on specific tools.

To log out of the database and remove credentials:

tsh db logout roach

Serve Teleport-issued certificates from CockroachDB nodes​

Follow the instructions in this section only if your CockroachDB nodes must serve server certificates issued by Teleport's db CA. Use them in place of the instructions in Set up mutual TLS in Step 3.

In this configuration, Teleport's db CA issues the server certificate, node.crt, and your CockroachDB CA issues the client certificate, client.node.crt, for each CockroachDB node.

warning

This configuration replaces ca.crt and node.crt on each CockroachDB node. Nodes that serve certificates from different CAs do not trust each other, so plan to update and restart all nodes in the same maintenance window. Any other clients that verify your CockroachDB nodes must also trust the Teleport db CA.

Teleport uses mutual TLS authentication with self-hosted databases. These databases must be configured with Teleport's certificate authority to be able to verify client certificates. They also need a certificate/key pair that Teleport can verify.

To issue certificates from your workstation with tctl, your Teleport user must be allowed to impersonate the system role Db.

Include the following allow rule in your Teleport user's role:

allow:
  impersonate:
    users: ["Db"]
    roles: ["Db"]

Complete the following steps once for each CockroachDB node, using a separate output directory on your workstation for each node. Run each step on your workstation unless the step says otherwise.

  1. Generate secrets for a CockroachDB node using tctl. Assign roach.example.com to the hostname of the node and /path/to/local/output/dir to a directory on your workstation for that node's files. If the output directory does not already exist, tctl creates it:

    tctl auth sign \ --format=cockroachdb \ --host=roach.example.com \ --out=/path/to/local/output/dir \ --ttl=2190h
    TTL

    We recommend using a shorter TTL, but keep in mind that you'll need to update the database server certificate before it expires to not lose the ability to connect. Pick the TTL value that best fits your use-case.

    The command produces 4 files:

    • ca.crt: Teleport's db certificate authority.
    • ca-client.crt: Teleport's db_client certificate authority.
    • node.crt: The node's server certificate.
    • node.key: The private key for the node's server certificate.
    note

    You can specify multiple comma-separated addresses, e.g., --host=roach,node-1,192.168.1.1. However, you must include the hostname that Teleport will use to connect to the database.

    Do not rename these files, as this is how CockroachDB expects them to be named. See Node key and certificates for details.

  2. Prepend your CockroachDB CA's certificate to ca-client.crt, assigning /path/to/cockroachdb-ca.crt to the path to your CockroachDB CA certificate:

    OUT_DIR=/path/to/local/output/dir
    cat /path/to/cockroachdb-ca.crt "${OUT_DIR}/ca-client.crt" > ca-client.tmp
    mv ca-client.tmp "${OUT_DIR}/ca-client.crt"

    Run these commands only once per output directory. The CockroachDB CA certificate must be the first certificate in ca-client.crt.

  3. Issue a client certificate for the node using your CockroachDB CA, assigning /path/to/cockroachdb-ca.key to the path to your CockroachDB CA's private key:

    cockroach cert create-client node \ --certs-dir=/path/to/local/output/dir \ --ca-key=/path/to/cockroachdb-ca.key

    This creates client.node.crt and client.node.key in the output directory.

    Details

    Seeing an error message about TLS key mismatch? If you see an error message like tls: private key does not match public key, it likely means you did not prepend your CockroachDB CA cert to ca-client.crt in the previous step.

    cockroach cert create-client expects the first certificate in ca-client.crt (in the --certs-dir specified) to be the certificate that corresponds to --ca-key. Ensure that your CockroachDB CA certificate is the first certificate in ca-client.crt.

  4. Copy the contents of /path/to/local/output/dir to /path/to/cockroachdb/certs/dir, the certs directory on the CockroachDB node.

  5. On the CockroachDB node, give ownership of the certs directory to the user that runs the cockroach process, and make the private keys readable only by that user. CockroachDB does not load private keys that other users can read. Assign cockroach to the name of that user:

    CERTS_DIR=/path/to/cockroachdb/certs/dir
    sudo chown -R cockroach "${CERTS_DIR}"
    sudo chmod 600 "${CERTS_DIR}/node.key" "${CERTS_DIR}/client.node.key"

Repeat these steps for each of your other CockroachDB nodes, changing the --host value and the output directory each time.

After you complete these steps for every node, load the new certificates as described in Load the new certificates, then continue with Step 4/4. Connect.

Troubleshooting​

Unimplemented client encoding error​

You may encounter the unimplemented client encoding: "sqlascii" error when connecting to your CockroachDB database if your psql uses SQL_ASCII encoding.

CockroachDB supports only UTF8 client encoding. To enforce the encoding, set the following environment variable in the shell running tsh db connect:

export PGCLIENTENCODING='utf-8'

If you are connecting to the CockroachDB database with Teleport Connect, add the environment variable to your shell startup scripts and restart the Teleport Connect app.

Unable to cancel a query​

If you use a PostgreSQL cli client like psql, and you try to cancel a query with Ctrl+C, but it doesn't cancel the query, then you need to connect using a tsh local proxy instead. When psql cancels a query, it establishes a new connection without TLS certificates, however Teleport requires TLS certificates not only for authentication, but also to route database connections.

If you enable TLS Routing in Teleport then tsh db connect will automatically start a local proxy for every connection. Alternatively, you can connect via Teleport Connect which also uses a local proxy. Otherwise, you need to start a tsh local proxy manually using tsh proxy db and connect via the local proxy.

If you have already started a long-running query in a psql session that you cannot cancel with Ctrl+C, you can start a new client session to cancel that query manually:

First, find the query's process identifier (PID):

SELECT pid,usename,backend_start,query FROM pg_stat_activity WHERE state = 'active';

Next, gracefully cancel the query using its PID. This will send a SIGINT signal to the postgres backend process for that query:

SELECT pg_cancel_backend(<PID>);

You should always try to gracefully terminate a query first, but if graceful cancellation is taking too long, then you can forcefully terminate the query instead. This will send a SIGTERM signal to the postgres backend process for that query:

SELECT pg_terminate_backend(<PID>);

See the PostgreSQL documentation on admin functions for more information about the pg_cancel_backend and pg_terminate_backend functions.

Next steps​