Skip to content

Instantly share code, notes, and snippets.

@mvillafuertem
Forked from sdkks/README.md
Created February 17, 2023 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvillafuertem/66ff38c9ee65a2f1a2088d092d3be6df to your computer and use it in GitHub Desktop.
Save mvillafuertem/66ff38c9ee65a2f1a2088d092d3be6df to your computer and use it in GitHub Desktop.
How to SSH to Kubernetes Pod with SSH ProxyCommand using socat

Requirements

  1. socat
  2. kubectl with proper ~/.kube/config that can connect to your cluster
  3. Working knowledge of kubectl client
  4. OpenSSH client

How does it work?

  1. kubectl does port forwarding to sshd port of your pod. I'm using pm2 process managed to keep my services alive in my workstation container. If you have only sshd, easiest to use is dropbear
  2. ProxyCommand of OpenSSH client uses socat to redirect two way fd - to forwarded port of kubectl
  3. Voila! You are in

See it in action

But WHY?

Starbucks, school, guest network, there are whole bunch of wifi zones with firewalls blocking outgoing access to TCP Port 22. I remember my school's firewall used to scan packet headers to see whether it's http to allow it. If you are in a place that whitelists only HTTP access to non-blacklisted sites, this will do the magic.

This is an autoamtic way of doing it, so you could possibly SSH, SFTP, even use this as JumpHost in your .ssh/config, meaning you could connect to regular port 22 servers like: kubectl proxy => ProxyCommand socat to your pod => regular ssh to any other server

#!/usr/bin/env bash
set -euo pipefail
# Ignore this function and `e home` if you use something like `kubectx` to manage your kubectl contexts and environments
e(){
export KUBECONFIG="${HOME}/.kubechain/${@}"
}
e home
# Replace podname with your own
POD=$(kubectl get pod | grep Running | grep ws- | awk '{print $1}')
# Change forwarding port here and in ssh-config if you need something different
if ! grep 2222 <(netstat -nat) &>/dev/null ; then
kubectl port-forward $POD 2222:2222 &
fi
while ! nc -z 127.0.0.1 2222; do
sleep 0.1
done
socat - tcp:127.0.0.1:2222
# Append this to your ~/.ssh/config
Host <server name you want to use>
Hostname <Assuming you are forwarding to localhost 127.0.0.1>
User <username>
Port <Your forwarded host, use >1024 because less than 1024 requires `sudo` perms 2222>
ProxyCommand ~/.dotfiles/scripts/kubectl-portfwd-ws.sh
IdentitiesOnly yes
IdentityFile ~/.dotfiles/keys/id_rsa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment