Implementing Keyless Cloud Bastion Access with AWS Session Manager

Traditional SSH bastion hosts (jump boxes) introduce significant operational and security overhead: they require a public IP address, an open inbound TCP port 22 rule on your perimeter security group, continuous OS patching, and painful lifecycle management of static SSH private keys across developers. Even worse, standard SSH sessions lack built-in command-by-command audit trails unless paired with complex third-party session recorders.

AWS Systems Manager (SSM) Session Manager eliminates the public bastion host entirely. By running the outbound-only amazon-ssm-agent inside private EC2 instances and routing traffic through AWS PrivateLink VPC Endpoints, engineers establish interactive shells and encrypted RDS/internal port-forwarding tunnels using short-lived IAM Identity Center (SSO) credentials—with zero inbound security group rules and zero SSH key pairs.

Traditional SSH Bastion Host vs. AWS SSM Session Manager

Comparing a traditional public jump host against an SSM Session Manager architecture highlights why keyless outbound control planes are the modern cloud standard:

Security & Operations DimensionTraditional SSH Bastion HostAWS SSM Session Manager (Keyless)
Inbound Firewall / Security GroupRequires inbound TCP/22 open to corporate CIDRs or 0.0.0.0/0Zero inbound ports required (100% outbound HTTPS TCP/443 control plane)
Public IP & NAT ExposureRequires Elastic IP in a public subnetInstances reside in isolated private subnets with zero public IPs
Credential ManagementStatic .pem / ed25519 SSH key pairs (authorized_keys sprawl)Ephemeral IAM / STS tokens federated via SSO + MFA (zero static keys)
Session Encryption & AuditingSSH transport encryption; no native keystroke/command logsTLS 1.3 + AWS KMS encryption; full session transcripts streamed to S3 & CloudWatch Logs
Granular Access ControlOS-level Linux users (ec2-user, ubuntu)IAM tag-based ABAC policies (aws:ResourceTag/Environment = staging)
Bastion Patching & HA CostDedicated EC2 Auto Scaling Group to patch and pay for 24/7Fully managed serverless control plane ($0.00 additional cost for EC2 sessions)
TEXT
+-----------------------------------------------------------------------------------+
|              KEYLESS PRIVATE SUBNET ACCESS WITH AWS SSM SESSION MANAGER           |
+-----------------------------------------------------------------------------------+
|                                                                                   |
|  [Engineer Workstation]                                                           |
|   - Authenticated via IAM Identity Center (SSO + FIDO2 MFA)                       |
|   - Runs: aws ssm start-session --target i-09a8b7c6d5e4f3a21                      |
|         |                                                                         |
|         | Outbound HTTPS (TCP/443) + AWS KMS Session Encryption                   |
|         v                                                                         |
|  +-----------------------------------------------------------------------------+  |
|  |                  AWS SYSTEMS MANAGER CONTROL PLANE (Regional)               |  |
|  |   - Evaluates IAM ABAC Policies & Condition Keys                            |  |
|  |   - Streams Immutable Session Logs -> [KMS-Encrypted S3 Bucket / CloudWatch]|  |
|  +-----------------------------------------------------------------------------+  |
|         |                                                                         |
|         | AWS PrivateLink (Interface VPC Endpoints - No Internet Gateway Needed)  |
|         v                                                                         |
|  +-----------------------------------------------------------------------------+  |
|  |              PRIVATE VPC SUBNET (Zero Public IPs, Zero Inbound Ports)       |  |
|  |                                                                             |  |
|  |  +-----------------------------------+   +-------------------------------+  |  |
|  |  |  Private EC2 Instance (SSM Agent) |   |  Private RDS PostgreSQL       |  |  |
|  |  |  - Security Group Ingress: NONE   |-->|  - Accessible via SSM Port    |  |  |
|  |  |  - SSH Key Pair: NONE             |   |    Forwarding Tunnel (:5432)  |  |  |
|  |  +-----------------------------------+   +-------------------------------+  |  |
|  +-----------------------------------------------------------------------------+  |
+-----------------------------------------------------------------------------------+

Step 1: Provisioning PrivateLink VPC Endpoints & Security Groups (ssm_vpc.tf)

