Skip to content

Instantly share code, notes, and snippets.

@axxapy
Last active January 4, 2024 05:39
Show Gist options
  • Save axxapy/0d8e6d965895988b5bd5bfa91aed287e to your computer and use it in GitHub Desktop.
Save axxapy/0d8e6d965895988b5bd5bfa91aed287e to your computer and use it in GitHub Desktop.
ssh into WSL2 ubuntu

Summary

The problem addressed here is the challenge of accessing a WSL (Windows Subsystem for Linux) instance from an external network. By default, WSL instances are not directly accessible from outside the host machine. This guide presents a solution using Docker and SSH proxying to allow SSH access to the WSL instance from an external machine via the host machine's Windows IP address.

Prerequisites

  • Windows 10/11
  • WSL2
  • Docker Desktop with WSL support enabled
  • Ubuntu (or another Linux distribution)

Concept

As WSL machines are not directly exposed to the external network (although it's possible to run in bridge mode, which I opted not to do), the idea is to utilize Docker to proxy SSH into WSL Linux. Instead of proxying ports (as it's a bit tricky), I've chosen to configure my SSH daemon (sshd) to listen to a socket file and proxy that instead.

Setup

  1. Install OpenSSH (apt install openssh).
  2. Modify /lib/systemd/system/ssh.socket to make it listen to a socket instead of a port: ListenStream=/run/sshd/sshd.sock.
  3. Reload the daemon: systemctl daemon-reload.
  4. Enable ssh.socket (not ssh.service): systemctl enable --now ssh.socket.
  5. Run a Docker container for the proxy:
    docker run -d -v /run/sshd/sshd.sock:/run/sshd/sshd.sock -p 22:22 alpine/socat 'TCP-LISTEN:22,reuseaddr,fork UNIX-CLIENT:/run/sshd/sshd.sock'

Alternatively, you can use the following Docker Compose file:

version: '3.7'
services:
  sshd:
    restart: unless-stopped
    container_name: sshd_proxy
    image: alpine/socat
    ports: 
      - "0.0.0.0:22:22"
    command: TCP-LISTEN:22,reuseaddr,fork UNIX-CLIENT:/run/sshd/sshd.sock
    volumes:
      - /run/sshd/sshd.sock:/run/sshd/sshd.sock

That's it! You can now SSH into your WSL Linux from an external machine using the Windows IP address.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment