Skip to main content
Federating Amazon Redshift Access using Teleport
Federating Amazon Redshift Access using Teleport

Length: 08:11

Database Access with Redshift on AWS

Teleport can provide secure access to Amazon Redshift via the Teleport Database Service. This allows for fine-grained access control through Teleport's RBAC.

In this guide, you will:

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

How it works

The Teleport Database Service uses IAM authentication to communicate with Amazon Redshift. 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.

Teleport Database Access Redshift Self-Hosted

This guide shows how to register a single Amazon Redshift cluster with your Teleport cluster. For a more scalable approach, learn how to set up Database Auto-Discovery to automatically enroll all AWS databases in your infrastructure.

Prerequisites

  • A running Teleport cluster version 16.4.7 or above. If you want to get started with Teleport, sign up for a free trial or set up a demo environment.

  • The tctl admin tool and tsh client tool.

    Visit Installation for instructions on downloading tctl and tsh.

  • AWS account with a Redshift cluster and permissions to create and attach IAM policies.
  • Command-line client psql installed and added to your system's PATH environment variable.
  • 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:
    $ tsh login --proxy=teleport.example.com [email protected]
    $ tctl status
    # Cluster teleport.example.com
    # Version 16.4.7
    # 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/6. 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 2/6. Create a Database Service configuration

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:

Install Teleport on your Linux server:

  1. Assign edition to one of the following, depending on your Teleport edition:

    EditionValue
    Teleport Enterprise Cloudcloud
    Teleport Enterprise (Self-Hosted)enterprise
    Teleport Community Editionoss
  2. Get the version of Teleport to install. If you have automatic agent updates enabled in your cluster, query the latest Teleport version that is compatible with the updater:

    $ TELEPORT_DOMAIN=example.teleport.com
    $ TELEPORT_VERSION="$(curl https://$TELEPORT_DOMAIN/v1/webapi/automaticupgrades/channel/default/version | sed 's/v//')"

    Otherwise, get the version of your Teleport cluster:

    $ TELEPORT_DOMAIN=example.teleport.com
    $ TELEPORT_VERSION="$(curl https://$TELEPORT_DOMAIN/v1/webapi/ping | jq -r '.server_version')"
  3. Install Teleport on your Linux server:

    $ curl https://cdn.teleport.dev/install-v16.4.7.sh | bash -s ${TELEPORT_VERSION} edition

    The installation script detects the package manager on your Linux server and uses it to install Teleport binaries. To customize your installation, learn about the Teleport package repositories in the installation guide.

On the node that is running the Database Service, create a configuration file. Assign CLUSTER_URI to the domain name and port of the cluster:

$ sudo teleport db configure create \
-o file \
--name="redshift-postgres" \
--proxy=teleport.example.com:3080 \
--protocol=postgres \
--token=/tmp/token \
--uri=${CLUSTER_URI?}

The command will generate a Database Service configuration to proxy your AWS Redshift cluster place it at the /etc/teleport.yaml location.

Step 3/6. Create an IAM Role for user access (optional)

Redshift supports two methods of IAM authentication, both of which Teleport also supports.

First is IAM authentication as a database user. In this method, the Teleport Database Service generates a temporary IAM authentication token for a database user that already exists in the Redshift database. If you choose to use this method, you can skip this step as no additional IAM roles are required.

The second method is to authenticate as an IAM role. In this case, the Teleport Database Service assumes an IAM role to authenticate with Redshift. Redshift then maps that IAM role to a database username and creates that database user if it doesn't already exist in the database.

If you choose the second method, create the AWS IAM role to provide user access to the Redshift database. Go to IAM -> Access Management -> Roles, and click "Create Role".

Create Role Step 1

Skip "Add permissions" for now, enter a role name, and press "Create role".

Once the role is created, find the role, and add the following inline policy to the IAM role: Create Role Step 1

Or in JSON format:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "redshift:GetClusterCredentialsWithIAM",
"Resource": "arn:aws:redshift:us-east-1:123456789012:dbname:my-redshift/*"
}
]
}

Replace 123456789012 and my-redshift with your AWS account ID and your Redshift database's cluster ID.

Step 4/6. Configure IAM permissions for the Database Service

The Teleport Database Service needs AWS IAM permissions to provide access to Redshift databases.

Create an IAM role for Teleport