To connect to EC2 instances inside an air-gapped private subnet (without a NAT Gateway or Internet Gateway), provision three Interface VPC Endpoints (ssm, ssmmessages, and ec2messages) and lock down the EC2 instance Security Group to zero inbound rules:

HCL
terraform {
  required_version = ">= 1.8.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.75"
    }
  }
}

variable "vpc_id" {
  type = string
}

variable "vpc_cidr" {
  type = string
}

variable "private_subnet_ids" {
  type = list(string)
}

variable "aws_region" {
  type    = string
  default = "us-east-1"
}

# 1. Security Group for Private EC2 Workload: ZERO Inbound Rules
resource "aws_security_group" "private_workload_sg" {
  name        = "private-workload-no-inbound-sg"
  description = "Zero inbound rules; outbound HTTPS allowed solely for SSM PrivateLink"
  vpc_id      = var.vpc_id

  egress {
    description = "Allow outbound HTTPS to VPC Interface Endpoints"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = [var.vpc_cidr]
  }
}

# 2. Security Group for SSM Interface VPC Endpoints
resource "aws_security_group" "ssm_endpoints_sg" {
  name        = "ssm-privatelink-endpoints-sg"
  description = "Accept HTTPS traffic from private VPC workloads"
  vpc_id      = var.vpc_id

  ingress {
    description     = "HTTPS from private EC2 instances"
    from_port       = 443
    to_port         = 443
    protocol        = "tcp"
    security_groups = [aws_security_group.private_workload_sg.id]
  }
}

# 3. Three Mandatory Interface VPC Endpoints for Session Manager
locals {
  ssm_services = toset([
    "com.amazonaws.${var.aws_region}.ssm",
    "com.amazonaws.${var.aws_region}.ssmmessages",
    "com.amazonaws.${var.aws_region}.ec2messages",
  ])
}

resource "aws_vpc_endpoint" "ssm_interfaces" {
  for_each            = local.ssm_services
  vpc_id              = var.vpc_id
  service_name        = each.value
  vpc_endpoint_type   = "Interface"
  subnet_ids          = var.private_subnet_ids
  security_group_ids  = [aws_security_group.ssm_endpoints_sg.id]
  private_dns_enabled = true
}

Step 2: Least-Privilege EC2 Instance Profile & KMS Session Encryption (ssm_security.tf)

Attach the AWS-managed AmazonSSMManagedInstanceCore policy to your EC2 instance role, create a dedicated AWS KMS Customer Managed Key (CMK) to encrypt session traffic end-to-end, and configure Session Manager preferences to stream tamper-evident logs to S3 and CloudWatch Logs:

HCL
# 1. Dedicated KMS Key for Session Manager Transit & Log Encryption
resource "aws_kms_key" "ssm_session_key" {
  description             = "Encrypts AWS SSM Session Manager traffic and S3/CloudWatch audit logs"
  deletion_window_in_days = 30
  enable_key_rotation     = true
}

# 2. EC2 Instance IAM Role (Zero SSH Keys Configured on Launch)
resource "aws_iam_role" "ec2_ssm_role" {
  name = "private-ec2-ssm-instance-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "ec2.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy_attachment" "ssm_core" {
  role       = aws_iam_role.ec2_ssm_role.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

resource "aws_iam_role_policy" "ssm_kms_decrypt" {
  name = "AllowSSMSessionKMS"
  role = aws_iam_role.ec2_ssm_role.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["kms:Decrypt", "kms:GenerateDataKey"]
      Resource = aws_kms_key.ssm_session_key.arn
    }]
  })
}

resource "aws_iam_instance_profile" "ec2_ssm_profile" {
  name = "private-ec2-ssm-profile"
  role = aws_iam_role.ec2_ssm_role.name
}

# 3. Encrypted S3 Audit Log Bucket
resource "aws_s3_bucket" "ssm_audit_logs" {
  bucket = "codecrown-ssm-session-audit-logs-prod"
}

