Hummus

Hummus

Detailed Explanation of the SSH Protocol

SSH Overview#

SSH is a Protocol#

  • Secure Shell (SSH) is an encrypted network transmission protocol.
  • SSH establishes a connection between the SSH client and server by creating a secure tunnel over the network.
  • The most common use of SSH is for remote system login, where people typically use SSH to transmit command-line interfaces and execute commands remotely.

OpenSSH Open Source Version#

OpenSSH is the open-source version of the Secure Shell (SSH) tools, which administrators of Linux and other non-Windows systems use to manage remote systems across platforms.

Common SSH Tools#

NameDescriptionSupported PlatformsRecommendation
PuTTY (Free Windows)Free and open-source SSH terminal toolWindows⭐⭐⭐
WinSCPFile transfer tool using SCP protocolWindows⭐⭐⭐⭐⭐
FileZillaMulti-protocol file transfer toolWindows
Linux
MacOS
⭐⭐⭐⭐
MobaXtermFree and open-source SSH terminal toolWindows⭐⭐⭐⭐
TermiusCross-platform SSH terminal toolWindows
Linux
MacOS
Android
IOS
⭐⭐⭐⭐⭐

SSH Protocol Working Principle#

Three Sub-protocols in the SSH Protocol Framework#

  • Transport Layer Protocol SSH-TRANS

    Provides server authentication, integrity, and confidentiality features, built on traditional TCP/IP protocols.

  • Authentication Protocol SSH-USERAUT

    Authenticates the client user to the server, with two authentication methods based on username/password and public key, built on the transport layer protocol SSH-TRANS.

  • Connection Protocol SSH-CONNECT

    Reuses the encrypted tunnel as several logical channels. It is built on the authentication protocol.

image

SSH Workflow#

image

Packet Analysis of Each Stage Using Wireshark#

TCP Three-Way Handshake#

image

The SSH server listens for client connection requests on port 22. After receiving a connection establishment request from the client, it performs a three-way handshake with the client to establish a TCP connection, and all subsequent message exchanges occur over this TCP connection.

Version Negotiation#

image

Both the server and client send their supported version numbers to each other. After receiving the version sent by the other party, both sides compare it with their own version numbers, and the highest version number supported by both parties is the negotiated version number.

Algorithm Negotiation#

image

  • Both the client and server send their lists of supported algorithms to each other;
  • They negotiate each algorithm (key exchange algorithms, encryption algorithms, etc.) in turn. The negotiation process for each algorithm is as follows: take the first algorithm from the client's list, look for the corresponding algorithm in the server's list, and if a matching algorithm is found, the negotiation is successful; otherwise, continue to take the next algorithm from the client's list and match it in the server's list until a match is found. If all algorithms supported by the client fail to match, the algorithm negotiation fails.
  • Once an algorithm is successfully negotiated, continue negotiating other algorithms in the same manner until all algorithms are successfully negotiated; if any algorithm negotiation fails, the algorithm negotiation between the client and server fails, and the server disconnects from the client.

In algorithms, all algorithms that need to be negotiated are included.

NO.DescriptionExplanation
1kex_algorithmsKey Exchange algorithms, including D-H algorithms used to generate session keys
2server_host_key_algorithmsHost Key algorithms used to generate key pairs
3encryption_algorithms_client_to_serverSymmetric encryption algorithms, commonly aes128-cbc,3des-cbc
4mac_algorithms_client_to_serverMac algorithms, mainly used to ensure data integrity
5compression_algorithms_client_to_serverCompression algorithms

Key Exchange#

image

The client generates a temporary key ephemera-public key and sends it to the server [??].

image

The server and client use the Diffie-Hellman algorithm to generate a session key.

In this packet, the server sends the host key, session key, signature, etc., to the client.

image

The client replies with a New Key, and then enters encrypted communication.

image

All subsequent session processes are encrypted, and no plaintext information can be seen from the packet capture.

User Authentication#

  1. The client sends an authentication request packet to the server, with the authentication method being "none".
  2. The server receives the none authentication request and replies with an authentication challenge packet, which contains the list of authentication methods supported by the server that the user needs to complete.
  3. The client selects an authentication method from the list sent by the server and initiates an authentication request to the server, which includes the username, authentication method, and content related to that authentication method:
    • In the password authentication method, the content is the user's password;
    • In the public key authentication method, the content is the public key part of the user's local key pair (public key verification stage) or a digital signature (digital signature verification stage).
  4. The server receives the client's authentication request and verifies the client's authentication information:
    • Password authentication: The server compares the username and password information sent by the client with the username and password stored on the device or remote authentication server to determine whether the authentication is successful or failed.
    • Public key authentication: The server checks the legality of the public key; if it is not legal, the authentication fails; otherwise, the server authenticates the client using the digital signature to determine whether the authentication is successful or failed.
  5. Based on the configuration for that user on the server and the completion of user authentication, the server decides whether the client needs to continue authentication, which can be divided into the following situations:
    • If the authentication method is successful and the user does not need to complete other authentications, the server replies with a successful authentication message, and the authentication process is completed smoothly.
    • If the authentication method is successful but the user still needs to complete other authentications, the server replies with a failed authentication message and continues to issue authentication challenges to the client, carrying the list of authentication methods that the server requires the client to continue completing;
    • If the authentication method fails and the user's authentication attempts have not reached the maximum value, the server continues to send authentication challenges to the client;
    • If the authentication method fails and the user's authentication attempts reach the maximum value, the user authentication fails, and the server disconnects from the client.

Service Request#

The SSH protocol supports various application services. After the user successfully completes authentication, the SSH client sends a service request to the server, requesting the server to provide a specific application.

The service request process is as follows:

  1. The client sends an SSH_MSG_CHANNEL_OPEN message, requesting to establish a session channel with the server;
  2. After receiving the SSH_MSG_CHANNEL_OPEN message, if the server supports that channel type, it replies with an SSH_MSG_CHANNEL_OPEN_CONFIRMATION message, thus establishing the session channel;
  3. After the session channel is established, the client can request to perform shell or subsystem type sessions over the channel, corresponding to SSH and SFTP services.

SSH Protocol Security Mechanisms#

Encrypted Channel#

An encrypted channel refers to the sender encrypting the data using an encryption key before sending it and then sending the data to the recipient; the recipient receives the data and uses a decryption key to obtain the plaintext from the ciphertext.

Encryption and decryption algorithms are divided into two categories:

  • Symmetric key algorithms: The same key and algorithm are used for both data encryption and decryption.
  • Asymmetric key algorithms: Different keys are used for data encryption and decryption, one being the public key and the other being the private key kept secret by the user.

Due to the time-consuming nature of asymmetric key algorithms, they are generally used for digital signatures and identity authentication. Data encryption and decryption on the SSH encrypted channel use symmetric key algorithms, with currently supported algorithms including DES, 3DES, AES, etc. These algorithms can effectively prevent the interception of interactive data, and due to the use of initialization vector protection, they can prevent attacks from cryptanalysis tools like password stream reuse.

Key Exchange Algorithm#