Grant the Database Service access to credentials that it can use to authenticate to AWS.

  • If you are running the Database Service on an EC2 instance, you may use the EC2 Instance Metadata Service method
  • If you are running the Database Service in Kubernetes, you can use IAM Roles for Service Accounts (IRSA)
  • Otherwise, you must use environment variables

Teleport will detect when it is running on an EC2 instance and use the Instance Metadata Service to fetch credentials.

The EC2 instance should be configured to use an EC2 instance profile. For more information, see: Using Instance Profiles.

Have multiple sources of AWS credentials?

Teleport's AWS client loads credentials from different sources in the following order:

  • Environment Variables
  • Shared credentials file
  • Shared configuration file (Teleport always enables shared configuration)
  • EC2 Instance Metadata (credentials only)

While you can provide AWS credentials via a shared credentials file or shared configuration file, you will need to run the Database Service with the AWS_PROFILE environment variable assigned to the name of your profile of choice.

If you have a specific use case that the instructions above do not account for, consult the documentation for the AWS SDK for Go for a detailed description of credential loading behavior.

Grant permissions

Attach the following AWS IAM permissions to the Database Service IAM role:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "RedshiftConnectAsDBUser",
"Effect": "Allow",
"Action": "redshift:GetClusterCredentials",
"Resource": "*"
},
{
"Sid": "RedshiftConnectAsIAMRole",
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": [
"arn:aws:iam::aws-account-id:role/example-iam-role"
]
},
{
"Sid": "RedshiftFetchMetadata",
"Effect": "Allow",
"Action": "redshift:DescribeClusters",
"Resource": "*"
}
]
}
StatementPurpose
RedshiftConnectAsDBUserConnect to a database as an existing database user.
RedshiftConnectAsIAMRoleAssume an IAM role to connect to a database with permissions mapped into the database 1:1 from the role's IAM permissions.
RedshiftFetchMetadataAutomatically import AWS tags as database labels or find missing information such as the database's AWS region.

You can reduce the scope of the RedshiftConnectAsDBUser statement by updating it to only allow specific users, databases, and database groups. The resource ARN you can specify has the following formats:

arn:aws:redshift:{Region}:{AccountID}:dbuser:{ClusterName}/{UserName}
arn:aws:redshift:{Region}:{AccountID}:dbname:{ClusterName}/{DatabaseName}
arn:aws:redshift:{Region}:{AccountID}:dbgroup:{ClusterName}/{DatabaseGroupName}

See Create an IAM role or user with permissions to call GetClusterCredentials for more information about the redshift:GetClusterCredentials permission grant syntax.

You can authenticate as an existing database user or as an IAM role that will be automatically mapped into the database. The corresponding IAM statement is only required for the method(s) you want to use. If an IAM role names the Database Service's identity as a trusted principal, and both identities are in the same AWS account, then the RedshiftConnectAsIAMRole statement can also be omitted.

Databases discovered by the Teleport Discovery Service should be registered with complete metadata, so you can also omit the RedshiftFetchMetadata permissions if all of your AWS databases are being auto-discovered.

Step 5/6. Start the Database Service

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.

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

$ 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.

The Database Service will proxy the Amazon Redshift cluster with the ID you specified earlier. Keep in mind that AWS IAM changes may not propagate immediately and can take a few minutes to come into effect.

Step 6/6. Connect

Once the Database Service has started and joined the cluster, log in to see the registered databases. Replace --proxy with the address of your Teleport Proxy Service.

$ tsh login --proxy=teleport.example.com --user=alice
$ tsh db ls
# Name Description Labels
# ----------- ------------------------------ --------
# my-redshift ...

To retrieve credentials for a database and connect to it:

$ tsh db connect --db-user=alice --db-name=dev my-redshift
Database users must exist

Teleport does not currently use the auto-create option when generating tokens for Redshift databases. Users must exist in the database.

To log out of the database and remove credentials:

$ tsh db logout my-redshift

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.

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 and EKS best practices for more details.

Timeout errors

The Teleport Database Service needs connectivity to your database endpoints. That may require enabling inbound traffic on the database from the Database Service on the same VPC or routing rules from another VPC. Using the nc program you can verify connections to databases:

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

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.

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

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

Maximum policy size exceeded errors

Due to IAM and STS character limits, you may encounter one of the following errors in the Database Service logs when large numbers of databases are registered:

  • LimitExceeded: Maximum policy size of 2048 bytes exceeded for user <iam-user>
  • LimitExceeded: Maximum policy size of 10240 bytes exceeded for role <iam-role>