resource "aws_s3_bucket_public_access_block" "ssm_audit_logs_block" {
  bucket                  = aws_s3_bucket.ssm_audit_logs.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# 4. Enforce Account-Wide Session Encryption & Logging via SSM Document
resource "aws_ssm_document" "session_manager_prefs" {
  name            = "SSM-SessionManagerRunShell"
  document_type   = "Session"
  document_format = "JSON"

  content = jsonencode({
    schemaVersion = "1.0"
    description   = "Enforce KMS encryption, idle timeout, and S3 audit logging for all SSM sessions"
    sessionType   = "Standard_Stream"
    inputs = {
      s3BucketName                = aws_s3_bucket.ssm_audit_logs.id
      s3KeyPrefix                 = "sessions/"
      s3EncryptionEnabled         = true
      kmsKeyId                    = aws_kms_key.ssm_session_key.arn
      idleSessionTimeout          = "15"
      maxSessionDuration          = "60"
      runAsEnabled                = true
      runAsDefaultUser            = "ssm-user"
    }
  })
}

Step 3: Enforcing Tag-Based ABAC IAM Policies for Engineers

Never grant ssm:StartSession on Resource: "*". Use Attribute-Based Access Control (ABAC) conditions so engineers can only open sessions to instances matching their team and environment tags, and require them to terminate their own sessions:

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowScopedSSMSessionStart",
      "Effect": "Allow",
      "Action": [
        "ssm:StartSession"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:123456789012:instance/*"
      ],
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/Environment": "staging",
          "aws:ResourceTag/Domain": "${aws:PrincipalTag/Domain}"
        },
        "BoolIfExists": {
          "aws:MultiFactorAuthPresent": "true"
        }
      }
    },
    {
      "Sid": "AllowApprovedSessionDocuments",
      "Effect": "Allow",
      "Action": [
        "ssm:StartSession"
      ],
      "Resource": [
        "arn:aws:ssm:us-east-1::document/SSM-SessionManagerRunShell",
        "arn:aws:ssm:us-east-1::document/AWS-StartPortForwardingSessionToRemoteHost"
      ]
    },
    {
      "Sid": "AllowTerminateOwnSessionOnly",
      "Effect": "Allow",
      "Action": [
        "ssm:TerminateSession",
        "ssm:ResumeSession"
      ],
      "Resource": [
        "arn:aws:ssm:us-east-1:123456789012:session/${aws:PrincipalTag/Email}-*"
      ]
    }
  ]
}

Step 4: Connecting & Port-Forwarding Without SSH Keys

Once the AWS CLI and session-manager-plugin are installed on the engineer's workstation, connect to private EC2 instances or forward local ports to private RDS databases without opening a single firewall port:

Bash
# 1. Start an interactive shell session on a private EC2 instance (no SSH key or public IP)
aws ssm start-session \
  --target i-09a8b7c6d5e4f3a21 \
  --region us-east-1

# 2. Encrypted Port Forwarding to a Private RDS PostgreSQL Database via the EC2 pivot
aws ssm start-session \
  --target i-09a8b7c6d5e4f3a21 \
  --document-name AWS-StartPortForwardingSessionToRemoteHost \
  --parameters '{"host":["payments-db.cluster-xyz.us-east-1.rds.amazonaws.com"],"portNumber":["5432"],"localPortNumber":["15432"]}'

# 3. Connect your local psql client to localhost:15432 over the encrypted SSM tunnel
psql -h 127.0.0.1 -p 15432 -U db_auditor -d payments

Common Mistakes

  • Leaving key_name populated on aws_instance or Launch Templates: Always omit key_name when provisioning new EC2 instances so no .pem private key is ever generated or injected into ~/.ssh/authorized_keys.
  • Running ssm-user with unrestricted passwordless sudo: By default, SSM Agent grants ssm-user passwordless sudo on Linux. For production hosts, configure runAsEnabled = true mapped to an unprivileged OS user (app-auditor) and restrict /etc/sudoers.d/ssm-agent-users via golden AMI builds.
  • Forgetting private_dns_enabled = true on SSM VPC Endpoints: Without Private DNS enabled on the three Interface VPC Endpoints, amazon-ssm-agent resolves ssm.us-east-1.amazonaws.com to public AWS IP addresses and fails to connect from air-gapped private subnets.

Summary

Replacing legacy SSH jump hosts with AWS Systems Manager Session Manager eliminates public bastion attack surfaces, inbound port 22 rules, and static SSH key sprawl. By routing agent traffic over PrivateLink VPC Endpoints, encrypting streams with AWS KMS, scoping access via tag-based IAM ABAC conditions, and archiving full session transcripts to S3, engineering teams achieve zero-trust private instance access with complete auditability.