0% found this document useful (0 votes)
7 views26 pages

Securing Remote Access On Linux Server (Centos)

This guide provides a comprehensive approach to securing remote access on a CentOS Linux server using SSH. It covers various authentication methods, server setup, user access preparation, and hardening techniques to mitigate threats such as brute-force attacks and unauthorized access. Key recommendations include enforcing strong password policies, utilizing public key authentication, and implementing multi-factor authentication for enhanced security.

Uploaded by

hammouchi.douae
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views26 pages

Securing Remote Access On Linux Server (Centos)

This guide provides a comprehensive approach to securing remote access on a CentOS Linux server using SSH. It covers various authentication methods, server setup, user access preparation, and hardening techniques to mitigate threats such as brute-force attacks and unauthorized access. Key recommendations include enforcing strong password policies, utilizing public key authentication, and implementing multi-factor authentication for enhanced security.

Uploaded by

hammouchi.douae
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BARNI ABDERRAHMAN

Securing Remote Access on Linux Server


(CentOS)
BARNI ABDERRAHMAN

CONTENT
1. Introduction
1.1. Purpose of the Guide
1.2. Threats to Remote Access
1.3. Security Principles Applied

2. Understanding SSH Authentication Methods


2.1. Password-Based Authentication
2.2. Public Key Authentication
2.3. Combining Password and Key Authentication

3. Initial SSH Server Setup


3.1. Installing the OpenSSH Server
3.2. Verifying SSH Service Status
3.3. Backing Up Existing SSH Configuration

4. User and Access Preparation


4.1. Enforcing Strong Password Policies
4.2. Creating a Dedicated Administrative User
4.3. Creating a Dedicated SSH Administrative Group
4.4. Granting Sudo Privileges
4.5. Securing User Home and SSH Directories

5. Configuring Password Authentication


5.1. Enabling Password Authentication
5.2. Limiting Authentication Attempts

6. Configuring Public Key Authentication


6.1. Generating SSH Key Pairs
6.2. Deploying Public Keys to the Server
6.3. Securing SSH Key Files and Permissions
6.4. SSH Public Key Configuration

7. Combining Password and Public Key Authentication


7.1. Enabling Multi-Factor Authentication Logic
7.2. Testing Combined Authentication

8. Hardening SSH Configuration


8.1. Changing the Default SSH Port
8.2. Disable Direct Root Login
8.3. Restricting SSH Access to Authorized Users and Groups
8.4. Limiting Simultaneous SSH Sessions
8.5. Configuring Idle Session Timeouts
8.6. Disabling unnecessary SSH Features
BARNI ABDERRAHMAN

8.7. Limiting Information Disclosure


8.8. Enable Verbose Logging

9. Network/Application Level Protection


9.1. Allowing SSH Through the Firewall
9.2. Source IP Filtering With PAM

10. Testing, Logging and Monitoring


10.1. Case 1: Successful Logging
10.2. Case 2: Failed Password Logging
10.3. Case 3: Logging From Disallowed IP
10.4. Case 4: Logging Attempt by Root

11. SSH Client Configuration


11.1. File Location and Scope
11.2. Basic Syntax and Structure
11.3. Global Configuration Using Wildcards
11.4. Testing SSH Connection

12. Conclusion
BARNI ABDERRAHMAN

[Link]

1.1. Purpose of the Guide


Secure remote access to a server is critical in protecting sensitive data and maintaining operational integrity. This
guide provides a practical approach to hardening SSH access by configuring both password authentication and
public key authentication.

1.2. Threats to Remote Access


Exposing SSH services to the network without proper security measures can lead to multiple threats.
Common risks include brute-force attacks targeting weak passwords, unauthorized access from compromised
credentials, and exploitation of default or misconfigured SSH settings. Attackers often scan for open SSH ports to
attempt credential guessing or deploy automated scripts to gain access, making it essential to implement robust
authentication and access controls.

1.3. Security Principles Applied


The guide follows established security principles to ensure a layered defense against potential attacks. Key
principles include defense in depth, where multiple authentication methods strengthen access control; least
privilege, granting users only the permissions necessary to perform their tasks; and strong authentication,
leveraging cryptographic keys alongside passwords.
BARNI ABDERRAHMAN

[Link] SSH Authentication Methods