Symmetric key algorithms require that the decryption key and encryption key be identical to successfully decrypt the ciphertext into plaintext. Therefore, to establish an encrypted channel, consistent encryption and decryption keys must first be deployed on both communicating parties. There are various ways to deploy encryption and decryption keys: manual configuration and distribution by third-party organizations. Manual configuration has poor scalability and is only suitable for small local networks; using third-party organizations to distribute keys requires an additional third-party server, and keys transmitted over the network are easily intercepted.

The SSH protocol uses a secure method to deploy keys between the communicating parties: the key exchange algorithm. The key exchange algorithm allows the dynamic generation of keys between the communicating parties, which can only be obtained by the two parties communicating, and no third party can intercept them, thus ensuring the security of the keys used for encryption and decryption from the source, effectively solving the key distribution problem.

Basic Principles of Key Exchange Algorithms#

  1. The client randomly selects a private key Xc(1<Xc<p1)X_c(1<X_c<p-1), calculates Yc=gXcmodpY_c=g^{X_c} \mod p, and sends the calculated YcY_c to the server. Here, pp is a large prime number, and gg is a primitive root of pp. pp and gg are a pair of parameters shared by both parties, and the protocol allows both parties to negotiate to obtain the same pp and gg parameters.
  2. The server also randomly generates a private key Xs(1<Xs<p1)X_s(1<X_s<p-1), calculates Ys=gXsmodpY_s=g^{X_s} \mod p, and sends the calculated YsY_s to the client.
  3. The server receives the YcY_c sent by the client and calculates the key using the following formula: K=YcXsmodpK={Y_c}^{X_s} \mod p.
  4. The client receives the YsY_s sent by the server and similarly calculates the key using the following formula: K=YsXcmodpK={Y_s}^{X_c} \mod p.

Through the above method, the client and server can obtain the same key.

From the above analysis, it can be seen that the security of the key exchange algorithm is based on the difficulty of computing discrete logarithms. It is easy to compute YY from XX, but it is very difficult to compute XX from YY. In the key exchange algorithm, only pp, gg, YcY_c, and YsY_s are publicly disclosed, while the private keys XcX_c and XsX_s are kept confidential. Even if other users obtain pp, gg, YcY_c, and YsY_s, it is difficult to infer the private keys XcX_c and XsX_s, thus ensuring the security of the keys.

The key exchange algorithm has the following advantages:

  • Better scalability, no need for excessive configuration by network administrators;
  • The exchanged keys are stored in memory and are not easily read or tampered with;
  • A new key is dynamically generated for each connection, providing higher security.

User Authentication Mechanism#

Password-Based Secure Authentication#

Using an automatically generated public-private key pair to simply encrypt the network connection, followed by using password authentication to log in. The specific process is as follows:

  • The client sends a login request, ssh user@hostname
  • The server accepts the request and sends the server's public key server_rsa.pub to the client
  • The client enters the password, which is encrypted using server_rsa.pub and sent to the server (sensitive information is transmitted securely)
  • The server receives the encrypted password, decrypts it using the server's private key server_rsa, and checks whether the authentication password is valid

At this point, the identity authentication is successful, and then the session key (symmetric encryption) is exchanged.

  • The client generates a session data encryption session_key, encrypts it using server_rsa.pub, and transmits it to the server (session key)
  • The server receives it and decrypts it using server_rsa to obtain session_key

Subsequent data transmitted is encrypted using the session key. Note: symmetric encryption is efficient.

  • The client and server securely transmit session data using session_key.

However, this authentication method cannot prevent man-in-the-middle attacks, as there may be other servers impersonating the real server.

Public Key Identity Authentication#

The client generates a pair of public and private keys and copies its public key to the server. When the client requests to log in, the server will randomly generate a string and encrypt it with the client's public key. The client receives it and decrypts it with its private key, then sends it back to the server. Upon receiving it, the server compares it; if the comparison is successful, it proves the user is trusted and allows login without requiring a password, thus avoiding man-in-the-middle attacks. The specific process is as follows:

image

The secure verification based on keys is simply described as shown in the figure. However, in the actual transmission process, all data needs to be encrypted to ensure secure data transmission, which also generates a session key to encrypt the transmitted data. The detailed process is as follows:

  • The client sends a login request, ssh user@hostname
  • The server accepts the request and sends the server's public key to the client
  • The server generates a session ID (session id), set as pp, and sends it to the client.
  • The client generates a session key (session key), set as qq, and calculates r=p xor qr=p\ xor\ q
  • The client encrypts rr using AsAs and sends the result to the server
  • The server decrypts it using the server's private key to obtain rr
  • The server performs the operation r xor pr\ xor\ p to obtain qq

At this point, both the server and client know the session key qq, and all subsequent transmitted data will be encrypted with qq.

  • The client uses its private key to decrypt SxS_x to obtain xx
  • The client calculates the md5 value of n(q+x)n(q+x), where qq is the session key obtained from the previous step
  • The client sends n(q+x)n(q+x) to the server
  • The server calculates the md5 value of m(q+x)m(q+x)
  • The server compares m(g+x)m(g+x) and n(g+x)n(g+x); if they are the same, authentication is successful.

At this point, both the server and client have authenticated each other and can use the session key for encryption and decryption during transmission.

  • The client and server securely transmit session data using qq.

SSH Keys#

SSH keys are access credentials used in the SSH protocol, similar to passwords. SSH keys grant users the ability to automatically access the core devices of enterprises remotely.

Host Key#

Each host (i.e., computer) has a unique host key.

  • Stored in Linux at /etc/ssh/ssh_host_<rsa/dsa/ecdsa/ed25519>_key
  • Stored in Windows at C:\ProgramData\ssh

When you first connect to a remote host via SSH, you will typically receive a prompt like this:

$ ssh user@ip-address
The authenticity of host 'ip-address (ip-address)' can't be established.
ECDSA key fingerprint is SHA256:hjn60Ix3hjduyfhjHLJKOdJSDDX6beXpfp0ypeqTOPQ+f0tU.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

When you type yes and press Enter to continue, you will see a prompt like this:

Warning: Permanently added 'ip-address' (ECDSA) to the list of known hosts.
user@ip-address's password:

It will be added to the known host key list in the following format:

ip-address ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEvRRBRoCJSuJuEaXK3i3k/4Cd+uriN5cKPGbbl/Q5f5DhjduyfhjHLQXDZPVDw0reLJKmIcGcZh2qQHX5qjMLQ=

Known Host Key List: The SSH client uses this to store the host keys of previously connected hosts.

  • Stored in Linux at /etc/ssh/known_hosts
  • Stored in Windows at C:\Users\User\.ssh\known_hosts

Authorized Key#

The authorized key in SSH is the public key used to grant users login access. The authentication mechanism is called public key authentication. In OpenSSH, the ssh-keygen tool can be used to generate it, usually generating a pair of keys (private key-public key), as shown in the figure below.

image

Authorized_keys File for Server Side#

