SSH closed by default, opened on demand

For years my production server’s SSH port was open to the whole internet. It was on a non-standard port, which cut the log noise, but that’s not security.

The usual fix is to allow only your office IP, but I don’t have one; my IP address changes with wherever I’m working. I fixed this security gap so the port is now closed by default. A short script opens it for my current IP only while I’m connected.

The examples use AWS but the idea works with any firewall that has an API.

How it works

  • A security group just for SSH, with no rules. Web traffic stays in a different group, so the script can never touch it.
  • A cloud identity that can change only that group. If its keys leak, the worst anyone can do is open SSH and they’d still need your SSH key.
  • Those keys are in aws-vault, encrypted in the system keychain instead of a plain file.
  • A way in that doesn’t use SSH. AWS Systems Manager gives you a shell through AWS’s API, so a broken firewall or SSH config can’t lock you out.

What you’ll need

  • AWS account ID: the 12-digit number in the console’s account menu.
  • Region: where the server runs, such as us-east-1.
  • Instance ID: the server’s ID, starting with i-.
  • Security group ID: of the new SSH group you create in step 2, starting with sg-.
  • Host: the server’s DNS name or IP address.
  • SSH port and user: such as 22 and ec2-user.

Set it up

  1. Set up the way in without SSH, and test it. Give the instance an IAM role with the AmazonSSMManagedInstanceCore policy, install the Session Manager plugin on your laptop, and run aws ssm start-session --target <instance ID> with your usual admin credentials. Don’t go on until you get a shell. It’s the last resort, so we test it first.
  2. Create the SSH security group with no inbound rules, and attach it to the instance. Leave the old SSH rule in place for now.
  3. Create the IAM user with the policy below, filling in your values. Create an access key for it and store it with aws-vault add ssh-admin.
  4. Save the script below as ssh-toggle somewhere on your PATH, fill in the settings at the top, and run chmod +x ssh-toggle.
  5. Connect with ssh-toggle. Once it works, delete the old SSH rule that’s open to everyone.
  6. Verify, with the commands at the end.

The policy

Replace these placeholders:

  • REGION: your region, everywhere it appears.
  • ACCOUNT_ID: your account ID, everywhere it appears.
  • SSH_SG_ID: the SSH security group ID.
  • INSTANCE_ID: the instance ID.

Leave ${aws:username} as it is; AWS fills it in.

{ "Version": "2012-10-17", "Statement": [
  { "Effect": "Allow",
    "Action": ["ec2:AuthorizeSecurityGroupIngress", "ec2:RevokeSecurityGroupIngress"],
    "Resource": "arn:aws:ec2:REGION:ACCOUNT_ID:security-group/SSH_SG_ID" },
  { "Effect": "Allow",
    "Action": ["ec2:DescribeSecurityGroups", "ec2:DescribeInstances"],
    "Resource": "*" },
  { "Effect": "Allow", "Action": "ssm:StartSession", "Resource": [
      "arn:aws:ec2:REGION:ACCOUNT_ID:instance/INSTANCE_ID",
      "arn:aws:ssm:REGION::document/AWS-StartSSHSession",
      "arn:aws:ssm:REGION:ACCOUNT_ID:document/SSM-SessionManagerRunShell" ] },
  { "Effect": "Allow", "Action": ["ssm:TerminateSession", "ssm:ResumeSession"],
    "Resource": "arn:aws:ssm:*:*:session/${aws:username}-*" } ] }

AWS doesn’t let the two describe actions be limited to one resource, so they’re open. They only read.

The script

It only removes rules it added itself, so anything set by hand in the console is left alone. If the laptop dies with the port open, the next connection from anywhere removes the old address.

The firewall decides who can reach the port. The server’s SSH settings still decide who gets in: keys only, no root login, no passwords.

#!/usr/bin/env bash
# ssh-toggle [open|close|status|<ssh args>]
set -euo pipefail

# Settings: fill these in.
PROFILE=ssh-admin          # the aws-vault profile from step 3
SG=sg-XXXXXXXX             # the SSH security group ID
HOST=server.example.com    # the server's DNS name or IP
PORT=22                    # the SSH port
SSH_USER=ec2-user          # the login user
DESC=ssh-toggle            # marks the rules this script adds

# Re-run under aws-vault, so the AWS keys never sit in a plain file.
[ -z "${AWS_VAULT:-}" ] && exec aws-vault exec "$PROFILE" -- "$0" "$@"

# Rules this script added, found by their description.
rules() { aws ec2 describe-security-groups --group-ids "$SG" --output text \
  --query "SecurityGroups[0].IpPermissions[?FromPort==\`$PORT\`].IpRanges[] | [?Description=='$DESC'].CidrIp"; }

# Every rule on the port, whoever added it.
status() {
  local out; out=$(aws ec2 describe-security-groups --group-ids "$SG" --output text \
    --query "SecurityGroups[0].IpPermissions[?FromPort==\`$PORT\`].IpRanges[].[CidrIp,Description]")
  if [ -z "$out" ]; then echo "port $PORT closed (no rules on $SG)"; else echo "$out"; fi
}

close() {
  local found; found="$(rules)"
  if [ -z "$found" ]; then echo "no '$DESC' rules on $SG:$PORT"; status; return; fi
  for c in $found; do
    aws ec2 revoke-security-group-ingress --group-id "$SG" --protocol tcp --port "$PORT" --cidr "$c" >/dev/null
    echo "revoked $c"
  done
  # Read the rules back rather than trust the revoke.
  if [ -n "$(rules)" ]; then echo "ERROR: rule still present" >&2; status; exit 1; fi
  echo "closed $PORT"
}

open() {
  local ip existing c; ip="$(curl -fsS https://checkip.amazonaws.com)/32"; existing="$(rules)"
  # Remove rules for addresses you're no longer at.
  for c in $existing; do
    [ "$c" = "$ip" ] || { aws ec2 revoke-security-group-ingress --group-id "$SG" --protocol tcp --port "$PORT" --cidr "$c" >/dev/null; echo "revoked stale $c"; }
  done
  if ! grep -qx "$ip" <<<"$existing"; then
    aws ec2 authorize-security-group-ingress --group-id "$SG" \
      --ip-permissions "IpProtocol=tcp,FromPort=$PORT,ToPort=$PORT,IpRanges=[{CidrIp=$ip,Description=$DESC}]" >/dev/null
  fi
  echo "opened $PORT for $ip"
}

case "${1:-}" in
  open)   open ;;
  close)  close ;;
  status) status ;;
  *)
    open
    # Close on exit, unless another session to the server is still open.
    trap 'pgrep -f "ssh -p $PORT $SSH_USER@$HOST" >/dev/null || close' EXIT
    ssh -p "$PORT" "$SSH_USER@$HOST" "$@"
    ;;
esac

How to use it

ssh-toggle               # open the port, connect, and close it when you log out
ssh-toggle 'docker ps'   # run one command on the server; arguments go to ssh
ssh-toggle open          # open the port only, for scp or another tool
ssh-toggle close         # close it again
ssh-toggle status        # list every rule on the port

Only the first two close the port by themselves. After open, run close when you’re done.

Verify it

ssh-toggle status                     # "port 22 closed" when you're not connected
nmap -Pn -p 22 server.example.com     # "filtered" from anywhere else
aws-vault exec ssh-admin -- aws ssm start-session --target i-…   # the way in without SSH still works

Run the last command every now and then. A recovery path you haven’t tested isn’t one.