2.1. Password-Based Authentication


Password authentication is the most common SSH authentication method. Users log in using a username and a
password stored on the server. While simple to use, it is vulnerable to brute-force attacks, weak passwords, and
credential theft. Securing password authentication requires enforcing strong passwords, limiting login
attempts, and monitoring failed login attempts.

2.2. Public Key Authentication


Public key authentication uses a cryptographic key pair: a private key kept securely on the client, and a public
key stored on the server. When a connection is attempted, the server verifies that the client possesses the matching
private key. This method is more secure than passwords because it is immune to brute-force attacks and
eliminates the need to transmit passwords over the network.

2.3. Combining Password and Key Authentication


For enhanced security, SSH can be configured to require both a password and a public key. This approach acts
as a form of multi-factor authentication, combining something the user knows (password) with something the
user has (private key).

NOTE:

This guide applies to CentOS 7 and CentOS Stream/RHEL-based systems. Commands may vary slightly.
BARNI ABDERRAHMAN

[Link] SSH Server Setup

3.1. Installing the OpenSSH Server


Ensure that the OpenSSH server package is installed:

yum install -y openssh-server

3.2. Verifying SSH Service Status


After installation, check that the sshd service is running and enabled at boot:

systemctl status sshd

systemctl enable sshd

systemctl start sshd

3.3. Backing Up Existing SSH Configuration


Before making any changes, always backup the default SSH configuration file:

cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

This ensures you can restore the original settings in case of misconfiguration. On CentOS, SSH also supports
custom configuration files in /etc/ssh/sshd_config.d/.
BARNI ABDERRAHMAN

[Link] And Access Preparation

4.1. Enforcing Strong Password Policies


To strengthen password authentication, configure password aging and complexity.

Edit the password policy file:

vim /etc/[Link]

For password complexity, install and configure:

yum install -y libpwquality

Then edit:

vim /etc/security/[Link]

 minlen: Minimum password length


 dcredit: Specifies how many digits are required. “-1”  at least 1 digit required.
 ucredit: Controls uppercase characters. “-1”  at least 1 uppercase required.
 lcredit: Controls lowercase characters. “-1”  at least 1 lowercase required.
 ocredit: Requires non-alphanumeric characters. “-1”  at least 1 special character required.
 difok: Difference from the old password. Prevents users from changing “Password123!” to “Password124!”.
 maxrepeat: Blocks weak patterns like “aaaaBBB111”.
 reject_username: Prevents passwords that contain the username.
BARNI ABDERRAHMAN

4.2. Creating a Dedicated Administrative User


Instead of using the root account for remote access, create a dedicated administrative user to limit exposure and
improves traceability.

Create a new user:

useradd adminuser

Set a strong password for the user:

passwd adminuser

4.3. Creating a Dedicated SSH Administrative Group


To better control which users are allowed to access the server via SSH, create a dedicated group specifically
for remote administrative access. This group will later be referenced in the SSH configuration to explicitly
allow or deny SSH access.

Create the group and add the administrative user to this group:

groupadd sshadmins

usermod -aG sshadmins adminuser

4.4. Granting Sudo Privileges


To allow the user to perform administrative operations without logging in as root, add the user to the wheel
group (default sudo group on CentOS):

usermod -aG wheel adminuser


BARNI ABDERRAHMAN

Verify sudo access:

4.5. Securing User Home and SSH Directories


Ensure correct permissions on the user’s home directory to prevent unauthorized access to sensitive files such as
SSH keys:

chmod 700 /home/adminuser

chown adminuser:adminuser /home/adminuser


BARNI ABDERRAHMAN

[Link] Password Authentication

5.1. Enabling Password Authentication


Open the SSH configuration file and edit the next directives:

PasswordAuthentication yes

PermitEmptyPasswords no

UsePAM yes

 PasswordAuthentication yes: ensures password login is allowed.


 UsePAM yes: enables system-level password controls (complexity, aging, lockout).
 PermitEmptyPasswords no: prevents authentication using accounts without defined passwords.

5.2. Limiting Authentication Attempts


MaxAuthTries 3

LoginGraceTime 30

 MaxAuthTries 3: restricts the number of authentication attempts per connection.


 LoginGraceTime 30: It gives the user 30 seconds to successfully authenticate (password, key, MFA, etc.)
