Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save anupkrbid/e894af7df2d43a4e253fc252251dd7fe to your computer and use it in GitHub Desktop.
Save anupkrbid/e894af7df2d43a4e253fc252251dd7fe to your computer and use it in GitHub Desktop.

SSH Setup Guide for VirtualBox Ubuntu VMs

This comprehensive guide covers setting up and managing SSH access to Ubuntu virtual machines running in VirtualBox, including detailed explanations of all commands used.

Understanding Linux Commands

Before we dive into the setup, let's understand some fundamental Linux commands we'll be using:

Sudo Command

sudo (Superuser Do) runs commands with administrative privileges:

sudo command_name

When you use sudo, you'll be prompted for your password. This is a security measure to prevent unauthorized system changes.

Package Management Commands

sudo apt update

This command:

  • apt: Advanced Package Tool, Ubuntu's package manager
  • update: Refreshes the list of available packages and their versions
  • Does not install anything, just updates the package database
sudo apt install openssh-server

This command:

  • install: Tells apt to download and install a package
  • openssh-server: The name of the package we want to install

System Control Commands

sudo systemctl status ssh

This command checks the SSH service status:

  • systemctl: The command used to control system services
  • status: Shows whether a service is running, stopped, or has errors
  • ssh: The name of the service we're checking

Firewall Commands

sudo ufw allow ssh

This command:

  • ufw: Uncomplicated Firewall, Ubuntu's default firewall
  • allow: Creates a new rule to allow traffic
  • ssh: Shorthand for port 22, the default SSH port

Network Commands

ip a

This command:

  • Shows all network interfaces and their IP addresses
  • a is short for address
  • Look for inet followed by an IP address like 192.168.1.xxx

SSH Setup Process

On Ubuntu VM (Guest)

  1. First, update the package database:

    sudo apt update

    Understanding the output:

    • "Hit": Repository is up to date
    • "Get": New package lists are being downloaded
    • "Reading package lists": Processing the updates
  2. Install the SSH server:

    sudo apt install openssh-server

    The output will show:

    • Dependencies that will be installed
    • Amount of disk space needed
    • Prompt for confirmation (y/n)
  3. Verify the SSH service:

    sudo systemctl status ssh

    Look for:

    • "active (running)" in green
    • No error messages
    • The process ID (PID)

File Management and Permissions

Understanding the SSH Config File

When we create or edit the SSH config file:

nano ~/.ssh/config

Breaking this down:

  • nano: A text editor, easier for beginners than vim
  • ~: Represents your home directory
  • .ssh: A hidden directory (starts with .)
  • config: The configuration file name

Setting proper permissions:

chmod 600 ~/.ssh/config

Understanding chmod:

  • chmod: Change mode command
  • 600: Permission number where:
    • 6 for owner = read (4) + write (2)
    • 0 for group = no permissions
    • 0 for others = no permissions

Working with the Hosts File

Editing the hosts file:

sudo nano /etc/hosts

Understanding the path:

  • /etc: System configuration directory
  • hosts: File that maps IP addresses to hostnames

SSH Key Management

Generate an SSH key:

ssh-keygen -t ed25519 -C "[email protected]"

Breaking down the command:

  • ssh-keygen: Tool for creating SSH keys
  • -t ed25519: Specifies the key type (Ed25519, a modern, secure algorithm)
  • -C: Adds a comment to identify the key

Copy your key to the VM:

ssh-copy-id username@vm_ip_or_hostname

This command:

  • Copies your public key to the remote server
  • Adds it to authorized_keys file
  • Sets correct permissions automatically

Connection Commands

Basic SSH connection:

ssh username@hostname

Understanding the format:

  • ssh: The SSH client command
  • username: Your account on the remote system
  • @: Separator between username and hostname
  • hostname: Can be IP address, hostname, or alias from config

Using configured shortcuts:

ssh myvm

This works when defined in ~/.ssh/config

Troubleshooting Commands

Check SSH daemon status:

sudo systemctl status ssh

View SSH logs:

sudo journalctl -u ssh

This command:

  • journalctl: System log viewer
  • -u ssh: Filter logs for SSH service only

Remove known host entry:

ssh-keygen -R hostname

Use this when:

  • Host key verification fails
  • Server's SSH key has changed
  • You want to remove old entries

Additional Commands for System Analysis

Check listening ports:

sudo netstat -tuln | grep 22

Breaking down:

  • netstat: Network statistics tool
  • -tuln: Show TCP/UDP listening numeric ports
  • grep 22: Filter for SSH port

Check SSH config syntax:

ssh -T -v myvm

