# Database Access Getting Started Guide

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

In this guide, you will:

1. Configure your PostgreSQL Amazon Aurora database with IAM authentication.
2. Add the database to your Teleport cluster.
3. Connect to the database via Teleport.

## How it works

**Self-Hosted**

![Enroll RDS with a Self-Hosted Teleport Cluster](/docs/assets/images/rds_selfhosted-7e80da2d81e68764994294704094f2c2.png)

**Teleport Enterprise Cloud**

![Enroll RDS with a Cloud-Hosted Teleport Cluster](/docs/assets/images/rds_cloud-d2a1c03c72cca85029ca149a4dd8e610.png)

The Teleport Database Service uses IAM authentication to communicate with Amazon Aurora. When a user connects to the database via Teleport, the Teleport Database Service obtains AWS credentials and authenticates to AWS as an IAM principal with permissions to access the database.

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

* An AWS account with a PostgreSQL Amazon Aurora database and permissions to create and attach IAM policies.
* A host, e.g., an EC2 instance, where you will run the Teleport Database Service.
* 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  18.7.3
  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. Set up Aurora

In order to allow Teleport connections to an Aurora instance, the instance needs to support IAM authentication.

If you don't have a database provisioned yet, create an instance of an Aurora PostgreSQL in the [RDS control panel](https://console.aws.amazon.com/rds/home). Make sure to choose the "Standard create" database creation method and enable "Password and IAM database authentication" in the Database Authentication dialog.

For existing Aurora instances, the status of IAM authentication is displayed on the Configuration tab and can be enabled by modifying the database instance.

Next, create the following IAM policy and attach it to the AWS user or service account. The Teleport Database Service will need to use the credentials of this AWS user or service account in order to use this policy.

```
{
   "Version": "2012-10-17",
   "Statement": [
      {
         "Effect": "Allow",
         "Action": [
             "rds-db:connect"
         ],
         "Resource": [
             "arn:aws:rds-db:<region>:<account-id>:dbuser:<resource-id>/*"
         ]
      }
   ]
}

```

This policy allows any database account to connect to the Aurora instance specified with resource ID using IAM auth.

---

RESOURCE ID

The database resource ID is shown on the Configuration tab of a particular database instance in the RDS control panel, under "Resource id". For regular RDS database it starts with `db-` prefix. For Aurora, use the database cluster resource ID (`cluster-`), not the individual instance ID.

---

Finally, connect to the database and create a database account with IAM auth support (or update an existing one). Once connected, execute the following SQL statements to create a new database account and allow IAM auth for it:

```
CREATE USER alice;
GRANT rds_iam TO alice;

```

For more information about connecting to the PostgreSQL instance directly, see the AWS [documentation](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ConnectToPostgreSQLInstance.html).

