# SSH Access to VPS

Complete guide to connecting to your VPS instances via SSH (Secure Shell).

## What is SSH?

SSH (Secure Shell) is a secure protocol for connecting to remote servers. It provides:

- **Encrypted** connections
- **Secure** authentication
- **Remote** command execution
- **File** transfer capabilities

## Prerequisites

Before connecting:

1. ✅ VPS instance is running
2. ✅ SSH key is added to the instance
3. ✅ Firewall allows port 22
4. ✅ You have the public IP address

## SSH Keys vs Passwords

### SSH Keys (Recommended)

**Advantages**:
- More secure than passwords
- Cannot be brute-forced
- Convenient (no typing)
- Can be revoked easily

### Passwords

**Disadvantages**:
- Less secure
- Can be brute-forced
- Easy to forget
- Harder to manage

**We strongly recommend SSH keys!**

### Choosing at Create Time

When you create a VPS you pick one authentication method:

- **SSH key** (recommended) — passwordless, key-based login
- **Root password** — a password of at least 12 characters

Windows Server instances always use a password (access is over RDP). Whichever you choose, you can further harden authentication from inside the OS once connected — see [SSH Security](#ssh-security).

## Generating SSH Keys

### On Linux/Mac

```bash
# Generate ED25519 key (recommended)
ssh-keygen -t ed25519 -C "your_email@example.com"

# Or RSA key (if ED25519 not supported)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# Follow prompts:
# - Save location: Press Enter for default (~/.ssh/id_ed25519)
# - Passphrase: Optional but recommended for extra security
```

**View your public key**:
```bash
cat ~/.ssh/id_ed25519.pub
```

### On Windows

**Using PowerShell**:
```powershell
# Generate key
ssh-keygen -t ed25519 -C "your_email@example.com"

# View public key
type $env:USERPROFILE\.ssh\id_ed25519.pub
```

**Using PuTTYgen**:
1. Download PuTTYgen from [putty.org](https://www.putty.org/)
2. Click **Generate**
3. Move mouse for randomness
4. Add passphrase (optional)
5. Save private key
6. Copy public key text

### Key Components

**Private Key** (`id_ed25519`):
- Keep secret!
- Never share
- Never commit to git
- Store securely

**Public Key** (`id_ed25519.pub`):
- Safe to share
- Add to servers
- Add to DanubeData dashboard

## Adding SSH Keys to DanubeData

### Method 1: During VPS Creation

1. Create VPS instance
2. In SSH Keys section, click **Add SSH Key**
3. Paste your public key
4. Name it (e.g., "My Laptop")
5. Complete VPS creation

### Method 2: Add to Existing Instance

1. Go to **Profile** > **SSH Keys**
2. Click **Add SSH Key**
3. Paste public key
4. Name it
5. Click **Add**
6. Attach to instances as needed

### Public Key Format

Your public key should look like:

```
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJqfBqGqv9Q... your_email@example.com
```

Or for RSA:

```
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDZk8... your_email@example.com
```

When you add a key, DanubeData validates the format and flags duplicates, so you won't accidentally add the same key twice.

## Connecting via SSH

### Basic Connection

```bash
ssh root@YOUR_VPS_IP
```

**First Connection**:
- You'll see host fingerprint
- Type `yes` to confirm
- Connection established!

### With Custom Key

```bash
ssh -i ~/.ssh/my_custom_key root@YOUR_VPS_IP
```

### With Custom Port

```bash
ssh -p 2222 root@YOUR_VPS_IP
```

### With Username

```bash
ssh username@YOUR_VPS_IP
```

## SSH Config File

Simplify connections with SSH config:

### Create Config

```bash
nano ~/.ssh/config
```

### Add Hosts

```
# Production Server
Host prod-web
    HostName 192.0.2.10
    User root
    IdentityFile ~/.ssh/id_ed25519
    Port 22

# Staging Server
Host staging
    HostName 192.0.2.20
    User deploy
    IdentityFile ~/.ssh/id_rsa
    
# Development Server
Host dev
    HostName 192.0.2.30
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519
```

### Connect Using Alias

```bash
# Instead of: ssh root@192.0.2.10
ssh prod-web

# Instead of: ssh deploy@192.0.2.20
ssh staging
```

**Much easier!**

## SSH on Windows

### Option 1: PowerShell (Windows 10+)

SSH is built into Windows 10/11:

```powershell
ssh root@YOUR_VPS_IP
```

### Option 2: PuTTY

1. Download [PuTTY](https://www.putty.org/)
2. Open PuTTY
3. Enter hostname/IP
4. Port: 22
5. Connection type: SSH
6. Click **Open**

**Using SSH Key with PuTTY**:
1. Convert key using PuTTYgen (Load private key → Save as .ppk)
2. In PuTTY: Connection → SSH → Auth → Browse for private key
3. Connect

### Option 3: Windows Subsystem for Linux (WSL)

```bash
# Install WSL
wsl --install

# Use Linux SSH
ssh root@YOUR_VPS_IP
```

## SSH Agent

SSH Agent stores your keys in memory:

### Start SSH Agent

```bash
# Start agent
eval "$(ssh-agent -s)"

# Add key
ssh-add ~/.ssh/id_ed25519

# List keys
ssh-add -l

# Remove keys
ssh-add -D
```

### Agent Forwarding

Use your local keys on remote server:

```bash
ssh -A root@YOUR_VPS_IP
```

Or in `~/.ssh/config`:
```
Host prod-web
    ForwardAgent yes
```

**Warning**: Only use on trusted servers!

## File Transfer with SSH

### SCP (Secure Copy)

**Upload file**:
```bash
scp local-file.txt root@YOUR_VPS_IP:/path/to/destination/
```

**Download file**:
```bash
scp root@YOUR_VPS_IP:/path/to/file.txt ./local-directory/
```

**Copy directory**:
```bash
scp -r local-directory/ root@YOUR_VPS_IP:/path/to/destination/
```

### SFTP (SSH File Transfer Protocol)

**Interactive session**:
```bash
sftp root@YOUR_VPS_IP

# SFTP commands:
put local-file.txt          # Upload
get remote-file.txt         # Download
ls                          # List remote files
lls                         # List local files
cd /path                    # Change remote directory
lcd /path                   # Change local directory
quit                        # Exit
```

### Rsync over SSH

Best for syncing directories:

```bash
# Sync local to remote
rsync -avz -e ssh ./local/ root@YOUR_VPS_IP:/remote/

# Sync remote to local
rsync -avz -e ssh root@YOUR_VPS_IP:/remote/ ./local/

# Options:
# -a: archive mode
# -v: verbose
# -z: compress
# -e ssh: use SSH
```

## SSH Tunneling

### Local Port Forwarding

Access remote service on local machine:

```bash
# Forward remote MySQL to local port 3306
ssh -L 3306:localhost:3306 root@YOUR_VPS_IP

# Now connect locally:
mysql -h 127.0.0.1 -P 3306
```

### Remote Port Forwarding

Expose local service to remote server:

```bash
# Forward local service to remote
ssh -R 8080:localhost:3000 root@YOUR_VPS_IP
```

### SOCKS Proxy

Route traffic through SSH:

```bash
ssh -D 8080 root@YOUR_VPS_IP

# Configure browser to use SOCKS proxy: localhost:8080
```

## SSH Security

### Disable Root Login

```bash
# Edit SSH config
sudo nano /etc/ssh/sshd_config

# Change to:
PermitRootLogin no

# Restart SSH
sudo systemctl restart sshd
```

### Disable Password Authentication

```bash
# Edit SSH config
sudo nano /etc/ssh/sshd_config

# Change to:
PasswordAuthentication no
PubkeyAuthentication yes

# Restart SSH
sudo systemctl restart sshd
```

### Change SSH Port

```bash
# Edit SSH config
sudo nano /etc/ssh/sshd_config

# Change port:
Port 2222

# Restart SSH
sudo systemctl restart sshd

# Update firewall:
sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcp
```

### Limit SSH Access

**By IP**:
```bash
# UFW
sudo ufw allow from YOUR_IP to any port 22

# Or in /etc/ssh/sshd_config:
AllowUsers root@YOUR_IP
```

**By user**:
```bash
# /etc/ssh/sshd_config:
AllowUsers john jane
```

### Two-Factor Authentication

Add extra security layer:

```bash
# Install Google Authenticator
sudo apt install libpam-google-authenticator -y

# Configure for user
google-authenticator

# Edit PAM config
sudo nano /etc/pam.d/sshd
# Add: auth required pam_google_authenticator.so

# Edit SSH config
sudo nano /etc/ssh/sshd_config
# Set: ChallengeResponseAuthentication yes

# Restart SSH
sudo systemctl restart sshd
```

## Troubleshooting

### Permission Denied

**Check key is added**:
```bash
ssh-add -l
```

**Add key**:
```bash
ssh-add ~/.ssh/id_ed25519
```

**Verify key on server**:
```bash
cat ~/.ssh/authorized_keys
```

### Connection Timeout

**Check firewall**:
- Verify firewall allows port 22
- Check cloud firewall rules
- Test with: `telnet YOUR_VPS_IP 22`

**Check SSH service**:
```bash
# Use web console
sudo systemctl status sshd
sudo systemctl start sshd
```

### Host Key Verification Failed

Server key changed (reinstall or new server):

```bash
# Remove old key
ssh-keygen -R YOUR_VPS_IP

# Reconnect (will add new key)
ssh root@YOUR_VPS_IP
```

### Too Many Authentication Failures

**Specify key**:
```bash
ssh -o IdentitiesOnly=yes -i ~/.ssh/id_ed25519 root@YOUR_VPS_IP
```

**Or in config**:
```
Host *
    IdentitiesOnly yes
```

### Connection Drops

**Keep alive**:
```bash
# Add to ~/.ssh/config:
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
```

**On server** (`/etc/ssh/sshd_config`):
```
ClientAliveInterval 60
ClientAliveCountMax 3
```

## SSH Best Practices

### Key Management
1. Use ED25519 keys (modern, secure)
2. Use passphrase on private keys
3. One key per device
4. Rotate keys regularly
5. Remove old/unused keys

### Connection Security
1. Disable password authentication
2. Disable root login
3. Use non-standard port
4. Limit access by IP
5. Use 2FA for critical servers

### Daily Usage
1. Use SSH config file
2. Use SSH agent
3. Keep private keys secure
4. Never share private keys
5. Use different keys for different purposes

### Monitoring
1. Review SSH logs: `sudo tail -f /var/log/auth.log`
2. Check failed attempts
3. Use fail2ban
4. Monitor unusual activity

## Advanced SSH Tips

### Jump Hosts (Bastion)

Connect through intermediate server:

```bash
ssh -J bastion@jump-host root@final-server
```

Or in config:
```
Host final-server
    ProxyJump bastion@jump-host
```

### SSH Multiplexing

Share connections:

```
Host *
    ControlMaster auto
    ControlPath ~/.ssh/control-%r@%h:%p
    ControlPersist 10m
```

Benefits:
- Faster subsequent connections
- Less overhead
- Shared authentication

### SSH Escape Sequences

During SSH session:
- `~.` - Disconnect
- `~^Z` - Suspend SSH
- `~#` - List forwarded connections
- `~?` - Help

### Remote Command Execution

Run command without interactive session:

```bash
# Single command
ssh root@YOUR_VPS_IP 'uptime'

# Multiple commands
ssh root@YOUR_VPS_IP 'cd /var/www && ls -la'

# Script execution
ssh root@YOUR_VPS_IP 'bash -s' < local-script.sh
```

## SSH Clients

### Linux/Mac
- **OpenSSH**: Built-in, most common
- **Termius**: Modern GUI client
- **iTerm2** (Mac): Terminal with SSH features

### Windows
- **OpenSSH**: Built into Windows 10+
- **PuTTY**: Popular, free
- **MobaXterm**: Feature-rich
- **Termius**: Modern, cross-platform
- **Windows Terminal**: Modern terminal

### Mobile
- **Termius**: iOS/Android
- **JuiceSSH**: Android
- **Blink Shell**: iOS

## Next Steps

- [VPS Management](https://docs.danubedata.ro/vps-managing)
- [Firewall Configuration](https://docs.danubedata.ro/networking-firewalls)
- [Security Best Practices](https://docs.danubedata.ro/platform-security)
- [Monitoring Setup](https://docs.danubedata.ro/monitoring-overview)

Need help with SSH? Contact support through the dashboard.