after the TCP/SSH connection is established. If authentication isn’t completed within that time,
sshd disconnects the session automatically.

Before restarting the SSH service, the configuration syntax is validated:


sshd -t

The absence of output indicates a valid configuration.

Restart the SSH service:


systemctl restart sshd
BARNI ABDERRAHMAN

[Link] Public Key Authentication

6.1. Generating SSH Key Pairs


SSH public key authentication relies on asymmetric cryptography, where a private key is retained by the user and a
corresponding public key is stored on the server.

Create a hidden directory in which we’re going to store the generated key:

mkdir .ssh

SSH key pairs should be generated on the client system from which administrative access is initiated.

For more control over the generated keys, set a passphrase to protect it.

ssh-keygen -t ed25519 -a 100 -f ~/.ssh/id_ed25519

 -t ed25519: selects a modern elliptic-curve algorithm with strong security and performance characteristics.
 -a 100: increases key derivation function (KDF) rounds, strengthening protection against brute-force attacks
on encrypted private keys.
 -f: specifies a non-default key filename to support key rotation and multiple identities.

Check the generated keys:


BARNI ABDERRAHMAN

6.2. Deploying Public Keys to the Server


The recommended method for deploying public keys is ssh-copy-id:

- Creates the .ssh directory if it does not exist


- Appends the public key to the authorized_keys file
- Applies secure default permissions

ssh-copy-id user@server_ip

Check the keys on the SSH server:

ls -la /home/adminuser/.ssh/

6.3. Securing SSH Key Files and Permissions


Strict file permission enforcement is mandatory for SSH public key authentication to function correctly.

Required Permission Settings:

- ~.ssh  700: Prevents unauthorized directory access


- ~.ssh/authorized_keys  600: Restricts key modification
- User Home Directory  750 or 700: Prevents key exposure. 700 is the safest and universally compatible
option.
BARNI ABDERRAHMAN

6.4. SSH Public Key Configuration


Add those lines:

PubkeyAuthentication yes

AuthorizedKeysFile .ssh/authorized_keys

 AuthorizedKeysFile: Restricting the authorized keys file location simplifies auditing and access control.

Check the syntax and restart the SSH Service:


BARNI ABDERRAHMAN

[Link] Password and Public Key Authentication

While public key authentication significantly improves security, the compromise of a private key can still lead to
unauthorized access. Combining public key authentication with password-based authentication introduces an
additional verification factor,

7.1. Enabling Multi-Factor Authentication Logic in SSH


By default, OpenSSH allows authentication using either a password or a public key. To enforce dual
authentication, the SSH daemon must be explicitly configured to require multiple authentication methods.

Add the following line:

AuthenticationMethods publickey,password

NOTE:

In environments where multiple categories of users access the same system—such as administrative users, service
accounts, or automated processes—it may be desirable to apply dual authentication only to privileged users.
This can be achieved using a conditional Match block, as shown below:

Match Group sshadmins

AuthenticationMethods publickey,password

7.2. Testing Combined Authentication


On the SSH client:

ssh user@server-ip

Connection successfully established and authenticated using both factors. ✅


BARNI ABDERRAHMAN

[Link] SSH Configuration

After implementing secure authentication mechanisms, additional hardening of the SSH service is required to
reduce the attack surface and mitigate common exploitation techniques. SSH hardening focuses on minimizing
exposure, restricting privileged access, enforcing session controls, and limiting the impact of potential misuse.

8.1. Changing the Default SSH Port


The default SSH port (TCP 22) is a frequent target for automated scanning and brute-force attacks. While
changing the port does not provide true security, it reduces unsolicited connection attempts and log noise.

Configure the port in the configuration file:

Port 2022

Make sure to allow the port on SELinux by issuing the next command as indicated in the SSH configuration file:

semanage port -a -t ssh_port_t -p tcp 2022

8.2. Disable Direct Root Login


Allowing direct SSH access as the root user increases the risk of privilege escalation and eliminates accountability.
Disabling root login ensures that administrative actions are performed through individual user accounts and
audited accordingly.

PermitRootLogin no

8.3. Restricting SSH Access to Authorized Users and Groups


Restricting SSH access ensures that only explicitly authorized users or groups can establish remote sessions,
significantly reducing the risk of unauthorized access.

