> ## Documentation Index
> Fetch the complete documentation index at: https://docs.formal.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# SSH/AWS SSM

> Connect to SSH and AWS SSM hosts through the Formal Connector or the Formal Endpoint

The Formal Connector supports connecting to upstream resources via both SSH and AWS SSM. The Formal Endpoint can also intercept SSH on the user's machine with [Transparent Mode](#transparent-mode).

## Requirements for SSH

When creating an SSH resource, set the resource hostname to the hostname of the target instance.

Create a Native User with one of these credential types:

* **Password** uses an SSH username and password.
* **SSH Key** uses an SSH username and private key. You can also provide a
  CA-signed SSH certificate.

In Terraform, to configure an SSH key Native User:

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_native_user_v3" "ssh_key" {
  resource_id = formal_resource.ssh.id
  label       = "ssh-key"

  ssh_key {
    username = "ubuntu"
    key {
      environment_variable = "SSH_PRIVATE_KEY"
    }
    certificate {
      environment_variable = "SSH_CERTIFICATE"
    }
  }
}
```

Secrets can be stored in Formal or read from Connector environment variables.
See [Native Users](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md) for
credential setup and
[Select a default Native User](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md#select-a-default-native-user)
for selection examples.

## Requirements for AWS SSM

Formal streamlines user access to instances using the AWS SSM protocol (AWS EC2 and ECS Fargate instances) through the Connector.

* **For AWS EC2 instances**:
  To utilize AWS SSM with EC2 instances, ensure the following:

  * SSM Agent Installation: The AWS Systems Manager Agent (SSM Agent) must be installed and running on the instance. While the SSM Agent comes pre-installed on certain Amazon Machine Images (AMIs), it may need to be manually installed or updated on others. For detailed guidance on verifying installation and performing manual installations, refer to [the SSM Agent documentation](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html).
  * IAM Role Configuration: The EC2 instance must be associated with an IAM Role that includes the `AmazonSSMManagedInstanceCore` policy. This policy grants the necessary permissions to enable AWS Systems Manager service core functionality.

  For a list of AMIs with the SSM Agent pre-installed and additional setup information, visit [the official documentation](https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html).

* **For ECS Fargate instances**:
  For applications running on ECS Fargate, AWS SSM access requires enabling the ECS Exec feature. This feature allows you to interact with your containers in real-time for tasks such as executing commands within a container or obtaining container logs.

  * ECS Exec Enablement: To use AWS SSM with ECS Fargate, the ECS Exec feature must be enabled for your services and standalone tasks. This setup allows secure and interactive access to your Fargate containers.

  For comprehensive steps on activating and using ECS Exec, consult [the ECS Exec documentation.](https://docs.aws.amazon.com/AmazonECS/latest/userguide/ecs-exec.html).

### Permissions

In order to discover and connect to the EC2 and ECS instances, the Formal Connector requires some permissions. You can give those permissions in two ways:

#### Ambient IAM role

Configure an IAM role for the Connector with the necessary permissions. Create
an **AWS IAM** Native User so the Connector uses this ambient identity.

#### IAM Role as a Native User

You can configure an IAM role to be assumed by the Formal Connector when connecting to the EC2 or ECS instances. This is useful if you want to use a specific IAM role for the Formal Connector rather than the default role, e.g. for connecting to resources in a different account.

Create an **AWS IAM Role** Native User and provide the role ARN. The username
can be any descriptive value. See
[Native Users](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md) for setup.

#### Required IAM permissions

The IAM role requires the following permissions:

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
- ssm:StartSession
- ssm:TerminateSession
- ec2:DescribeInstances
- ecs:ExecuteCommand
- ecs:ListTasks
- ecs:DescribeTasks
- ecs:ListTagsForResource
```

When the Connector assumes an IAM role, either for an **AWS IAM Role** Native User or for `--assume-role`, that role needs the permissions above. The Connector's own identity then needs `sts:AssumeRole` on that role, and the role's trust policy must allow the Connector's identity to assume it.

## Connect to the Connector