See the [Automatic User Provisioning](https://goteleport.com/docs/enroll-resources/database-access/auto-user-provisioning/postgres.md) guide for how to configure Teleport to create accounts for your PostgreSQL users on demand.

## Step 2/5. Configure 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
```

Alternative methods

For users with a lot of infrastructure in AWS, or who might create or recreate many instances, consider alternative methods for joining new EC2 instances running Teleport:

- [Configure Teleport to Automatically Enroll EC2 instances](https://goteleport.com/docs/enroll-resources/auto-discovery/servers/ec2-discovery.md)
- [Joining Teleport Services via AWS IAM Role](https://goteleport.com/docs/enroll-resources/agents/aws-iam.md)
- [Joining Teleport Services via AWS EC2 Identity Document](https://goteleport.com/docs/enroll-resources/agents/aws-ec2.md)

Install Teleport on the host where you will run the Teleport Database Service:

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

**Self-Hosted**

On the node where you will run the Teleport Database Service, configure Teleport and point it to your Aurora database instance. Make sure to update the database endpoint and region appropriately. The `--proxy` flag must point to the address of your Teleport Proxy Service.

```
$ sudo teleport db configure create \
  --token=/tmp/token \
  --name=aurora \
  --proxy=teleport.example.com:443 \
  --protocol=postgres \
  --uri=postgres-aurora-instance-1.abcdefghijklm.us-west-1.rds.amazonaws.com:5432 \
  --aws-region=us-west-1 \
  --output file:///etc/teleport.yaml
```

**Teleport Enterprise Cloud**

On the node where you will run the Teleport Database Service, configure Teleport and point it to your Aurora database instance. Make sure to update the database endpoint and region appropriately. The `--proxy` flag must point to the address of your Teleport Cloud tenant.

```
$ sudo teleport db configure create \
  --token=/tmp/token \
  --name=aurora \
  --proxy=mytenant.teleport.sh:443 \
  --protocol=postgres \
  --uri=postgres-aurora-instance-1.abcdefghijklm.us-west-1.rds.amazonaws.com:5432 \
  --aws-region=us-west-1 \
  --output file:///etc/teleport.yaml
```

---

AWS CREDENTIALS

The node that connects to the database should have AWS credentials configured with the policy from [step 1](#step-15-set-up-aurora).

---

## Step 3/5. Start the Database Service

Start the Teleport Database Service in your environment:

Configure the 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 Database Service.

**Package Manager**

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

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

**TAR Archive**

On the host where you will run the 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 Database Service with `systemctl status teleport` and view its logs with `journalctl -fu teleport`.

## Step 4/5. Create a user and role

Create the role that will allow a user to connect to any database using any database account:

```
$ tctl create <<EOF
kind: role
version: v3
metadata:
  name: db
spec:
  allow:
    db_labels:
      '*': '*'
    db_names:
    - '*'
    db_users:
    - '*'
EOF
```

---

TIP

You can also create and edit roles using the Web UI. Go to **Access -> Roles** and click **Create New Role** or pick an existing role to edit.

---

Create the Teleport user assigned the `db` role we've just created:

**Teleport Community Edition**

```
$ tctl users add --roles=access,db alice
```

**Commercial**

```
$ tctl users add --roles=access,requester,db alice
```

## Step 5/5. Connect

Now that Aurora is configured with IAM authentication, Teleport is running, and the local user is created, we're ready to connect to the database.

Log in to Teleport with the user we've just created.

**Self-Hosted**

```
$ tsh login --proxy=teleport.example.com --user=alice
```

**Teleport Enterprise Cloud**

```
$ tsh login --proxy=mytenant.teleport.sh --user=alice
```

Now we can inspect available databases:

```
$ tsh db ls
```

Finally, connect to the database:

```
$ tsh db connect --db-user=alice --db-name postgres aurora
```

### Auditing

You can view database session activity in the audit log. After a session is uploaded, you can play back the audit data with the `tsh play` command.

Database session ID will be in a UUID format (ex: `307b49d6-56c7-4d20-8cf0-5bc5348a7101`) See the audit log to get a database session ID with a key of `sid`.

PostgreSQL database recordings are available in interactive format:

```
$ tsh play 307b49d6-56c7-4d20-8cf0-5bc5348a7101
Session started to database "postgres-database" at Mon Jul 20 20:00 UTC

postgres=> SELECT * FROM products;
SUCCESS
(10 rows affected)

postgres=> INSERT INTO products (name, price) VALUES ('Phone', 150.00);
ERROR: permission denied for table products (SQLSTATE 42501)

Session ended at Mon Jul 20 20:30 UTC
```

All database protocols recordings are supported in JSON format (`--format json`):

```
$ tsh play --format json 307b49d6-56c7-4d20-8cf0-5bc5348a7101
```

```
{
    "cluster_name": "teleport.example.com",
    "code": "TDB02I",
    "db_name": "example",
    "db_origin": "dynamic",
    "db_protocol": "postgres",
    "db_query": "select * from sample;",
    "db_roles": [
        "access"
    ],
    "db_service": "example",
    "db_type": "rds",
    "db_uri": "databases-1.us-east-1.rds.amazonaws.com:5432",
    "db_user": "alice",
    "ei": 2,
    "event": "db.session.query",
    "sid": "307b49d6-56c7-4d20-8cf0-5bc5348a7101",
    "success": true,
    "time": "2023-10-06T10:58:32.88Z",
    "uid": "a649d925-9dac-44cc-bd04-4387c295580f",
    "user": "alice"
}

```

The audit log is viewable under **Audit** in the left-hand pane via the Web UI for users with permission to the `event` resources. Database sessions are listed on the session recordings page, but only PostgreSQL sessions are playable.

## Troubleshooting

### Certificate error

If your `tsh db connect` error includes the following text, you likely have an RDS or DocumentDB database created before July 28, 2020, which presents an X.509 certificate that is incompatible with Teleport:

```
x509: certificate relies on legacy Common Name field, use SANs instead

```

AWS provides instructions to rotate your [SSL/TLS certificate](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html).

### No credential providers error

If you see the error `NoCredentialProviders: no valid providers in chain` in Database Service logs then Teleport is not detecting the required credentials to connect via AWS IAM permissions. Check whether the credentials or security role has been applied in the machine running the Teleport Database Service.

When running on EKS, this error may occur if the Teleport Database Service cannot access IMDSv2 when the PUT requests hop limit on the worker node instance is set to 1. You can use the following commands to check the hop limit:

```
$ aws ec2 describe-instances --instance-ids <node-instance-id> | grep HttpPutResponseHopLimit
                        "HttpPutResponseHopLimit": 1,
```

See [IMDSv2 support for EKS](https://aws.amazon.com/about-aws/whats-new/2020/08/amazon-eks-supports-ec2-instance-metadata-service-v2/) and [EKS best practices](https://aws.github.io/aws-eks-best-practices/security/docs/iam/#when-your-application-needs-access-to-imds-use-imdsv2-and-increase-the-hop-limit-on-ec2-instances-to-2) for more details.

### Timeout errors

The Teleport Database Service requires connectivity to your database endpoints.

Check that firewall rules (e.g., AWS security groups) allow connectivity between the Teleport Database Service and the database endpoint.

- Inbound firewall rules for the database must allow connections from the Teleport Database Service.
- Outbound firewall rules for the Teleport Database Service must allow connections to the database endpoint.

---

TIP

On the same host as the Teleport Database Service, try running `nc` to check if it can reach the database port.

- Database host: database-host
- Database port: database-port

```
$ nc -zv database-host database-port
Connection to postgres-instance-1.sadas.us-east-1.rds.amazonaws.com (172.31.24.172) 5432 port [tcp/postgresql] succeeded!
```

---

Debugging connection timeout errors in AWS

For deployments in AWS, it may be helpful to use [AWS Reachability Analyzer](https://docs.aws.amazon.com/vpc/latest/reachability/what-is-reachability-analyzer.html) to analyze the network path between the Teleport Database Service and the database.

1. Identify the Elastic Network Interface (ENI) associated with the Teleport Database Service host. This can be found in the [EC2 console](https://console.aws.amazon.com/ec2/home?NIC).

2. Identify the private IP address of the database.

3. Create and analyze a network path:

   - Set the path source to the ENI associated with the Teleport Database Service host.
   - Set the path destination to the database IP.

4. Check the analysis results to identify reachability issues.

If your database is registered dynamically or via auto-discovery, repeat the above connectivity test for *every*\* Teleport Database Service instance that proxies this database. To list all Teleport Database Service instances associated with a given database, run the `tctl get db_server/<db_name>` command. For example:

```
$ tctl get db_server/postgres-instance-1 --format json | jq '.[] | {hostname: .spec.hostname, host_id: .spec.host_id, version: .spec.version, target_health: .status.target_health}'
{
  "hostname": "ip-10-0-0-111.ca-central-1.compute.internal",
  "host_id": "e5e670ac-a7b8-44ef-b373-6296d87f50e8",
  "version": "18.3.0",
  "target_health": {
    "status": "unhealthy",
    ...
  }
}
{
  "hostname": "ip-10-0-0-222.ca-central-1.compute.internal",
  ...
}

```

If any of the Database Service instances listed here **should not** proxy the database, (for example, a Database Service instance in a different VPC or AWS region without connectivity), locate and update their configurations so they only receive or discover databases they can reach. In most cases, you can achieve this by refining your tag filters, such as adding the `vpc-id` label.

### Not authorized to perform `sts:AssumeRole`

The Database Service assumes an IAM role in one of following situations:

- A Teleport user specifies an IAM role as the database user they wish to use when accessing AWS services that require IAM roles as database users. Databases that support using an IAM role as a database user include: DynamoDB, Keyspaces, Opensearch, Redshift, and Redshift Serverless.
- The `assume_role_arn` field is specified for the database resources or dynamic resource matchers.

What if both situations apply? (role chaining)

When both of the above conditions are true for a database connection, the Database Service performs a role chaining by assuming the IAM role specified in `assume_role_arn` first, then using that IAM role to assume the IAM role for the database user.

You may encounter the following error if the trust relationship is not configured properly between the IAM roles:

```
AccessDenied: User: arn:aws:sts::111111111111:assumed-role/teleport-db-service-role/i-* is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::111111111111:role/db-user-role

```

how to properly configure the trust relationship?

To allow IAM Role `teleport-db-service-role` to assume IAM Role `db-user-role`, the following is generally required:

**1. Configure Trust Relationships on db-user-role**

`teleport-db-service-role` or its AWS account should be set as `Principal` in `db-user-role`'s trust policy.

**Role as principal**

Assign aws-account-id to your AWS account ID:

```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::aws-account-id:role/teleport-db-service-role"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

```

**Account as principal**

Assign aws-account-id to your AWS account ID:

```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::aws-account-id:root"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

```

**Cross-account with external-id**

Assign external-aws-account-id to an external AWS account ID:

```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::external-aws-account-id:role/teleport-db-service-role"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "sts:ExternalId": "example-external-id"
        }
      }
    }
  ]
}