AllowGroups sshadmins

This directive ensures that only members of the sshadmins group can authenticate via SSH.

Use the AllowUsers directive to restrict access to specific users independently.


BARNI ABDERRAHMAN

8.4. Limiting Simultaneous SSH Sessions


MaxSessions limits the maximum number of simultaneously open shell, login, or subsystem sessions (for
example, SFTP) that a client can establish over a single SSH network connection.

MaxSessions 3

8.5. Configuring Idle Session Timeouts


Idle SSH sessions pose a security risk if left unattended. Enforcing session timeouts reduces the likelihood of
session hijacking or misuse.

ClientAliveInterval 300

ClientAliveCountMax 2

 ClientAliveInterval 300: sets how often the sshd server sends an encrypted keepalive request when it has not
received any data from the client for that many seconds (here, 300 seconds = 5 minutes).
 ClientAliveCountMax 2: sets how many of those keepalive requests can be sent without getting any
response back from the client before sshd disconnects the session (here, after 2 unanswered keepalives).

8.6. Disabling Unnecessary SSH Features


Disable X11 Forwarding and TCP Forwarding:

X11Forwarding no

AllowTcpForwarding no

 X11 Forwarding lets a user run graphical (GUI) apps on the remote SSH server but display the windows on
the local machine through the SSH tunnel.
It creates a channel that can expose the client’s X session to risk (e.g., window/keystroke scraping or abuse if
the remote side is malicious or compromised), and it’s rarely needed on servers.
 TCP Forwarding allows SSH to create tunnels/port forwards (local -L, remote -R, dynamic/SOCKS -D) so
traffic to other services can be carried inside SSH.
Disabling SSH port forwarding entirely, means users can still SSH in, but they can’t use the SSH connection to
proxy/tunnel other network connections through the server.
It reduces “SSH tunnel abuse” like bypassing firewall rules, hiding data exfiltration inside an encrypted tunnel,
reaching internal services through the SSH server as a pivot, or setting up reverse tunnels that create
unintended inbound access paths.
BARNI ABDERRAHMAN

8.7. Limiting Information Disclosure


Create a file and edit it using a text editor and add those lines:

Modify the path of the banner:

Banner /etc/ssh/ssh_banner

Check the syntax and restart the SSH service.

8.8. Enable Verbose Logging


The VERBOSE log level records successful and failed authentication attempts, including the method used
(password, key, or combined).

LogLevel VERBOSE

Save and reload the SSH service.


BARNI ABDERRAHMAN

[Link]/Application-Level Protection

In addition to securing authentication and SSH daemon settings, it is essential to protect the SSH service at the
network level. Network-level protection reduces exposure to unauthorized access attempts, minimizes brute-
force attack surface, and provides an additional layer of defense against remote exploitation.

9.1. Allowing SSH Through the Firewall


CentOS uses firewalld as the default firewall management service. SSH traffic must be explicitly permitted for the
service to remain accessible.

Verify the services and ports allowed on the firewall:

firewall-cmd --list-all

Allow SSH on the configured port number:

firewall-cmd --add-port=2022/tcp –permanent

Reload the firewalld service:

firewall-cmd --reload
BARNI ABDERRAHMAN

Verification:

9.2. Source IP Filtering With PAM (pam_access)


The pam_access module allows administrators to restrict SSH authentication based on both user/group identity
and source IP address or subnet. When combined with firewalld rules and other PAM modules (e.g.,
pam_faillock), it enforces layered security controls, limits administrative exposure, and supports the principle of
least privilege.

On CentOS, this can be achieved using the pam_access module in combination with the
/etc/security/[Link] file. This method allows fine-grained control over which users or groups can
authenticate from which IP addresses, providing an additional layer of defense alongside firewalls and SSH
hardening.

Enable pam_access by opening the /etc/pam.d/sshd and uncommenting/adding the following line:

account required pam_access.so

This directs the SSH daemon to consult /etc/security/[Link] for access rules.

The /etc/security/[Link] file defines allow (+) and deny (-) rules for users and groups, optionally restricting
them to specific source IP addresses or networks.
BARNI ABDERRAHMAN

Edit the /etc/security/[Link] file and add those lines:

## Single administrative user - only allowed from bastion IP