For reference, a user policy can maintain permissions for approximately 6 Redshift databases, or 20 RDS databases due to the IAM policy character limits. A role policy can maintain permissions for approximately 30 Redshift databases, or 100 RDS databases.

To get around this limit, try using one or a combination of the following methods:

Method 1: Organize IAM roles with "assume_role_arn"

You can reduce the policy size by separating them into multiple IAM roles. Use assume_role_arn to specify different IAM roles for accessing the databases:

You can specify assume_role_arn in the AWS matchers of Discovery Service's configuration:

warning

Discovery Service exposes a configuration parameter - discovery_service.discovery_group - that allows you to group discovered resources into different sets. This parameter is used to prevent Discovery Agents watching different sets of cloud resources from colliding against each other and deleting resources created by another services.

When running multiple Discovery Services, you must ensure that each service is configured with the same discovery_group value if they are watching the same cloud resources or a different value if they are watching different cloud resources.

It is possible to run a mix of configurations in the same Teleport cluster meaning that some Discovery Services can be configured to watch the same cloud resources while others watch different resources. As an example, a 4-agent high availability configuration analyzing data from two different cloud accounts would run with the following configuration.

  • 2 Discovery Services configured with discovery_group: "prod" polling data from Production account.
  • 2 Discovery Services configured with discovery_group: "staging" polling data from Staging account.
discovery_service:
discovery_group: "prod"
enabled: "yes"
aws:
- types: ["rds"]
regions: ["us-west-1", "us-west-2"]
assume_role_arn: "arn:aws:iam::123456789012:role/example-role-rds-env-prod-discovery"
tags:
"env": "prod"

- types: ["redshift", "redshift-serverless"]
regions: ["us-west-2"]
assume_role_arn: "arn:aws:iam::123456789012:role/example-role-redshift-env-dev"
tags:
"env": "dev"

The Discovery Service will use the IAM roles specified in assume_role_arn for discovery, and by default the Database Service will use the same IAM roles for authentication.

However, you can also overwrite the IAM roles for authentication by Database Service if you wish to use different roles:

db_service:
enabled: "yes"
resources:
# Matches us-west-1 env=prod RDS databases from Discovery Service, and
# overwrites assume_role_arn.
- labels:
"env": "prod"
"region": "us-west-1"
aws:
assume_role_arn: "arn:aws:iam::123456789012:role/example-role-rds-env-prod-us-west-1-access"

# Matches us-west-2 env=prod RDS databases from Discovery Service, and
# overwrites assume_role_arn.
- labels:
"env": "prod"
"region": "us-west-2"
aws:
assume_role_arn: "arn:aws:iam::123456789012:role/example-role-rds-env-prod-us-west-2-access"

# Matches env=dev Redshift databases from Discovery Service and inherits
# "arn:aws:iam::123456789012:role/example-role-redshift-env-dev"
- labels:
"env": "dev"
Auto-discovery labels

Teleport generates certain labels derived from the cloud resource attributes during discovery. See Auto-Discovery labels /labels/#auto-discovery) for more details.

Create or print the required IAM policies with the following commands and attach them to the respective IAM roles:

$ teleport db configure aws create-iam --types redshift,redshift-serverless --name teleport-redshift-access
$ teleport db configure aws print-iam --types redshift,redshift-serverless

Refer to the command usage for a complete list of database types supported by the --types option.

The IAM roles specified in assume_role_arn must trust the IAM identity of the host running the Database Service.

The assume_role_arn is not limited to the same AWS account so you can also use this feature for AWS Cross-Account Access.

Method 2: Manually manage your IAM policies

You can manually manage IAM policies for database connections instead of relying on the Database Service to update them.

For example, you can limit the character size by attaching a policy with a wildcard "*" for "Resource":

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "rds-db:connect",
"Resource": "*"
}
]
}

You can safely remove the inline policy created by the Database Service and the IAM permissions for the Database Service to Get/Put/Delete the user or role policy.

Method 3: Separate Database Services

You can deploy the Database Service in a highly available (HA) configuration where databases can be sharded to separate Database Services with different IAM roles.

Method 4: Use IAM roles instead of IAM users

IAM users have a lower character limit compared to IAM roles. If the limit is exceeded for a user policy, it is recommended to use IAM roles for the Database Service instead.

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,starttime,duration,trim(user_name) AS user,trim(query) AS query FROM stv_recents WHERE status = 'Running';

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.

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