In the authorized_keys file, authorized keys are configured separately for each user.

  • Stored in Linux at ~/.ssh/authorized_keys
  • Stored in Windows at C:\Users\user\.ssh\authorized_keys

You can modify its storage path in the SSH server's configuration file.

The content of the authorized key is as follows:

ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBN+Mh3U/3We4VYtV1QmWUFIzFLTUeegl1Ao5/QGtCRGAZn8bxX9KlCrrWISIjSYAwCajIEGSPEZwPNMBoK8XD8Q= user@host-name

Identity Key#

The identity key is a type of private key used in SSH public key authentication to grant access to the server. In OpenSSH, the ssh-keygen tool can be used to generate it, usually generating a pair of keys (private key-public key), as shown in the figure below.

image

Session Key#

The SSH protocol uses the Key Exchange algorithm to derive a unique key for each session or connection, known as the session key. Common Key Exchange algorithms include Diffie-Hellman and Elliptic-curve Diffie–Hellman.

The session key is shared between the two parties in the session connection, which is easily susceptible to man-in-the-middle attacks.

Forward secrecy: Because session keys are used, even if long-term keys (host keys) are compromised, intruders cannot decrypt previous session content.

Basic Knowledge About Keys#

Public Key#

The public key is the non-secret half of the key pair used with the private key algorithm. The public key is typically used to encrypt session keys, verify digital signatures, or encrypt data that can be decrypted with the corresponding private key. The public key and private key are a key pair obtained through an algorithm (i.e., one public key and one private key), where one is made public, called the public key; the other is kept private, called the private key. The key pair obtained through this algorithm can guarantee uniqueness worldwide. When using this key pair, if one key encrypts a piece of data, the other key must be used to decrypt it. For example, if the public key encrypts data, the private key must decrypt it; if the private key encrypts, the public key must decrypt it; otherwise, decryption will not succeed.

In SSH, public key encryption is used for authentication of computers and users. Host keys authenticate hosts. Authorized keys and identity keys authenticate users.

Private Key#

In public key cryptography, the private key is the key used to digitally sign documents. In some cryptographic systems, it can also be used to decrypt data encrypted with the public key. Each private key has a corresponding public key. Typically, the public key can be easily derived from the private key, but deriving the private key from the public key is computationally infeasible.

In SSH, the private key is used for authentication of computers and users. Host keys authenticate servers, while identity keys serve as user authentication credentials.

SSH Configuration Files#

OpenSSH Client Configuration File#

The configuration file's storage location:

  • Linux ~/.ssh/config /etc/ssh/ssh_config
  • Windows C:\Users\user\.ssh\config

Typically, the configuration file does not exist, and you can create it manually.

  • Linux touch ~/.ssh/config&&chmod 600 ~/.ssh/config
  • Windows manually create a text file in the C:\Users\user\.ssh\ path and remove the .txt suffix.

Structure of the Configuration File#

Host hostname1
    SSH_OPTION value
    SSH_OPTION value

Host hostname2
    SSH_OPTION value

Host *
    SSH_OPTION value
  • The structure of the config is as shown above, divided into blocks.
  • Indentation is not strictly necessary, but it greatly aids readability.
  • Each block starts with the Host directive, and each Host block can match one or more contents (separated by spaces) or use the following special identifiers:
    • * matches 0 or any number of characters. For example, Host * matches all Hosts, 192.168.0.* matches IPs under the subnet 192.168.0.0/24.
    • ? matches a single character. For example, 10.10.0.? matches 10.10.0.[0-9].
    • ! negates, i.e., does not match. For example, Host 10.10.0.* !10.10.0.5 matches the 10.10.0.0/24 subnet but excludes 10.10.0.5.

Matching Rules: The SSH client matches from top to bottom, so if multiple Host matches occur, the configuration parameters defined first take effect. For example, if the first matching configuration group has a User configuration, and the last matching group also has one, the User from the first matching group will be used. Therefore, it is recommended to place more specific matches at the top and general ones at the bottom (e.g., matches for a specific IP range at the top, and matches for all at the bottom).