Understanding flags:

  • -T: Disable pseudo-terminal allocation
  • -v: Verbose mode for debugging

These commands form the foundation of managing SSH connections in a Linux environment. Understanding them helps you troubleshoot issues and maintain secure connections to your virtual machines.

Network Configuration Options

Method 1: Bridged Adapter

When using bridged networking, your virtual machine appears as a separate device on your network, just like a physical computer. This method gives your VM its own IP address on your local network.

  1. Configure VirtualBox Network Settings:

    • Go to VM Settings → Network
    • Set "Attached to" as "Bridged Adapter"
    • Select your network interface (e.g., Wireless adapter for WiFi)
  2. Get VM's IP address (run this inside the VM):

    ip a

    Look for an IP address like 192.168.1.xxx or 10.0.x.x in the output.

  3. Connect from host:

    ssh username@vm_ip_address

    For example: ssh [email protected]

Method 2: NAT with Port Forwarding

NAT (Network Address Translation) lets your VM share your host's IP address. Port forwarding tells VirtualBox to redirect SSH connections from your host to your VM.

  1. Configure VirtualBox Network Settings:

    • Go to VM Settings → Network
    • Set "Attached to" as "NAT"
    • Click "Advanced" → "Port Forwarding"
    • Add new rule:
      • Name: SSH Rule
      • Protocol: TCP
      • Host Port: 22
      • Guest Port: 22
  2. Connect from host:

    ssh username@localhost

Simplifying SSH Connections

Understanding and Using the SSH Config File

The SSH config file is a powerful tool that lets you create shortcuts for your SSH connections. Think of it as your SSH address book, where you can store connection details for all your machines.

  1. Create/edit the SSH config file:

    nano ~/.ssh/config
  2. Here's a comprehensive example with different scenarios:

    # Basic VM connection
    Host ubuntu-vm
        HostName 192.168.1.100
        User ubuntu
        Port 22
    
    # NAT VM connection using localhost
    Host nat-vm
        HostName localhost
        User developer
        Port 22
    
    # VM with custom settings
    Host dev-vm
        HostName 192.168.1.101
        User developer
        Port 2222
        IdentityFile ~/.ssh/dev_key
        ForwardX11 yes
    
  3. Set proper permissions (required for security):

    chmod 600 ~/.ssh/config

Now instead of typing ssh [email protected], you can simply use:

ssh ubuntu-vm

The config file supports many options:

  • Host: Your chosen nickname for the connection
  • HostName: The actual IP address or hostname
  • User: Your username on the remote system
  • Port: SSH port (default is 22)
  • IdentityFile: Path to your SSH key
  • ForwardX11: Enable X11 forwarding for GUI applications

Using Custom Hostnames

There are two approaches to using hostnames instead of IP addresses. Let's understand both:

Method 1: Using /etc/hosts

The hosts file maps IP addresses to names system-wide:

  1. Edit the hosts file:

    sudo nano /etc/hosts
  2. Add entries (example):

    # VirtualBox VMs
    192.168.1.100    ubuntu-vm
    192.168.1.101    dev-vm
    

Now you can use these names anywhere, including SSH:

ssh username@ubuntu-vm

Method 2: Combining Hosts File with SSH Config

This approach gives you the best of both worlds:

  1. In /etc/hosts:

    192.168.1.100    ubuntu-vm
    
  2. In ~/.ssh/config:

    Host dev
        HostName ubuntu-vm
        User developer
    
  3. Connect with the short command:

    ssh dev

SSH Key Authentication (Recommended)

Using SSH keys is more secure than passwords:

  1. Generate SSH key pair on host:

    ssh-keygen -t ed25519 -C "[email protected]"
  2. Copy public key to VM:

    ssh-copy-id username@vm_ip_or_hostname

Troubleshooting Common Issues

  1. Connection refused errors:

    • Verify SSH service is running: sudo systemctl status ssh
    • Check firewall settings: sudo ufw status
    • Ensure correct IP/port forwarding
  2. Permission denied errors:

    • Check SSH config file permissions: ls -l ~/.ssh/config
    • Verify username and password
    • Check SSH key permissions: ls -l ~/.ssh/id_*
  3. Host key verification failed:

    • Remove old key: ssh-keygen -R hostname_or_ip
    • Connect again to add new key

First-time Connection

When connecting to a new VM for the first time, you'll see this security prompt:

The authenticity of host '...' can't be established.
... key fingerprint is ...
Are you sure you want to continue connecting (yes/no/[fingerprint])?

This is normal and helps prevent man-in-the-middle attacks. Type 'yes' to add the host to your known_hosts file.

@anupkrbid
Copy link
Author

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