# Database Access with MongoDB Atlas

Teleport can provide secure access to MongoDB Atlas 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 MongoDB Atlas database with either mutual TLS or AWS IAM authentication.
2. Add the database to your Teleport cluster.
3. Connect to the database via Teleport.

## How it works

The Teleport Database Service communicates with MongoDB Atlas using mutual TLS or AWS IAM:

- **Mutual TLS:** You configure MongoDB Atlas to trust the Teleport certificate authority for database clients, and Teleport to trust the Let's Encrypt CA, which signs certificates for MongoDB Atlas. When a user connects to MongoDB Atlas via Teleport, the Teleport Database Service authenticates using a certificate and forwards user traffic to MongoDB Atlas.
- **AWS IAM:** You configure MongoDB users to use "MONGODB-AWS" authentication mechanism, and Teleport to trust Let's Encrypt CA, which signs certificates for MongoDB Atlas. When a user connects to MongoDB Atlas via Teleport, the Teleport Database Service assumes the associated IAM role for authentication and forwards user traffic to MongoDB Atlas.

**Self-Hosted**

![Enroll MongoDB with a self-hosted Teleport cluster](/docs/assets/images/mongodbatlas_selfhosted-1d01316bf6d5ae59e5fdc28747e4cae7.png)

**Teleport Enterprise Cloud**

![Enroll MongoDB with a cloud-hosted Teleport cluster](/docs/assets/images/mongodbatlas_cloud-350aa9bc7b8dc7ceec825b370d002505.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
     ```

* [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) cluster.
* A host, e.g., an Amazon 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/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 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
   ```

Next, start the Database Service.

**Teleport CLI**

On the node where you will run the Database Service, start Teleport, pointing the `--auth-server` flag at the address of your Teleport Proxy Service:

```
$ sudo teleport db start \
  --token=/tmp/token \
  --auth-server=example.teleport.sh:443 \
  --name=mongodb-atlas \
  --protocol=mongodb \
  --uri=mongodb+srv://cluster0.abcde.mongodb.net \
  --labels=env=dev
```

---

NOTE

The `--auth-server` flag must point to the Teleport cluster's Proxy Service endpoint because the Database Service always connects back to the cluster over a reverse tunnel.

---

**Configuration file**

On the node where you will run the Teleport Database Service, add the following in `/etc/teleport.yaml`:

```
version: v3
teleport:
  auth_token: "/tmp/token"
  proxy_server: example.teleport.sh:443

# disable services that are on by default
ssh_service: { enabled: false }
proxy_service: { enabled: false }
auth_service: { enabled: false }

db_service:
  enabled: true
  databases:
  - name: "mongodb-atlas"
    protocol: "mongodb"
    uri: "mongodb+srv://cluster0.abcde.mongodb.net"
    static_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`.

See the full [YAML reference](https://goteleport.com/docs/enroll-resources/database-access/reference/configuration.md) for details.

See below for details on how to configure the Teleport Database Service.

### Connection endpoint

You will need to provide your Atlas cluster's connection endpoint for the `db_service.databases[*].uri` configuration option or `--uri` CLI flag. You can find this via the Connect dialog on the Database Deployments overview page:

![Connect](/docs/assets/images/atlas-connect-btn@2x-a37f984f5430535ea3ed3dbd26e68138.png)

Go through the "Setup connection security" step and select "Connect with the MongoDB shell" to view the connection string:

![Connection string](/docs/assets/images/atlas-connect@2x-756460a1fef4742e7d47817b346a4359.png)

Use only the scheme and hostname parts of the connection string in the URI:

```
$ --uri=mongodb+srv://cluster0.abcde.mongodb.net
```

## Step 2/4. 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.

If you opt for a stricter selection of database names for your user, which differs from the wildcard approach illustrated in this guide, it is essential to include the `admin` database. This ensures MongoDB clients won't have issues while connecting and executing operations such as retrieving server information, listing databases, and aborting transactions.

## Step 3/4. Configure Atlas

Teleport MongoDB Atlas integration supports two methods of authentication:

- Self-managed X.509: This method relies on certificates for authentication, with MongoDB Atlas trusting the Teleport certificates.
- AWS IAM: The authentication is done using AWS credentials fetched by Teleport.

**Self-managed X.509**

First, obtain Teleport CA certificate by running the following `tctl auth sign` command against your Teleport cluster:

```
$ tctl auth sign --format=mongodb --host=mongo --out=mongo
```

The `--host` and `--ttl` flag value doesn't matter in this case since you'll only use the CA certificate which this command will output to `mongo.cas` file. You can discard the other `mongo.crt` file.

Go to the Security / Advanced configuration section of your Atlas cluster and toggle "Self-managed X.509 Authentication" on:

![X.509](/docs/assets/images/atlas-self-managed-x509@2x-972a2f2d122e883ee9b622394921d87b.png)

Paste the contents of `mongo.cas` file in the Certificate Authority edit box and click Save.

### Create a MongoDB user

On the Security / Database Access page add a new database user with Certificate authentication method:

![Add user](/docs/assets/images/atlas-add-user@2x-3ef4e235b07fde2310bb94196d4e44d7.png)

Make sure to specify the user as `CN=<user>` as shown above since MongoDB treats the entire certificate subject as a username. When connecting to a MongoDB cluster, say, as a user `alice`, Teleport will sign an ephemeral certificate with `CN=alice` subject.

---

NOTE

Case matters so make sure to specify Common Name in the username with capital letters `CN=`.

---

**AWS IAM**

You must provide the Teleport Database Service access to AWS credentials.

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

**Instance Metadata Service**

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](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html).

**Kubernetes IRSA**

Refer to [IAM Roles for Service Accounts (IRSA)](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) to set up an OIDC provider in AWS and configure an AWS IAM role that allows the pod's service account to assume the role.

**Environment Variables**

Teleport's built-in AWS client reads credentials from the following environment variables:

- `AWS_ACCESS_KEY_ID`
- `AWS_SECRET_ACCESS_KEY`
- `AWS_DEFAULT_REGION`

When you start the Database Service, the service reads environment variables from a file at the path `/etc/default/teleport`. Obtain these credentials from your organization. Ensure that `/etc/default/teleport` has the following content, replacing the values of each variable:

```
AWS_ACCESS_KEY_ID=00000000000000000000
AWS_SECRET_ACCESS_KEY=0000000000000000000000000000000000000000
AWS_DEFAULT_REGION=<YOUR_REGION>

```

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](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/) for a detailed description of credential loading behavior.

