# Guide: How to SSH Into WSL2 ## Install WSL2 SSH server 1. Open your wsl ubuntu terminal 2. install open-ssh server ```sh sudo apt update sudo apt install openssh-server ``` 2. Configure the ssh server: `sudo vim /etc/ssh/sshd_config` 1. `PermitRootLogin no` - disallows root login for security 2. `PasswordAuthentication yes` - if you want to allow password login 3. `PubkeyAuthentication yes` - if you want to use key-based authentication (recommended) 4. `Port 2222` - Windows ssh server already uses port 22, so we need to pick a different one. 5. `ListenAddress 0.0.0.0` 3. Activate and start the ssh server: ```sh sudo systemctl start ssh sudo systemctl enable ssh ``` 4. Set [mirrored networking mode](https://learn.microsoft.com/en-us/windows/wsl/networking#mirrored-mode-networking) in `.wslconfig` ``` [wsl2] networkingMode=mirrored ``` 5. Expose port `2222` in the wsl2 firewall in **PRIVILEGED PowerShell terminal**: ```powershell New-NetFirewallHyperVRule -Name "SSH" -DisplayName "SSH" -Direction Inbound -VMCreatorId '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' -Protocol TCP -LocalPorts 2222 ``` 6. Restart wsl by shutting it down (`wsl --shutdown`) and then starting it again (`wsl`) ## Using SSH Keys to login 1. Generate new ssh keys on your remote machine by following [this guide from GitHub](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent) 2. Add your keys to your wsl's user `~/.ssh/authorized_keys` 1. Copy the contents of the public key you created in step 1. 2. Run: `public_key_placeholder >> ~/.ssh/authorized_keys` - make sure to replace `public_key_placeholder` with the actual contents of the public key 3. [Optional] Add ssh config 1. Edit your ssh config file: `vim ~/.ssh/config` 2. Add the following config (make sure to replace placeholder values): ``` Host wsl_hostname_placeholder Hostname wsl_hostname_placeholder Port 2222 User wsl_user_placheolder UseKeychain yes AddKeysToAgent yes IdentityFile ~/.ssh/id_rsa ``` 4. Now you can ssh to your wsl2 instance: `ssh wsl_hostname_placeholder` 1. If you didn't add a ssh config, then you need specify those options: `ssh wsl_user_placheolder@wsl_hostname_placeholder -p 2222`