Detailed Explanation of the Configuration File#

  • Host host-name specifies the configuration block, a required item.
  • user username specifies the login user, a required item.
  • hostname 10.0.0.1 specifies the server address, usually an IP address, a required item.
  • port 22 specifies the authentication private key file, a required item.
  • Identityfile ~/.ssh/id_rsa specifies the local authentication private key address.
  • IdentityFile ~/.ssh/id_rsa.pub specifies the authentication private key file.
  • ForwardAgent yes allows ssh-agent forwarding.
  • ForwardX11 yes allows X11 forwarding.
  • ForwardX11Trusted yes remote X11 clients will have full access to the original X11 display.
  • DynamicForward 2000 specifies the local port forwarded through a secure channel.
  • RemoteForward 3000 specifies a TCP port on the remote host forwarded through a secure channel to a specified host and port on the local machine. The first parameter must be: [bind_address:]port, and the second parameter must be host:port. SSH tunnel.
  • LocalForward specifies a TCP port on the local machine forwarded through a secure channel to a specified host and port on the remote machine. The first parameter must be [bind_address:]port, and the second parameter must be host:port.
  • ExitOnForwardFailure yes whether to terminate the connection when dynamic, tunnel, local, and remote port forwarding settings fail.
  • ClearAllForwardings specifies to clear all local, remote, and dynamic port forwards specified in the configuration file or on the command line.
  • GatewayPorts 2001 specifies whether to allow remote hosts to connect to local ports.
  • IdentitiesOnly no specifies whether ssh should only use private key files specified in the configuration file or command line for authentication. The value can be yes or no, defaulting to no, which can be used when ssh-agent provides too many authentication files.
  • StrictHostKeyChecking ask
    • ask: default value, prompts whether to add the server's public key when connecting to an unknown server for the first time, and refuses to connect if the remote server's public key changes;
    • yes: does not automatically add the server's public key to ~/.ssh/known_hosts, and refuses to connect if the remote server's public key changes;
    • no: automatically adds new host keys to ~/.ssh/known_hosts.
  • BindAddress 10.0.0.1 specifies using a specified address on the local machine as the source address for the connection.
  • Protocol 2 specifies the preferred order of protocol versions. Multiple versions must be separated by commas.
  • Cipher <char> sets the password used for encryption in SSH v1.
  • Ciphers <char>
    • Specifies the allowed passwords for SSH v2 in order of preference.
    • Multiple passwords must be separated by commas.
    • The command ssh -Q cipher can be used to query supported passwords.
  • HostKeyAlgorithms ssh-ed25519 specifies the host key algorithms for SSH v2 that the client will use, sorted by priority.
  • HostKeyAlias username specifies an alias to use when looking up or saving host keys in the key database file instead of the real host name.
  • GlobalKnownHostsFile <path> specifies a file to be used for the global host key database instead of /etc/ssh/known_hosts.
  • HashKnownHosts yes specifies whether to hash host names and addresses when adding them to ~/.ssh/known_hosts.
  • Compression no specifies whether to use compression.
  • CompressionLevel 1 specifies the compression level to use when compression is enabled.
  • EscapeChar ~ sets the escape key.
  • ConnectionAttempts 10 specifies the number of attempts to make before exiting.
  • ConnectTimeout 10 specifies the timeout (in seconds) to use when connecting to the SSH server instead of the default system TCP timeout.
  • ControlMaster 3 allows multiple sessions to share a single network connection.
  • ControlPath <path> specifies the path for the control socket used for connection sharing, or specify the string none to disable connection sharing.
  • RhostsAuthentication no sets whether to use rhosts-based security authentication.
  • RhostsRSAAuthentication no sets whether to use rhosts-based security authentication with RSA.
  • HostbasedAuthentication yes specifies whether to attempt rhosts-based authentication with public key authentication using .rhosts or .shosts files in the user's home directory and /etc/hosts.equiv and /etc/shosts.equiv in the global configuration.
  • RSAAuthentication yes sets whether to use RSA for secure authentication.
  • PasswordAuthentication yes sets whether to use password authentication.
  • FallBackToRsh no sets whether to automatically use rsh if there is an error connecting with ssh.
  • UseRsh no sets whether to use rlogin/rsh on this machine.
  • BatchMode no if set to yes, prompts for passphrase/password (interactive input) will be disabled. This option is useful for scripts and batch jobs when interactive input of passwords is not possible.
  • CheckHostIP yes sets whether ssh checks the IP address of the host connecting to the server to prevent DNS spoofing. It is recommended to set this to yes.
  • StrictHostKeyChecking no if set to yes, ssh will not automatically add the machine's key to the $HOME/.ssh/known_hosts file, and will refuse to connect if the machine's key changes.
  • KbdInteractiveAuthentication yes specifies whether to use keyboard-interactive authentication. This is a common method for password authentication, one-time passwords, and multi-factor authentication.
  • KbdInteractiveDevices
  • LocalCommand ipconfig specifies a command to execute on the local machine after successfully connecting to the server.
  • LogLevel ERROR specifies the verbosity of log information from ssh. It can be QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, DEBUG3.
  • Macs hmac-sha1 specifies the MAC (Message Authentication Code) algorithms in order of preference; the command ssh -Q mac can be used to query supported MAC algorithms.
  • NoHostAuthenticationForLocalhost yes can be used if the home directory is shared across machines. In this case, localhost will refer to different machines on each machine, and users will receive many warnings about changing host keys.
  • PreferredAuthentications specifies the order in which the client should attempt SSH v2 authentication methods.
  • ProxyCommand specifies the command to use to connect to the server. The SSH client communicates with the proxy command using its standard input and output, and the proxy command should pass the communication to the SSH server.
  • PubkeyAuthentication yes specifies whether to attempt public key authentication using SSH keys.
  • SendEnv specifies which environment variables should be sent to the server.
  • ServerAliveCountMax 10 sets the number of keepalive messages sent by the client without receiving any feedback from the server. When this threshold is reached, the client will terminate the session.
  • ServerAliveInterval 5 specifies the interval at which to send keepalive messages to the server. These messages are sent over the encrypted channel to detect whether the server has crashed or the network has been interrupted.
  • TCPKeepAlive yes specifies whether to send TCP keepalives to the other party. This operates at the TCP protocol level.
  • Tunnel yes requests device forwarding between the client and server. This is used to implement VPN over SSH.
  • TunnelDevice remote_tun specifies the device to open for tun, either local_tun or remote_tun.
  • UsePrivilegedPort no specifies whether to use privileged ports for outbound connections.
  • UserKnownHostsFile <path> specifies a file for the user's known host key database instead of the default ~/.ssh/known_hosts.
  • VerifyHostKeyDNS yes specifies whether to use DNS and SSHFP resource records to verify remote keys.
  • VisualHostKey yes specifies whether to print the remote host key fingerprint as ASCII art in addition to the hexadecimal fingerprint string when logging in or for unknown host keys.

OpenSSH Server Configuration File#

The OpenSSH server reads the configuration file at startup, and the usual storage locations for the configuration file are:

  • Linux /etc/ssh/sshd_config
  • Windows C:\ProgramData\ssh\sshd_config

Relationship of Configuration Files#

image

Configuration Details#

  1. Overall settings for the SSH Server, including the port used and the password algorithms used.
  • Port 22 SSH defaults to using port 22.
  • Protocol 2,1 specifies the SSH protocol version, which can be either 1 or 2; if both are to be supported, it must be specified as 2,1.
  • ListenAddress 10.0.0.1 only listens for SSH connections from 10.0.0.1. (Assuming there are two IPs, 10.0.0.1 and 10.0.0.2.)
  • PidFile /var/run/sshd.pid can place the PID file for SSHD; the left column is the default value.
  • LoginGraceTime 600 connection wait time (in seconds).
  • Compression yes specifies whether compression commands can be used.
  1. Specifies the files where the host's private keys are placed; the default files can be used.
  • HostKey /etc/ssh/ssh_host_key private key used for SSH v1.
  • HostKey /etc/ssh/ssh_host_rsa_key RSA private key used for SSH v2.
  • HostKey /etc/ssh/ssh_host_dsa_key DSA private key used for SSH v2.
  • KeyRegenerationInterval 3600 time interval for regenerating host keys.
  • ServerKeyBits 768 length of the server key.
  1. Information about the login file and the name of the daemon.
  • SyslogFacility AUTH when someone logs into the system using SSH, SSH records the information under the daemon name, which defaults to AUTH, i.e., in /var/log/secure. Other available daemon names include: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5.
  • LogLevel INFO the level of login record.
  1. Login settings.
  • PermitRootLogin no whether to allow root login. By default, it is allowed, but it is recommended to set it to no.
  • UserLogin no the SSH server does not accept login from the login program.
  • StrictModes yes if the user's host key changes, the server will not accept new SSH connections.
  • RSAAuthentication yes whether to use RSA authentication exclusively, only for SSH v1.
  • PubkeyAuthentication yes whether to allow public key authentication only for SSH v2.
  • AuthorizedKeysFile .ssh/authorized_keys path to the key for key identity authentication.
  1. Authentication section.
  • RhostsAuthentication no whether to use .rhosts, which is usually disabled due to security concerns.
  • IgnoreRhosts yes whether to cancel the use of ~/.ssh/.rhosts.
  • RhostsRSAAuthentication no whether to use rhosts with RSA for authentication, only for SSH v1.
  • HostbasedAuthentication no this item is similar to the above, only for SSH v2.
  • IgnoreUserKnownHosts no whether to ignore the host contents recorded in /home/.ssh/known_hosts.
  • PasswordAuthentication yes whether to enable password authentication.
  • PermitEmptyPasswords no whether to allow login with empty passwords.
  • ChallengeResponseAuthentication yes challenges any password authentication; any authentication method specified in login.conf can apply!
  • PAMAuthenticationViaKbdInt yes whether to enable other PAM modules! Enabling this will cause the PasswordAuthentication setting to become ineffective.
  1. Parameters related to Kerberos.
  • KerberosAuthentication no
  • KerberosOrLocalPasswd yes
  • KerberosTicketCleanup yes
  • KerberosTgtPassing no
  1. The following are related settings for use under X-Window.
  • X11Forwarding yes
  • X11DisplayOffset 10
  • X11UseLocalhost yes
  1. Post-login items.
  • PrintMotd no whether to display some information after logging in, such as the last login time and location, default is yes.
  • PrintLastLog yes display information about the last login, default is yes.
  • KeepAlive yes whether to enable keepalive.
  • UsePrivilegeSeparation yes user privilege setting items.
  • MaxStartups 10 the number of simultaneous connections allowed that have not yet logged in (i.e., connected to SSH but have not yet entered a password).
  1. Settings for denying connections.
  • DenyUsers test set the username to deny login.
  • DenyGroups test set the user group to deny login.
  1. Settings for SFTP services.
  • Subsystem sftp /usr/lib/ssh/sftp-server.