+:adminuser:[Link]
-:adminuser:ALL

## SSH administrative group


+:@sshadmins:[Link]
-:@sshadmins:ALL

## Disable root login entirely


-:root:ALL

 +:adminuser:[Link]: Allow adminuser from bastion host only. Permits SSH login from a trusted IP.
 -:adminuser:ALL: Deny adminuser from all other IPs. Prevents login attempts from unauthorized locations.
 +:@sshadmins:[Link]: Allow members of sshadmins group from the same bastion IP. Grants group-level
administrative access from a trusted host.
 -:@sshadmins:ALL: Deny group members from all other IPs. Blocks all other access attempts for group
members.
 -:root:ALL: Disable root login entirely. Provides an extra layer beyond PermitRootLogin no in
sshd_config.
BARNI ABDERRAHMAN

10. Testing, Logging and Monitoring

On CentOS, SSH logs are written to /var/log/secure via rsyslog or journald.

PAM-related events (e.g., failed login attempts, lockouts) are also recorded in the same log.

Regular log review enables early detection of anomalies or malicious activity.

For basic log review:

tail -f /var/log/secure

10.1. Case 1: Successful Login (Authorized User, Allowed IP)

grep "Accepted" /var/log/secure

10.2. Case 2: Failed Password Login (Incorrect Password)


Filtering failed logins:

grep "Failed Password" /var/log/secure


BARNI ABDERRAHMAN

10.3. Case 3: Login From Disallowed IP (PAM pam_access)


grep "pam_access" /var/log/secure

10.4. Case 4: Login Attempt by Root


tail -n /var/log/secure | grep "root"
BARNI ABDERRAHMAN

11. SSH Client Configuration

When administrators are required to connect to multiple remote servers—each with distinct access parameters
such as usernames, ports, or authentication methods—or when performing chained (jump host) connections,
managing these details manually can become inefficient and error-prone.

To address this challenge, OpenSSH provides a client-side configuration file, commonly referred to as
~/.ssh/config, which allows centralized and persistent management of SSH connection parameters.

This configuration does not affect the SSH server and applies only to outbound connections initiated by the
client.

11.1. File Location and Scope


The SSH client configuration file is located in the user’s home directory: ~/.ssh/config

This file is user-specific and applies only to the account under which it is defined.

NOTE:

The file must have restrictive permissions (600) to be accepted by the SSH client.

Create the file (if not already there) and check permissions:

11.2. Basic Syntax and Structure


The SSH client configuration file is composed of Host blocks, each defining connection parameters for a specific
server or group of servers.
BARNI ABDERRAHMAN

 Host: Defines a connection alias used in the ssh command.


 HostName: Specifies the actual hostname or IP address of the remote server.
 User: Defines the default username for the connection.
 Port: Specifies the port if changed

NOTE:

- The file is case-sensitive


- Indentation is significant and typically uses spaces
- Each directive must belong to the appropriate Host block
- Incorrect formatting may cause directives to be ignored silently

11.3. Global Configuration Using Wildcards


The SSH client supports wildcard patterns, allowing the definition of global defaults using the * character.

 Compression: Enables data compression, improving performance over slow or high-latency links.

 ServerAliveInterval: Sends a keepalive message every 60 seconds to prevent idle disconnections.

 ForwardX11: Disables X11 forwarding by default, reducing attack surface. This option can be selectively
enabled for trusted hosts if required.

Global settings apply to all SSH connections, unless overridden in a specific Host block.
BARNI ABDERRAHMAN

11.4. Testing SSH Connection


Establishing an SSH Connection to the first server:

ssh srv1

Establishing an SSH connection to the second server:

ssh srv2
BARNI ABDERRAHMAN

12. Conclusion
By applying layered controls—strong password policy, SSH key-based authentication (optionally combined with
a password), and strict user/group restrictions—remote access is hardened against common threats like brute-force
attempts and credential misuse. SSH daemon hardening (non-root administration, session limits/timeouts, reduced
feature exposure), firewall/IP-based filtering, and verbose logging further reduce the attack surface while
improving detection and traceability. Finally, treat SSH security as an ongoing process: validate changes, keep
rollback access and backups ready, rotate keys, patch regularly, and perform periodic audits to maintain a secure
remote-access baseline over time.

You might also like