```

**2. Configure Permissions Policies on teleport-db-service-role**

`teleport-db-service-role` requires `sts:AssumeRole` permissions, for example:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "sts:AssumeRole",
            "Effect": "Allow",
            "Resource": "arn:aws:iam::aws-account-id:role/db-user-role"
        }
    ]
}

```

Note that this policy can be omitted when `teleport-db-service-role` and `db-user-role` are in the same AWS account and `teleport-db-service-role`'s full ARN is configured as Principal in `db-user-role`'s trust policy.

**3. Configure Permissions Boundary on teleport-db-service-role**

If `teleport-db-service-role` does not have an attached [Permissions boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) then you can skip this step. Otherwise, the boundary policy attached to `teleport-db-service-role` must include `sts:AssumeRole` permissions, for example:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "sts:AssumeRole",
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

```

You can test the trust relationship by running this AWS CLI command as `teleport-db-service-role`:

```
$ aws sts assume-role --role-arn arn:aws:iam::111111111111:role/db-user-role --role-session-name test-trust-relationship
```

Learn more on [how to use trust policies with IAM roles](https://aws.amazon.com/blogs/security/how-to-use-trust-policies-with-iam-roles/).

## Next Steps

For the next steps, dive deeper into the topics relevant to your Database Access use-case, for example:

- Check out configuration [guides](https://goteleport.com/docs/enroll-resources/database-access/guides.md).
- Learn how to configure [GUI clients](https://goteleport.com/docs/connect-your-client/third-party/gui-clients.md).
- Learn about database access [role-based access control](https://goteleport.com/docs/enroll-resources/database-access/rbac.md).
- See [frequently asked questions](https://goteleport.com/docs/enroll-resources/database-access/faq.md).
