# Database Access with Self-Hosted PostgreSQL

Teleport can provide secure access to PostgreSQL via the [Teleport Database Service](https://goteleport.com/docs/enroll-resources/database-access.md). This allows for fine-grained access control through the [Teleport RBAC system](https://goteleport.com/docs/enroll-resources/database-access/rbac.md).

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 PostgreSQL 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 PostgreSQL database using mutual TLS. PostgreSQL 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.

**Self-Hosted**

![Enroll PostgreSQL with a Self-Hosted Teleport Cluster](/docs/assets/images/postgresqlselfhosted_selfhosted-4ff2a9574ad1d1863ad008fe25a18e8a.png)

**Teleport Enterprise Cloud**

![Enroll PostgreSQL with a Cloud-Hosted Teleport Cluster](/docs/assets/images/postgresqlselfhosted_cloud-91b00d48bbea473803e8cfbce5c63f27.png)

## Prerequisites

- A running Teleport cluster. If you want to get started with Teleport, [sign up](https://goteleport.com/signup) for a free trial or [set up a demo environment](https://goteleport.com/docs/get-started/deploy-community.md).

- 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:

     **Mac**

     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.

     ---

     **Windows - Powershell**

     ```
     $ curl.exe -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-windows-amd64-bin.zip
     Unzip the archive and move the `tctl` and `tsh` clients to your %PATH%
     NOTE: Do not place the `tctl` and `tsh` clients in the System32 directory, as this can cause issues when using WinSCP.
     Use %SystemRoot% (C:\Windows) or %USERPROFILE% (C:\Users\<username>) instead.
     ```

     **Linux**

     All of the Teleport binaries in Linux installations include the `tctl` and `tsh` clients. For more options (including RPM/DEB packages and downloads for i386/ARM/ARM64) see our [installation page](https://goteleport.com/docs/installation.md).

     ```
     $ curl -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gz
     $ tar -xzf teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gz
     $ cd teleport
     $ sudo ./install
     Teleport binaries have been copied to /usr/local/bin
     ```

* A self-hosted PostgreSQL instance.
* Command-line client `psql` installed and added to your system's `PATH` environment variable.
* A host, e.g., an Amazon EC2 instance, where you will run the Teleport Database Service.
* Optional: a certificate authority that issues certificates for your self-hosted database.
* To check that you can connect to your Teleport cluster, sign in with `tsh login`, then verify that you can run `tctl` commands using your current credentials. For example, run the following command, assigning teleport.example.com to the domain name of the Teleport Proxy Service in your cluster and email\@example.com to your Teleport username:
  ```
  $ tsh login --proxy=teleport.example.com --user=email@example.com
  $ tctl status
  Cluster  teleport.example.com
  Version  19.0.0-dev
  CA pin   sha256:abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678
  ```
  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.

## Step 1/5. Create a Teleport token and user

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
```

### Create a Teleport user

---

TIP

To modify an existing user to provide access to the Database Service, see [Database Access Controls](https://goteleport.com/docs/enroll-resources/database-access/rbac.md)

---

**Teleport Community Edition**

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

```
$ tctl users add \
  --roles=access \
  --db-users="*" \
  --db-names="*" \
  alice
```

**Teleport Enterprise/Enterprise Cloud**

Create a local Teleport user with the built-in `access` and `requester` roles:

```
$ tctl users add \
  --roles=access,requester \
  --db-users="*" \
  --db-names="*" \
  alice
```

| Flag         | Description                                                                                                                              |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `--roles`    | List of roles to assign to the user. The builtin `access` role allows them to connect to any database server registered with Teleport.   |
| `--db-users` | List of database usernames the user will be allowed to use when connecting to the databases. A wildcard allows any user.                 |
| `--db-names` | List 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](https://goteleport.com/docs/enroll-resources/database-access/rbac.md) documentation.

## Step 2/5. Create a certificate/key pair

Teleport uses mutual TLS authentication with self-hosted databases. These databases must be able to verify certificates presented by the Teleport Database Service. Self-hosted databases also need a certificate/key pair that Teleport can verify.

By default, the Teleport Database Service trusts certificates issued by a certificate authority managed by the Teleport Auth Service. You can either:

- Configure your self-hosted database to trust this CA, and instruct Teleport to issue a certificate for the database to present to the Teleport Database Service.
- Configure the Database Service to trust a custom CA.

**Use the Teleport CA**

To configure the database to trust the Teleport CA and issue a certificate for the database, follow these instructions on your workstation:

1. To use `tctl` from your workstation, your Teleport user must be allowed to impersonate the system role `Db` in order to be able to generate the database certificate. Include the following `allow` rule in your Teleport user's role:

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

   ```

2. Export Teleport's certificate authority and generate a certificate/key pair. This example generates a certificate with a 90-day validity period. `db.example.com` is the hostname where the Teleport Database Service can reach the PostgreSQL server.

   ```
   $ tctl auth sign --format=db --host=db.example.com --out=server --ttl=2160h
   ```

   ---

   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 creates 3 files: `server.cas`, `server.crt` and `server.key`.

**Use a custom CA**

If the PostgreSQL database already has a CA that it uses to sign certificates , you only need to export a Teleport CA certificate for the database to authenticate traffic from the Teleport Database Service. You do not need to enable `Db` impersonation privileges.

1. Replace example.teleport.sh:443 with the host and web port of the Teleport Proxy Service in your cluster. Run the following command on your workstation:

   ```
   $ tctl auth export --type=db-client --auth-server=example.teleport.sh:443 > db-client.cas
   ```

   The command creates 1 file, `db-client.cas`.

2. Append the contents of `db-client.cas` to your database's existing CA cert file, which this guide expects to be called `server.cas`.

3. Generate `server.crt` and `server.key` by retrieving a TLS certificate and private key from your existing database CA, signed for your database server. You will use these files later in the guide.

## Step 3/5. Configure your PostgreSQL server

To configure your PostgreSQL server to accept TLS connections, add the following to the PostgreSQL configuration file, `postgresql.conf`, using the paths where you placed the `server.crt`, `server.key`, and `server.cas` files you generated earlier:

```
ssl = on
ssl_cert_file = '/path/to/server.crt'
ssl_key_file = '/path/to/server.key'
ssl_ca_file = '/path/to/server.cas'

```

Restart the PostgreSQL instance to enable this configuration.

See [Secure TCP/IP Connections with SSL](https://www.postgresql.org/docs/current/ssl-tcp.html) in the PostgreSQL documentation for more details.

Configure PostgreSQL to require client certificate authentication from clients connecting over TLS. This can be done by adding the following entries to PostgreSQL's host-based authentication file `pg_hba.conf`:

```
hostssl all             all             ::/0                    cert
hostssl all             all             0.0.0.0/0               cert

```

You should also ensure that you have no higher-priority authentication rules that will match, otherwise PostgreSQL will offer them first, and the certificate-based Teleport login will fail.

See [The pg\_hba.conf File](https://www.postgresql.org/docs/current/auth-pg-hba-conf.html) in the PostgreSQL documentation for more details.

## Step 4/5. Configure and start the Database Service

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

**Linux Server**

To install a Teleport Agent on your Linux server:

The recommended installation method is the cluster install script. It will select the correct version, edition, and installation mode for your cluster.

1. Assign teleport.example.com:443 to your Teleport cluster hostname and port, but not the scheme (https\://).

2. 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`.

Run the following command to generate a configuration file at `/etc/teleport.yaml` for the Database Service. Update example.teleport.sh to use the host and port of the Teleport Proxy Service:

```
$ sudo teleport db configure create \
   -o file \
   --token=/tmp/token \
   --proxy=example.teleport.sh:443 \
   --name=example-postgres \
   --protocol=postgres \
   --uri=postgres.example.com:5432 \
   --labels=env=dev 
```

To configure the Teleport Database Service to trust a custom CA:

1. Export a CA certificate for the custom CA and make it available at `/var/lib/teleport/db.ca` on the Teleport Database Service host.

2. Run a variation of the command above that uses the `--ca-cert-file` flag. This configures the Teleport Database Service to use the CA certificate at `db.ca` to verify traffic from the database:

   ```
   $ sudo teleport db configure create \
      -o file \
      --token=/tmp/token \
      --proxy=example.teleport.sh:443 \
      --name=example-postgres \
      --protocol=postgres \
      --uri=postgres.example.com:5432 \
      --ca-cert-file="/var/lib/teleport/db.ca" \
      --labels=env=dev
   ```

If your database servers use certificates that are signed by a public CA such as ComodoCA or DigiCert, you can use the `trust-system-cert-pool` option without exporting the CA:

```
$ sudo teleport db configure create \
   -o file \
   --token=/tmp/token \
   --proxy=example.teleport.sh:443 \
   --name=example-postgres \
   --protocol=postgres \
   --uri=postgres.example.com:5432 \
   --trust-system-cert-pool \
   --labels=env=dev
```

Configure the Teleport Database Service to start automatically when the host boots up by creating a systemd service for it. The instructions depend on how you installed the Teleport Database Service.

**Package Manager**

On the host where you will run the Teleport Database Service, enable and start Teleport:

```
$ sudo systemctl enable teleport
$ sudo systemctl start teleport
```

**TAR Archive**

On the host where you will run the Teleport Database Service, create a systemd service configuration for Teleport, enable the Teleport service, and start Teleport:

```
$ sudo teleport install systemd -o /etc/systemd/system/teleport.service
$ 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`.

**Kubernetes Cluster**

Teleport provides Helm charts for installing the Teleport Database Service in Kubernetes Clusters.

Configure Helm to fetch Teleport charts from the Teleport Helm repository:

```
$ helm repo add teleport https://charts.releases.teleport.dev
```

Refresh the local Helm cache by fetching the latest charts:

```
$ helm repo update
```

Install a Teleport Agent into your Kubernetes Cluster with the Teleport Database Service configuration.

Create a file called `values.yaml` with the following content. Update example.teleport.sh to use the host and port of the Teleport Proxy Service and JOIN\_TOKEN to the join token you created earlier:

```
roles: db
proxyAddr: example.teleport.sh
# Set to false if using Teleport Community Edition
enterprise: true
authToken: "JOIN_TOKEN"
databases:
  - name: example-postgres
    uri: postgres.example.com:5432
    protocol: postgres
    static_labels:
      env: dev

```

To configure the Teleport Database Service to trust a custom CA:

1. Export a CA certificate for the custom CA and make it available at `db.ca` on your workstation.

2. Create a secret containing the database CA certificate in the same namespace as Teleport using the following command:

   ```
   $ kubectl create secret generic db-ca --from-file=ca.pem=/path/to/db.ca
   ```

3. Add the following to `values.yaml`:

   ```
     roles: db
     proxyAddr: example.teleport.sh
     # Set to false if using Teleport Community Edition
     enterprise: true
     authToken: JOIN_TOKEN
     databases:
       - name: example-postgres
         uri: postgres.example.com:5432
         protocol: postgres
   +     tls:
   +       ca_cert_file: "/etc/teleport-tls-db/db-ca/ca.pem"
         static_labels:
           env: dev
   + extraVolumes:
   +   - name: db-ca
   +     secret:
   +       secretName: db-ca
   + extraVolumeMounts:
   +   - name: db-ca
   +     mountPath: /etc/teleport-tls-db/db-ca
   +     readOnly: true

   ```

4. Install the chart:

   ```
   $ helm install teleport-kube-agent teleport/teleport-kube-agent \
     --create-namespace \
     --namespace teleport-agent \
     --version 19.0.0-dev \
     -f values.yaml
   ```

5. Make sure that the Teleport Agent pod is running. You should see one `teleport-kube-agent` pod with a single ready container:

   ```
   $ kubectl -n teleport-agent get pods
   NAME                    READY   STATUS    RESTARTS   AGE
   teleport-kube-agent-0   1/1     Running   0          32s
   ```

---

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 5/5. Connect

Once the Database Service has joined the cluster, log in to see the available databases:

**Self-Hosted**

```
$ tsh login --proxy=teleport.example.com --user=alice
$ tsh db ls
Name             Description        Labels
---------------- ------------------ --------
example-postgres Example PostgreSQL env=dev
```

**Teleport Enterprise Cloud**

```
$ tsh login --proxy=mytenant.teleport.sh --user=alice
$ tsh db ls
Name             Description        Labels
---------------- ------------------ --------
example-postgres Example PostgreSQL env=dev
```

Note that you will only be able to see databases your role has access to. See [RBAC](https://goteleport.com/docs/enroll-resources/database-access/rbac.md) section for more details.

To retrieve credentials for a database and connect to it:

```
$ tsh db connect --db-user=postgres --db-name=postgres example-postgres
```

---

TIP

You can also [access your PostgreSQL databases using the Web UI.](https://goteleport.com/docs/connect-your-client/teleport-clients/web-ui.md#starting-a-database-session)

---

To log out of the database and remove credentials:

```
Remove credentials for a particular database instance.
$ tsh db logout example-postgres
Remove credentials for all database instances.
$ tsh db logout
```

## Troubleshooting

### 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](https://goteleport.com/docs/zero-trust-access/deploy-a-cluster/tls-routing.md) then `tsh db connect` will automatically start a local proxy for every connection. Alternatively, you can connect via [Teleport Connect](https://goteleport.com/docs/connect-your-client/teleport-clients/teleport-connect.md) 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](https://www.postgresql.org/docs/current/functions-admin.html#functions-admin-signal) for more information about the `pg_cancel_backend` and `pg_terminate_backend` functions.

### SSL SYSCALL error

You may encounter the following error when your local `psql` is not compatible with newer versions of OpenSSL:

```
$ tsh db connect --db-user postgres --db-name postgres postgres
psql: error: connection to server at "localhost" (::1), port 12345 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 12345 failed: SSL SYSCALL error: Undefined error: 0
```

Please upgrade your local `psql` to the latest version.

## Next steps

- Set up [automatic database user provisioning](https://goteleport.com/docs/enroll-resources/database-access/auto-user-provisioning/postgres.md).

* Learn how to [restrict access](https://goteleport.com/docs/enroll-resources/database-access/rbac.md) to certain users and databases.

- View the [High Availability (HA)](https://goteleport.com/docs/enroll-resources/agents/high-availability.md) guide.

* Take a look at the YAML configuration [reference](https://goteleport.com/docs/enroll-resources/database-access/reference/configuration.md).

- See the full CLI [reference](https://goteleport.com/docs/enroll-resources/database-access/reference/cli.md).