> [!TIP]
>
> The [Formal Endpoint](https://docs.formal.ai/docs/guides/client-apps/desktop-app.md) helps configure your `~/.ssh/config` file automatically for SSH resources.

Once you have created an SSH resource, you can connect to it by making an SSH connection to the connector using a remote command to tell the connector which resource to connect to.

> [tab] SSH
>
> ```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> ssh -t -p [CONNECTOR_LISTENER_PORT] \
>   'idp:formal:human:john@joinformal.com'@[CONNECTOR_HOSTNAME] \
>   formal connect ssh --instance-name [RESOURCE_NAME]
> ```

> [tab] EC2
>
> ```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> ssh -t -p [CONNECTOR_LISTENER_PORT] \
>   'idp:formal:human:john@joinformal.com'@[CONNECTOR_HOSTNAME] \
>   formal connect ec2 --instance-arn arn:aws:ec2:us-east-1:123456789012:instance/i-01234567890abcdef0
> ```
>
> The connector can optionally assume a role from the command line argument `--assume-role <IAM_ROLE_ARN>` before making the connection.

> [tab] ECS
>
> ```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> ssh -t -p [CONNECTOR_LISTENER_PORT] \
>   'idp:formal:human:john@joinformal.com'@[CONNECTOR_HOSTNAME] \
>   formal connect ecs \
>     --cluster-arn arn:aws:ecs:us-east-1:123456789012:cluster/my-cluster \
>     --task-id 0761dca1661d4776b3fba04fe985cbcf \
>     --container my-container
> ```
>
> Note that for ECS, you can pass a service ARN rather than a task ID and container name, in which case the connector will automatically find the first task in the service's first container.
>
> The connector can optionally assume a role from the command line argument `--assume-role <IAM_ROLE_ARN>` before making the connection.

As with other resources, the Formal user password to the connector is the Formal access token available from the Control Plane. Additionally, with the Formal Endpoint installed, a local private key identity automatically populated at `~/.formal/id_rsa` can be used as well.

## Policy Evaluation

Formal supports the following policy evaluation stages for SSH:

* **Session**: Evaluate and enforce policies at connection time

Session policies can read what the client asked for, such as the remote command. See the [SSH object](https://docs.formal.ai/docs/guides/policies/evaluation.md#ssh-resources) for the available fields.

## Policies

You can apply access restrictions to SSH Resources, similar to any other Resource. For EC2 resources, you can apply restrictions based on the instance ARN and tags. For ECS resources, you can apply restrictions based on the cluster ARN, service ARN, task ID, task tags, and container name.

## Recordings

The Formal Connector records every session and makes recordings available in the [Sessions application](https://docs.formal.ai/docs/guides/observability/sessions.md).

## Applications

### VSCode Remote SSH

The Formal Connector supports the VSCode Remote SSH extension for SSH and SSM remotes. To do so, we recommend adding configuration in the `~/.ssh/config` file, which VSCode will read to render a menu of hosts to connect to.

For hosts that you would like to use VSCode Remote SSH with, we recommend configuring your SSH client to:

* Refrain from requesting a TTY (`RequestTTY no`)
* Use the `formal` command to request a remote host to connect to from the connector (see [Connect to the Connector](#connect-to-the-connector) above)
* For ECS Fargate remotes, use `--shell /bin/bash` to avoid breaking VSCode Remote SSH's setup script.

Additionally,

* For SSH remotes, ensure the `AllowTcpForwarding` directive is set to `yes` in your SSH server configuration.
* For EC2 remotes, set the SSM agent to `exec /bin/bash` at startup in the AWS Session Manager console's Preferences section.

In the VSCode Remote SSH extension, you should also configure

* Remote.SSH: Enable Dynamic Forwarding (enabled)
* Remote.SSH: Use Local Server (enabled)
* Remote.SSH: Enable Remote Command (enabled)
* Remote.SSH: Permit Pty Allocation (disabled)
* Remote.SSH: Use Curl And Wget Configuration Files (enabled)
* Remote.SSH: Use Exec Server (enabled for ECS Fargate remotes, disabled for EC2 remotes)

Note that you'll need to configure an additional IAM permission for the Formal Connector to work with VSCode Remote SSH with SSM remotes. You'll need to allow `ssm:StartSession` on `AWS-StartPortForwardingSession`.

`AWS-StartPortForwardingSession` only connects to a port on the instance or container itself. The Connector therefore refuses a port forward over SSM to any host other than `localhost`, `127.0.0.1` or `::1`, such as `ssh -L 5432:db.internal:5432`.

For ECS Fargate remotes, AWS requires a "runtime ID" of the specific container to start a port forwarding session with. The Connector does not look up this value. When ECS Autodiscovery is enabled for your [AWS Cloud Account](https://docs.formal.ai/docs/guides/integrations/clouds/aws.md), the Formal Endpoint adds `--runtime-id` to the SSH configuration it writes for discovered containers. Otherwise, pass it yourself, e.g. with

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
ssh ... formal connect ecs ... --runtime-id $(aws ecs describe-tasks --cluster [CLUSTER_NAME] --tasks [TASK_ID] | jq .tasks[].containers[].runtimeId)
```

#### Cursor Remote SSH

As a VS Code fork, Cursor's Remote SSH extension works similarly to that of VS Code. However, the way it sets up the remote server binary is a bit different and requires additional configuration against ECS Fargate remotes.

First, create an `.ssh_inputrc` file in the home directory of the remote native user with the following content:

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
set enable-bracketed-paste off
set completion-query-items 0
set page-completions off
```

Then, in your Formal connection string, use `--shell "/bin/bash -c 'exec env INPUTRC=/path/to/.ssh_inputrc /bin/bash'"` to ensure that the `~/.ssh_inputrc` file is used when connecting to the remote host.

### SCP/SFTP

The Formal Connector supports SCP using the SFTP protocol for SSH resources only.

For SSH remotes, note that the `scp` command will not work with the `RemoteCommand` SSH directive, which is used by the Formal Connector to determine which remote host to connect to. Instead, you can include the resource name in the user identity string, such as `idp:formal:human:example@example.com+resource-name` (i.e., the resource name is the last part of the identity string after the `+` character).

To transfer a file, you can format the SCP command as

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
scp -i ~/.formal/id_rsa \
  -o User='idp:formal:human:john@joinformal.com+ssh-demo-resource' \
  /path/to/src \
  demo-connector.formal.connectors.joinformal.com:/path/to/dest
```

or, you can format `~/.ssh/config` as

```ssh-config theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
Host scp-demo-connector
	Port 22
	User idp:formal:human:john@joinformal.com+ssh-demo-resource
	HostName demo-connector.formal.connectors.joinformal.com
	RequestTTY yes
	IdentityFile ~/.formal/id_rsa
```

> [!TIP]
>
> The Formal Endpoint configures `~/.ssh/config` this way automatically.

### Rsync

The Formal Connector supports rsync over SSH for SSH and SSM remotes.

For SSH remotes, `rsync` encounters a similar `RemoteCommand` limitation as `scp`. You will need to configure `~/.ssh/config` similar to the example above, but also set `RequestTTY` to `no` for rsync compatibility.

For SSM remotes, the Formal Connector does not support `rsync` using the normal SSH channel due to [AWS limitations](https://github.com/aws/containers-roadmap/issues/1536). Instead, you can run `rsync` as a daemon on the remote host and then use `rsync://` to connect to it. Note that the rsync daemon needs to run on a port greater than 1000 (e.g., 8873) for permissions reasons. For EC2 remotes, ensure that the receiving directory is writable by the `ssm-user` user and for ECS Fargate remotes, ensure that the receiving directory is writable by the container user. For example, you can configure `/etc/rsyncd.conf` on the remote host as follows:

```ini theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
port = 8873

# EC2
[ec2-upload]
path = /home/ssm-user/upload
uid = ssm-user

# ECS Fargate
[ecs-upload]
path = /root/upload
uid = root
```

Then, port-forward the rsync daemon to your local machine:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
ssh -L 8873:localhost:8873 -i ~/.formal/id_rsa -p [CONNECTOR_LISTENER_PORT] \
  'idp:formal:human:john@joinformal.com'@[CONNECTOR_HOSTNAME] \
  formal connect ec2 --instance-arn arn:aws:ec2:us-east-1:123456789012:instance/i-01234567890abcdef0
```

Then, you can use the following command to copy files to the remote host:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
rsync -r target-dir rsync://localhost:8873/ec2-upload/
```

## Transparent Mode

The Formal Endpoint intercepts SSH in [Transparent Mode](https://docs.formal.ai/docs/guides/client-apps/transparent-mode.md) on macOS and Linux. Users run `ssh`, `scp`, or `sftp` against the real host, with their own keys. By default, the Endpoint connects to that host directly, without a Formal resource or Connector.

Write a [network rule](https://docs.formal.ai/docs/guides/network-rules.md) that matches SSH for the hosts to watch. This rule matches SSH on port 22:

```cel theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
{
  "condition": {
    "pre_tcp": port == 22,
    "pre_tls": port == 22,
    "post_tls": technology == "ssh"
  }
}
```

[Session policies](#policy-evaluation) apply as they do on the Connector. Logs use the Endpoint source in [Logs](https://docs.formal.ai/docs/guides/observability/logs.md). Native Users, SSM, and the `formal connect` commands apply only to the Connector.

Once a rule matches SSH, the Endpoint refuses any connection it cannot proxy. It never passes the connection through unwatched. The client prints the reason for the refusal.

### Forward to the Connector

To send SSH through a resource's Connector instead, set `forward_to_connector`. This rule forwards SSH to the `bastion` resource when clients dial its hostname and port:

```cel theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
{
  "condition": {
    "pre_tcp": port == 22,
    "pre_tls": resource.name == "bastion",
    "post_tls": technology == "ssh"
  },
  "outputs": {
    "forward_to_connector": true
  }
}
```

If clients dial another hostname or port, such as a Kubernetes Service name, match that destination and set `resource_name` to `"bastion"`.

Clients do not need to authenticate, and their username is ignored. The Connector logs in to the host as the resource's Native User.

### Troubleshooting

> [accordion] The key is protected by a passphrase
>
> **Error:** `Formal cannot use SHA256:...: it is protected by a passphrase.`
>
> **Solution:** Load the key into the agent with `ssh-add`, then retry.

> [accordion] The remote host identification has changed
>
> **Error:** `WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!`
>
> **Solution:** The server key no longer matches `known_hosts`. Confirm the new key with the host owner. Then run the `ssh-keygen -R` command from the message.


## Related topics

- [AWS](https://docs.formal.ai/docs/guides/integrations/clouds/aws.md)
- [Terraform Provider](https://docs.formal.ai/docs/changelog/terraform-provider.md)
- [Policy Evaluation](https://docs.formal.ai/docs/guides/policies/evaluation.md)
- [Native Users](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.