### Create a MongoDB IAM role

Navigate to the [AWS IAM console](https://console.aws.amazon.com/iam/). In the navigation pane, choose **Roles** and then choose **Create role**. Next, select the "Custom trust policy" type. Edit the trust policy to allow the Teleport Database service IAM role to assume this role so that the Teleport can fetch the necessary credentials to authenticate to MongoDB:

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111111111111:role/teleport-database-access",
                "Service": "ec2.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

```

Your role won’t require any permission, so you can leave it empty on the **Add Permissions** step. Then, choose a name for it and create it. In this guide, we will use the name `teleport-access`.

### Create a MongoDB User

On the Security / Database Access page add a new database user with **AWS IAM** authentication method, and choose "IAM Role" as the **IAM User type**. Then, fill in the AWS ARN field with the ARN of the newly created IAM role. In the **Database User Privileges** section, give the user sufficient privileges to access the desired database data.

![Create AWS IAM database user](/docs/assets/images/atlas-add-aws-iam-user-bb102b38b8746ab75759ebdf9e9cf198.png)

Please note that Teleport does not support authentication using AWS IAM users; it exclusively supports authentication using AWS IAM roles.

## Step 4/4. Connect

Log into your Teleport cluster and see available databases:

**Self-Hosted**

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

**Cloud-Hosted**

```
$ tsh login --proxy=mytenant.teleport.sh --user=alice
$ tsh db ls
Name          Description Labels
------------- ----------- --------
mongodb-atlas             env=dev
```

**Self-managed X.509 authentication**

To retrieve credentials for a database and connect to it:

```
$ tsh db connect --db-user=alice --db-name dev mongodb-atlas
```

**AWS IAM authentication**

To retrieve credentials for a database and connect to it, you must provide the database username in the `role/<role-name>` format:

```
$ tsh db connect --db-user=role/teleport-access --db-name dev mongodb-atlas
```

Alternatively, you provide the full ARN as the database username when connecting to the database instance:

```
$ tsh db connect --db-user=arn:aws:iam::111111111111:role/teleport-access --db-name dev mongodb-atlas
```

Either the `mongosh` or `mongo` command-line clients should be available in `PATH` in order to be able to connect. The Database Service attempts to run `mongosh` first and, if `mongosh` is not in `PATH`, runs `mongo`.

To log out of the database and remove credentials:

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

## Next steps

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

## Further reading

- [Which certificate authority signs MongoDB Atlas cluster TLS certificates?](https://docs.atlas.mongodb.com/reference/faq/security/#which-certificate-authority-signs-mongodb-atlas-cluster-tls-certificates-)
- [Self-managed X.509 authentication](https://docs.atlas.mongodb.com/security-self-managed-x509/)
- [AWS IAM authentication](https://www.mongodb.com/docs/atlas/security/passwordless-authentication/)