known_hosts#

The known_hosts file stores the host keys of authenticated remote hosts, and each SSH Server has a secret, unique ID called a host key.

The storage path for known_hosts:

  • Linux: ~/.ssh/known_hosts
  • Windows: C:\Users\user\.ssh\known_hosts

When we first log into a remote host via SSH, the client will prompt as follows:

Host key not found from the list of known hosts.
Are you sure you want to continue connecting (yes/no)?

At this point, if we choose yes, the host key will be added to the client's known_hosts in the following format:

# domain name + encryption algorithm + host key
example.hostname.com ssh-rsa AAAAB4NzaC1yc2EAAAABIwAAAQEA...

Why is known_hosts needed? This file mainly serves to authenticate both the client and server, thus avoiding man-in-the-middle attacks. Each time the client initiates a connection to the server, not only does the server need to verify the client's legitimacy, but the client also needs to verify the server's identity. The SSH client verifies the server's identity using the host key in known_hosts.

Practical Tutorial#

Installing SSH Client and Server#

Linux Installation Verification#

In most Linux systems, it is installed by default, and you can use the following command to check.

  • Successfully displaying the version number proves that OpenSSH is installed.
  • The service status is green, indicating that the SSH service is running.
# Verify ssh version
$ ssh -V
OpenSSH_8.2p1 Ubuntu-4ubuntu0.4, OpenSSL 1.1.1f  31 Mar 2020
# Verify SSH service status
$ systemctl status sshd.service
 ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/lib/systemd/system/ssh.service; ena>
     Active: active (running) since Sun 2022-02-27 19:28:>
       Docs: man:sshd(8)
             man:sshd_config(5)
    Process: 796 ExecStartPre=/usr/sbin/sshd -t (code=exi>
   Main PID: 824 (sshd)
      Tasks: 1 (limit: 4491)
     Memory: 4.0M
     CGroup: /system.slice/ssh.service
             └─824 sshd: /usr/sbin/sshd -D [listener] 0 o>

Mar 03 00:44:39 zac-ubuntu sshd[21852]: pam_unix(sshd:ses>
Mar 03 00:44:39 zac-ubuntu sshd[21852]: pam_unix(sshd:ses>
Mar 03 00:44:54 zac-ubuntu sshd[21917]: Accepted password>
Mar 03 00:44:54 zac-ubuntu sshd[21917]: pam_unix(sshd:ses>
Mar 03 00:45:02 zac-ubuntu sshd[21985]: Accepted password>
Mar 03 00:45:02 zac-ubuntu sshd[21985]: pam_unix(sshd:ses>
Mar 03 19:56:27 zac-ubuntu sshd[26728]: Accepted password>
Mar 03 19:56:27 zac-ubuntu sshd[26728]: pam_unix(sshd:ses>
Mar 03 21:28:46 zac-ubuntu sshd[28737]: Accepted password>
Mar 03 21:28:46 zac-ubuntu sshd[28737]: pam_unix(sshd:ses>
lines 1-22/22 (END)

Manual Installation of SSH on Linux#

Installation commands:

# arch
pacman -S openssh
# ubuntu
apt-get install openssh
# RHEL
yum install openssh

Start the service:

# Start the SSH daemon
systemctl start sshd
# Enable on boot
systemctl enable sshd

Manual Installation of SSH on Windows#

OpenSSH support started in Windows 10 (version 1809 and later). To install the OpenSSH component:

  1. Open "Settings", select "Apps" > "Apps & Features", then select "Optional Features".
  2. Scan the list to see if OpenSSH is installed. If not, select "Add a feature" at the top of the page, then:
  • Look for "OpenSSH Client" and click "Install".
  • Look for "OpenSSH Server" and click "Install". After setup is complete, return to "Apps" > "Apps & Features" and "Optional Features", and you should see OpenSSH listed.

For step-by-step tutorials, refer to “Windows - Installing SSH Server”.

image

For Windows 10 (version 1809 and earlier) and Windows 7, manually install OpenSSH:

  1. Download the installation file for the corresponding system version; GitHub download link.
  2. Unzip the downloaded installation .zip file.
  3. Copy the unzipped folder to the C:/Program Files/ path, or any other path you prefer on your computer.
  4. In Computer (Windows 7) or This PC (Windows 10), right-click --> Properties --> Advanced System Settings --> Environment Variables -- System Variables, find Path and edit it;

image

  1. For Windows 7, edit in text form, so you need to add a semicolon ; at the end, then paste your installation path C:\Program Files\OpenSSH-Win64; for Windows 10, adding is more convenient, just go into Path, click New, and paste it directly;

image

For detailed tutorials, refer to “Windows Install OpenSSH Support for SSH”.

Verify the installation on Windows by opening cmd or powershell:

$ ssh -V
OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2

Set the SSH service to start automatically on boot.

image

SSH Port Number#

By default, SSH operates on TCP port 22.

In the SSH C/S model, the SSH Server listens on port 22, while the SSH Client uses a random port number (1024~65535) to establish a connection with the SSH Server.

How to Change the Default Port of the SSH Server#

Locate the SSH configuration file:

  • In Linux: /etc/ssh/sshd_config
  • In Windows: C:\ProgramData\ssh\sshd_config
#Port 22

Uncomment the line by removing the # and change 22 to the port you want SSH to operate on (please do not conflict with other ports).

Connecting to SSH Using a Specified Port Number#

ssh -p <port-number> user@ip-address
sftp -P <port-number> user@ip-address  # Note P is uppercase

SFTP uses the SSH protocol to transfer data, so it shares the port number.

Key Generation Tool ssh-keygen#

ssh-keygen is a tool used to create new key pairs, which consist of the authorized key and identity key mentioned in the previous sections.

Here is an example of the operation:

$ ssh-keygen 
Generating public/private rsa key pair. 
Enter file in which to save the key (/home/user/.ssh/id_rsa):   # You can specify the key storage path at this step
Enter passphrase (empty for no passphrase):   # You can specify a password (passphrase) to protect the key at this step
Enter same passphrase again:   # Confirm the password (passphrase) from the previous step again
Your identification has been saved in /home/user/.ssh/id_rsa.   # Prompting your private key storage path
Your public key has been saved in /home/user/.ssh/id_rsa.pub.   # Prompting your public key storage path
The key fingerprint is: SHA256:Up6KjbnEV4Hgfo75YM393QdQsK3Z0aTNBz0DoirrW+c user@host 
The key's random art image is: 
+---[RSA 2048]----+ 
|    .      ..oo..| 
|   . . .  . .o.X.| 
|    . . o.  ..+ B| 
|   .   o.o  .+ ..| 
|    ..o.S   o..  | 
|   . %o=      .  | 
|    @.B...     . | 
|   o.=. o. . .  .| 
|    .oo  E. . .. | 
+----[SHA256]-----+ 
host (11:40) ~>

All the steps above can be left blank, and you do not need to fill in any content.

Choosing Algorithm and Key Size#

In the above "The key's random art image is:", we can see RSA 2048, where RSA is the key algorithm; 2048 is the key size.

ssh-keygen -t <algorithm> -b <size>   #-t specifies the algorithm name; -b specifies the key size

SSH supports various key algorithms:

  • rsa is one of the earliest public key cryptosystems widely used for secure data transmission. Its security relies on integer factorization, so it never requires a secure RNG (random number generator). Compared to DSA, RSA has faster signature verification but slower generation speed. A key size of at least 2048 bits is recommended, with 4096 bits being better.
  • dsa is an older digital signature algorithm used by the U.S. government. It is based on the difficulty of computing discrete logarithms. Compared to RSA, DSA has faster signature generation but slower verification speed. A typical key size is 1024.
  • ecdsa is the elliptic curve implementation of DSA (Digital Signature Algorithm). Elliptic curve cryptography can provide a level of security comparable to RSA with smaller keys. It also has the disadvantage of DSA being sensitive to poor RNG. It supports three key sizes: 256, 384, and 521 bits, with 521 bits recommended.
  • ed25519 is an EdDSA signature scheme that uses SHA-512/256 and Curve25519; it is a secure elliptic curve that provides better security and performance than DSA, ECDSA, and EdDSA. This is a new algorithm added in OpenSSH, with limited client support.
  1. Based on mathematical properties, these four types can be divided into two categories: dsa/rsa is one category, and ecdsa/ed25519 is another, with the latter being more advanced.
  2. DSA is no longer used due to security issues.
  3. ECDSA is also not recommended for political and technical reasons.
  4. RSA is currently the most compatible and widely used key type, and it is also the default type when generating keys with the ssh-keygen tool. However, if the specified key size is too small, there are security issues; a recommended key size is 3072 or larger.
  5. Ed25519 is currently the most secure and fastest key type for encryption and decryption. Due to its mathematical properties, its key length is much smaller than RSA, making it the preferred choice. Its only issue is compatibility, as it may not be usable in older versions of SSH toolsets. However, I have not encountered such issues in my tests. -- Excerpted from “Differences Between RSA, DSA, ECDSA, EdDSA, and Ed25519”.

Using ssh-keygen to Create Host Keys#

This tool is also used to create host keys. Each host can generate a pair of keys for each of the four algorithms mentioned above. In Linux, the examples are as follows:

  • /etc/ssh/ssh_host_dsa_key
  • /etc/ssh/ssh_host_dsa_key.pub
  • /etc/ssh/ssh_host_ecdsa_key
  • /etc/ssh/ssh_host_ecdsa_key.pub
  • /etc/ssh/ssh_host_ed25519_key
  • /etc/ssh/ssh_host_ed25519_key.pub
  • /etc/ssh/ssh_host_rsa_key
  • /etc/ssh/ssh_host_rsa_key.pub

Host keys are usually generated automatically when the SSH service is installed. They can also be regenerated at any time, and if the host key changes, the client may issue warnings about the changed key.

Tool to Copy Keys to the Server ssh-copy-id#

In addition to manually copying the authorized key from the client's id-rsa.pub to the server's authorized_keys, you can also use the ssh-copy-id tool to complete this operation via the command line.

First, ensure you have generated a pair of keys (public key-private key) on the client. Here is the copy command:

ssh-copy-id -i <pub_key path> user@serverhost   #<pub_key path>: the path of the public key file

Upon successful execution, the client's authorized key will appear in the server's authorized_keys.

The ssh-copy-id command is not available on Windows; you can refer to “Solution for Unable to Use ssh-copy-id on Windows”.

Achieving Passwordless Login via SSH (Public Key Authentication)#

Preparation Conditions#

  • SSH client and server installed.

Simple Configuration on the Server Side#

  1. Create the ~/.ssh directory and the ~/.ssh/authorized_keys file for the user you want to log in as. Set the correct permissions (otherwise, SSH will refuse the connection):
# Confirm the current user is harttle
whoami
# Create .ssh directory
mkdir ~/.ssh
chmod 700 ~/.ssh
# Create the public key file
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

The above commands apply to Linux. On Windows, find the C:\Users\user\.ssh\ directory, and the authorized_keys file will usually be generated automatically. If not, you can manually create a text file and rename it to authorized_keys (note: it should not have a .txt or other suffix).

  1. Copy the content of the public key (authorized key) from the client’s ~/.ssh/id_rsa.pub to the server’s ~/.ssh/authorized_keys file.
cat ~/.ssh/id_rsa.pub | ssh user 'cat >> .ssh/authorized_keys'

On Linux, you can also use the ssh-copy-id tool to copy the key.

Now you can log in without authentication using the following command:

ssh <user>@<ipaddress>

When using Windows as the server, it may not configure successfully; refer to the issue of automatic login configuration in section 7.4.

SSH Identity Authentication Agent ssh-agent#

ssh-agent is a program that controls the private keys used for public key authentication.

Essentially, ssh-agent is a key manager. After running ssh-agent, use ssh-add to hand over the private key to ssh-agent for safekeeping. Other programs that require authentication can submit their requests to ssh-agent to complete the entire authentication process.

Usage Scenarios for ssh-agent#

  • When connecting to different hosts using different keys, you need to manually specify the corresponding key. ssh-agent can help us select the corresponding key for authentication without manually specifying it.

    If we did not use the default name id_rsa when generating the key pair with ssh-keygen, but instead used another name, such as is_rsa_test, when we use that key pair to connect to the remote server ssh user@host, it will still prompt for the password of the server host.

    This is because SSH defaults to using ~/.ssh/id_rsa for authentication when authenticating based on keys. If you use a non-default private key for authentication, you need to manually specify the corresponding private key; otherwise, SSH will still default to using ~/.ssh/id_rsa, resulting in authentication failure.

    Although you can specify the corresponding private key file for authentication using the -i option, ssh -i ~/.ssh/id_rsa_test user@host, this can become cumbersome if there are many key pairs. ssh-agent can help us manage these keys, avoiding the need to manually specify keys; ssh-agent will help us select the corresponding key. Use ssh-add ~/.ssh/id_rsa_test to add the key to ssh-agent.

  • When the private key is password-protected and we need to frequently use the private key for authentication, ssh-agent can help us avoid repeatedly entering the password.

    If a password is specified when generating the key pair, each time the private key is used for authentication, it will require entering the private key password. If you need to connect to the server repeatedly in the current SSH session, entering the complex private key password repeatedly can be cumbersome. ssh-agent can help us; in one SSH session, you only need to enter the private key password once, and in the same SSH session, you can use the same private key without entering the corresponding password again.

How to Use ssh-agent#

  1. Start the ssh-agent process.

    Enter the ssh-agent environment:

    # On Linux
    ssh-agent bash  
    ssh-agent $SHELL
    eval $(ssh-agent)
    # On Windows
    ssh-agent
    # You can also manually start the OpenSSH Authentication Agent service in the services.
    

    At this point, you will find that a new ssh-agent process has been added to the system.

    ssh-agent parameters:

    ParameterDescription
    -a <bind_address>Bind the agent to a Unix domain socket binding address
    -dDebug mode
    -DForeground mode.
    -kKill the ssh-agent process (not effective on Windows)
    -sGenerate Bourne shell style command output
    -E <fingerprint_hash>Specify the hash algorithm to use when displaying key fingerprints. md5 or sha256 (default)
  2. Add keys to ssh-agent.

    ssh-add <options> <path>  #<path>: the path of the key
    

    ssh-add parameters:

    ParameterDescription
    -lList all key fingerprints in the current agent
    -LList all public key parameters in the current agent
    -E <fingerprint_hash>Specify the hash algorithm to use when displaying key fingerprints. md5 or sha256 (default)
    -kSkip certificates when adding or removing keys from agent
    -KLoad resident keys from the FIDO authenticator
    -cRequire confirmation before using the added key for authentication
    -tSet the lifetime (in seconds) when adding the key (you can add TIME FORMATS h in sshd_config to change the time unit, supporting s m h d w)
    -TTest whether the specified private key is usable by performing signing and verification operations on each private key
    -dRemove the key from agent
    -DRemove all keys from agent
    -xLock agent with a password, i.e., pause agent from managing keys
    -XUnlock agent with a password
    -qKeep silent after successful operation
    -hAdd the key only for specific hosts or targets
    -HSpecify a hosts file for this key to look up host keys during authentication. Multiple hosts files can be specified multiple times, separated by commas.

Other Settings#

Simplifying Login#

You have already configured passwordless login (public key authentication), but if your username is complex (e.g., an email address) or you do not want to remember the server's IP address, you can change the configuration file to simplify the process.

Find the path of the configuration file:

  • Linux ~/.ssh/config
  • Windows C:\Users\Lin\.ssh\config

Add the following content to the config file:

Host <name>  # Custom name
  HostName <ipaddress>  # Server host name or IP address
  UserName <user>  # Username to use when logging in

Now you can use the simplified command:

ssh <name>

You can also refer to the detailed explanation of the client configuration file to add the features you need.

Secure File Transfer Tools#

Secure File Transfer SFTP#

sftp is a file transfer program similar to ftp, which uses ssh to encrypt all operations. It can also use SSH's public key authentication and compression features.

  • Connection command:

    sftp user@host:path
    # URI format:
    sftp://user@host:port/path
    

    sftp command parameters:

    ParameterDescription
    -aAttempt to continue interrupted transfers instead of overwriting existing parts of files
    -bBatch mode
    -B <buffer_size>Specify the buffer size to use when transferring files. Larger buffers require fewer round trips but consume more memory. The default is 32768 bytes.
    -lLimit bandwidth, specified in Kbit/s
    -PSpecify the port on the remote host to connect to
    -pPreserve original file modification times, access times, and modes
    -4Same as ssh command
    -6Same as ssh command
    -ASame as ssh command
    -CSame as ssh command
    -FSame as ssh command
    -iSame as ssh command
    -JSame as ssh command
  • Interactive commands:

    sftp> cd <path> # Open path <path>
    sftp> bye  # Exit SFTP
    sftp> quit  # Exit SFTP
    sftp> exit  # Exit SFTP
    sftp> help  # Display help text
    sftp> ?  # Display help text
    sftp> ls <path>  # Display directories and files in the current directory or <path>
    sftp> ls -1 <path>  # Display the current directory or <path> in a single column
    sftp> ls -a <path>  # List files starting with . in the current directory or <path>
    sftp> ls -f <path>  # List files in the current directory or <path> without sorting
    sftp> ls -l <path>  # Display detailed information about files and directories in the current directory or <path>
    sftp> ls -n <path>  # Display detailed information about files and directories in the current directory or <path>, with user and group information displayed numerically
    sftp> ls -r <path>  # Display files in the current directory or <path> in reverse order
    sftp> ls -S <path>  # Sort files by size in the current directory or <path>
    sftp> ls -t <path>  # Sort files by last modified time in the current directory or <path>
    sftp> lls <path>  # Display directories in the current directory or <path>
    sftp> chgrp <group> <path>  # Change the group of the file <path> to <group>
    sftp> chmod <mode> <path>  # Change the mode of the file <path> to <mode>
    sftp> chown <owner> <path>  # Change the owner of the file <path> to <owner>
    sftp> df -h <path>  # Display usage information for the file system containing the current directory or <path>
    sftp> df -i <path>  # Display inode information for the file system containing the current directory or <path>
    sftp> get <remote-path> <local path>  # Retrieve the <remote-path> file or directory and store it in the local <local path>; if no local path name is specified, it will be given the same name as on the remote machine.
    sftp> get -a <remote-path> <local path>  # Attempt to recover partially transferred existing files
    sftp> get -p <remote-path> <local path>  # Copy file permissions and access times
    sftp> lcd <path>  # Change the local directory to <path> or the user's home directory
    sftp> lpwd  # Print the local working directory
    sftp> pwd  # Print the remote working directory
    sftp> lmkdir <path>  # Create a local directory <path>
    sftp> mkdir <path>  # Create a remote directory <path>
    sftp> rename <path1> <path2>  # Rename the remote file from <path1> to <path2>
    sftp> ln <path1> <path2>  # Create a link from <path1> to <path2>
    sftp> ln -s <path1> <path2>  # Create a hard link from <path1> to <path2>
    sftp> put <local path> <remote path>  # Upload the local <local path> and store it in the remote <remote path>; if no remote path name is specified, it will be given the same name as on the local machine.
    sftp> put -a <local path> <remote path>  # Attempt to recover partially transferred existing files
    sftp> put -ap <local path> <remote path>  # Copy file permissions and access times
    sftp> reget <remote-path> <local path>  # Equivalent to get -a
    sftp> reput <local path> <remote path>  # Equivalent to put -a
    sftp> rm <path>  # Delete the specified remote file <path>
    sftp> rmdir <path>  # Delete the specified remote directory <path>
    sftp> version  # Display the current sftp protocol version
    sftp> !  # Jump to the local shell
    sftp> ! <command>  # Execute command <command> in the local shell
    

Secure File Copy SCP#

SCP is a program used to copy files between computers, using the SSH protocol. By default, it is included in the SSH software package.

Basic usage of SCP:

  1. Copy from local to remote host.

    • Specify the remote directory; the file name remains unchanged after copying.
    scp local_file remote_username@remote_ip:remote_folder  # Only prompts for password after execution
    scp local_file remote_ip:remote_folder # Prompts for username and password after execution
    
    • Specify the file name; change to the specified file name after copying.
    scp local_file remote_username@remote_ip:remote_file # Only prompts for password after execution
    scp local_file remote_ip:remote_file # Prompts for username and password after execution
    
    • Copy directory -r
    scp -r local_folder remote_username@remote_ip:remote_folder # Only prompts for password after execution
    scp -r local_folder remote_ip:remote_folder # Prompts for username and password after execution
    
  2. Copy from remote host to local.

    Just swap the last two parameters of the command used to copy from local to remote.

    scp remote_username@remote_ip:remote_file local_file 
    scp -r remote_username@remote_ip:remote_folder local_folder
    
  3. Specify port number -P.

    Use uppercase P.

    # SCP command using port number 4588
    scp -P 4588 remote_username@remote_ip:remote_folder
    
  4. Passwordless authentication.

    Passwordless authentication can be achieved after configuring SSH public key authentication.

Summary of SSH Commands#

Syntax format ssh [options] [remote host]

ParameterDescription
-1Force the use of SSH protocol version 1
-2Force the use of SSH protocol version 2
-4Force the use of IPv4 addresses
-6Force the use of IPv6 addresses
-AEnable authentication agent connection forwarding
-aDisable authentication agent connection forwarding
-b <IP address>Use the specified address on the local machine as the source IP address for the connection
-CRequest compression of all data
-F Specify the configuration file for the ssh command; the default configuration file is “/etc/ssh/ssh_config”
-fExecute the ssh command in the background
-gAllow remote hosts to connect to local forwarded ports
-i Specify the identity file (i.e., private key file)
-l Specify the username to connect to the remote server
-NDo not execute remote commands
-o Specify configuration options
-p Specify the port on the remote server
-qSilent mode; all warnings and diagnostic messages are suppressed
-XEnable X11 forwarding
-xDisable X11 forwarding
-yEnable trusted X11 forwarding
# Example
ssh -p <port-number> -- user -i C:\Users\user\.ssh\custom_config <ip-address>

Common Issues#

Man-in-the-Middle Attacks in SSH#

Hackers and malware attack routers, DSL modems, and WiFi routers, installing malicious software to perform man-in-the-middle attacks. Devices with installed malware are called attack tools.

In the SSH protocol, host keys can only be accessed by the root user. If an attacker gains root access to the server, they can certainly obtain a copy of the host key.

Once the attacker obtains a copy of the server's host key, when the client connects, they can impersonate the SSH server and establish a connection with the client, tricking the server into providing its password or key.

Then, the attacker can act as the client on the attack tool and establish another encrypted connection with the server.

X11 Forwarding#

What is X11 Forwarding?#

The X in X11 refers to the X protocol; 11 refers to the 11th version of the X protocol. Simply put, X11 forwarding allows you to connect to a remote Linux server using an SSH client that supports X Server, such as MobaXterm, and run graphical programs on the remote Linux server locally.

Brief Introduction to X Protocol Principles#

image

The Linux system itself does not have a graphical interface; the so-called graphical interface system is merely an application under Linux, and all graphical interface applications in Linux are based on the X protocol.

The X protocol consists of an X server and X clients:

  • The server manages the hardware settings related to display on the host (such as graphics cards, hard drives, mice, etc.), responsible for rendering and displaying the screen, as well as informing the X client of input settings (such as keyboard and mouse) actions.
  • The X client (i.e., X application) is mainly responsible for event handling (i.e., program logic).

For example, if the user clicks the left mouse button, since the mouse is managed by the X server, the X server captures this mouse click action and informs the X client of the action. The X client, responsible for program logic, tells the X server, "Please draw a circle at the position where the mouse was clicked." Finally, the X server responds to the X client's request by drawing and displaying a circle at the mouse click position.

SSH Clients Supporting X11 Forwarding#

  • XShell- 6
  • MobaXterm 11

Similarities and Differences Between SCP and SFTP#

Both use the SSH protocol to transfer files. The user information during login is transmitted after being encrypted by SSH, so both SCP and SFTP achieve secure file transfer. SFTP commands are similar to FTP commands, and the usage of SFTP is also similar to FTP. The commonality between SCP and SFTP is that files are transmitted encrypted using SSH.

Differences between SCP and SFTP:

  • SCP is simpler and lightweight, while SFTP has more features.
  • If the file transfer process of SFTP is interrupted, it can continue transferring after reconnecting, but SCP cannot.

Issues with Automatic Login Configuration on Windows#

When using Windows as the server and following the steps in section 6.5 to configure SSH passwordless login (public key authentication), it still prompts for a password during connection.

I tried restarting the OpenSSH SSH Server service on the server side, but it still did not work.

Using ssh -vvv to check debug information:

debug3: send packet: type 50
debug2: we sent a keyboard-interactive packet, wait for reply
debug3: receive packet: type 51 
debug1: Authentications that can continue: publickey,password,keyboard-interactive

This is the debug information for successful automatic login with Ubuntu as the server:

debug3: sign_and_send_pubkey: signing using rsa-sha2-512
debug3: send packet: type 50
debug3: receive packet: type 52
debug1: Authentication succeeded (publickey).
Authenticated to 10.0.0.20 ([10.0.0.20]:2000).

It can be seen that when using Windows as the server, the client sends the key, but the server does not respond.

You can obtain the complete debug information from Aliyun Drive.

SSH Tunneling#

SSH tunneling, or SSH port forwarding, establishes a tunnel between the SSH client and the SSH server, forwarding network data through that tunnel to a specified port for network communication. SSH tunneling automatically provides the corresponding encryption and decryption services, ensuring the security of data transmission.

There are three modes of port forwarding in SSH tunneling: local port forwarding, remote port forwarding, and dynamic port forwarding. The directions of local and remote port forwarding are exactly opposite. When connecting to a cloud phone, local port forwarding is used, so this article focuses on the working principle of local port forwarding.

Assuming the local host A1 is the SSH client and the remote cloud host B1 is the SSH server. By logging into the B1 host from A1, specifying different port forwarding options (-L, -R, and -D), an SSH tunnel can be established between A1 and B1 for different port forwarding.

Application Scenario

A service running on the remote cloud host B1 listens on port 2000, and the local host A1 needs to access this service. Assuming the cloud host B1's IP is 122.x.x.x, the service's access address is: http://122.x.x.x:2000.

Why is local port forwarding needed?

Generally, the firewall of the cloud host only opens port 22 by default. If you need to access port 2000, you need to modify the firewall settings. To ensure security, the firewall needs to be configured to allow access from specific IP addresses. However, the public IP of the cloud host is usually dynamically assigned by the network provider, and if the public IP address changes, the firewall configuration needs to be modified frequently, causing unnecessary trouble.

What is local port forwarding?

Local port forwarding forwards requests sent to

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.