How to configure sshd to have both ssh and sftp connection?
Configuring sshd
for Seamless SSH and SFTP Connections: A Comprehensive Guide
At revWhiteShadow, we understand the critical need for secure and flexible remote access to your Linux servers. This guide offers a deep dive into configuring the sshd
service to enable both secure shell (SSH) and secure file transfer protocol (SFTP) access, especially when dealing with configurations that might initially restrict SSH access. We will meticulously dissect the configuration, troubleshoot common issues, and provide best practices to ensure a robust and user-friendly setup. This guide is geared towards system administrators and power users who want granular control over their server’s remote access capabilities.
Understanding the SSHD Configuration Landscape
The sshd_config
file is the cornerstone of your SSH server’s behavior. This file dictates authentication methods, connection protocols, and user-specific rules. Incorrect configurations can lead to access restrictions, security vulnerabilities, and operational inefficiencies. A careful approach to modifying sshd_config
is essential.
Navigating the /etc/ssh/sshd_config
File
The sshd_config
file, typically located at /etc/ssh/sshd_config
, is the central configuration file for the OpenSSH server. Editing this file requires root privileges. Before making any changes, always back up the original file to facilitate rollback if necessary. The file comprises a series of directives, each controlling a specific aspect of the server’s operation.
Core SSHD Directives Relevant to This Guide
Several directives are paramount to configuring both SSH and SFTP access. We will provide a detailed overview of the most important ones:
Port
: Specifies the port number that the SSH server listens on (default: 22).ListenAddress
: Defines the IP address(es) on which the server listens for connections.PermitRootLogin
: Determines whether root login is allowed. Set toyes
(discouraged, for security reasons),no
(recommended), orprohibit-password
(allowing key-based authentication).PasswordAuthentication
: Controls password-based authentication. Set toyes
(discouraged), orno
(encouraged with key-based authentication).PubkeyAuthentication
: Enables public key authentication. Set toyes
to allow key-based authentication.AuthorizedKeysFile
: Specifies the location of the authorized keys file for public key authentication (default:.ssh/authorized_keys
).AllowUsers
: Defines a list of users allowed to connect.DenyUsers
: Defines a list of users denied access.AllowGroups
: Defines a list of groups allowed to connect.DenyGroups
: Defines a list of groups denied access.Match
: Enables conditional configuration based on user, group, host, or address. This directive is essential for user-specific settings.ChrootDirectory
: Restricts a user’s file system access to a specified directory. This greatly enhances security for SFTP access.ForceCommand
: Executes a specific command when a user connects. This directive is very common for SFTP setups, where theinternal-sftp
command is used.Subsystem sftp
: Configures the SFTP subsystem. Although often commented out by default, it’s crucial for SFTP functionality.
Addressing the SFTP-Only Restriction
The primary challenge is that the provided configuration in the prompt results in SFTP-only access. The ForceCommand internal-sftp
directive overrides the user’s shell upon login. This is great for SFTP, but it blocks standard SSH interactive sessions.
Decoding the Match Group root
Configuration
The Match Group root
configuration is a conditional block that applies settings to the root
group. This means that any user belonging to the root group will have those settings applied. In the example provided, it sets a ChrootDirectory
and a ForceCommand
. The ChrootDirectory
confines the user’s access to the /share
directory, enhancing security. The ForceCommand internal-sftp
ensures that when a user connects, the internal-sftp
server is invoked, thus disabling the SSH shell.
Identifying the Root Cause: The ForceCommand
Directive
The root of the problem lies in the ForceCommand internal-sftp
directive. This directive, while essential for SFTP, prevents the user from accessing a standard SSH shell. To solve this, we need to allow the root
user (or, more safely, a specific group or user) to have both SSH and SFTP access, allowing them to choose their connection method.
Configuring SSH and SFTP Access for the Root User (with Caution)
Providing both SSH and SFTP access to the root user directly is generally discouraged due to security implications. It’s far safer to create a dedicated user account and grant them the necessary permissions instead. However, we’ll discuss this setup for the sake of demonstration and understanding.
Modifying sshd_config
to Allow SSH and SFTP for Root
To achieve both SSH and SFTP access for root (again, with caution), you can modify the /etc/ssh/sshd_config
file. Back up the file before making any changes. Use a text editor with root privileges. The core modification involves removing the ForceCommand
directive for root directly, or alternatively commenting out the Match Group root
section.
Example 1 (Removing ForceCommand
or commenting out the whole section):
#SFTP server configuration
#Match Group root
# ChrootDirectory /share
# ForceCommand internal-sftp
Example 2 (Allowing interactive SSH and SFTP):
Match User root
ChrootDirectory /share
# Note that if your user cannot navigate the directory structure the login will fail.
AllowTcpForwarding no
X11Forwarding no
ForceCommand internal-sftp
Example 3 (Allowing interactive SSH and SFTP, and setting up SFTP to a dedicated directory):
Match User root
ChrootDirectory /share
# Note that if your user cannot navigate the directory structure the login will fail.
AllowTcpForwarding no
X11Forwarding no
ForceCommand /usr/lib/openssh/sftp-server
Explanation of changes:
- The code comment indicates that all of the lines are now not applied.
- The code in the last example allows SSH by allowing the default shell and allowing sftp-server. This can be a bit tricky because the user still has an interactive shell.
Important Considerations:
- Restart
sshd
: After making changes, you must restart the SSH service for them to take effect. You can do this by runningsudo systemctl restart sshd
orsudo service ssh restart
. - Security Risks: Directly allowing SSH access to root increases the attack surface of your server. Limit this practice where possible, and favor key-based authentication over password-based authentication. Consider creating a dedicated user account and granting them elevated privileges using tools like
sudo
.
Configuring SSH and SFTP Access for a Dedicated User (Recommended)
The best approach is to create a dedicated user account and configure sshd
to allow both SSH and SFTP access for this user, which is far more secure.
Creating a Dedicated User and Group
First, create a user and group for managing SFTP and SSH access.
- Create a Group:
sudo groupadd sftpusers
- Create a User and Add to the Group:Replace
sudo useradd -m -g sftpusers -s /bin/bash your_sftp_user
your_sftp_user
with the desired username. The-m
option creates the user’s home directory,-g
specifies the group, and-s /bin/bash
sets the default shell (choose your preferred shell). - Set the User’s Password:Enter and confirm a strong password.
sudo passwd your_sftp_user
Configuring sshd_config
for the Dedicated User
Now, modify the /etc/ssh/sshd_config
file to define SSH and SFTP access for your new user. This is similar to the root configuration, but it’s targeted specifically to the dedicated user.
Back up the original
sshd_config
file.Edit the File:
sudo nano /etc/ssh/sshd_config
Add the
Match User
block:Match User your_sftp_user ChrootDirectory /share # Or your desired chroot directory AllowTcpForwarding no # Optional: Disable TCP forwarding X11Forwarding no # Optional: Disable X11 forwarding ForceCommand internal-sftp # Or /usr/lib/openssh/sftp-server
Match User your_sftp_user
: This applies the subsequent settings only to the specified user.ChrootDirectory /share
: Specifies the root directory for SFTP access. This directory should be owned by root, and it is highly recommended to contain only the files your user should access.AllowTcpForwarding no
andX11Forwarding no
: These directives can enhance security. They are optional, but disabling them may reduce the attack surface if these features are not required.ForceCommand internal-sftp
: (for SFTP-only) This restricts the user to SFTP only. The alternative is to use theForceCommand /usr/lib/openssh/sftp-server
setting and provide an interactive shell.
Save the changes and close the editor.
Restart SSHD:
sudo systemctl restart sshd
Setting Up Permissions and Chroot Directory
Correctly configuring the permissions of the chroot directory is very important.
- Create the Chroot Directory:
sudo mkdir -p /share
- Set Ownership and Permissions:This sets the owner to root, the group to root, and the permissions to 755 (rwxr-xr-x).
sudo chown root:root /share sudo chmod 755 /share
- Create a User-Specific Subdirectory (Recommended):This creates a directory within
sudo mkdir /share/your_sftp_user sudo chown your_sftp_user:sftpusers /share/your_sftp_user sudo chmod 755 /share/your_sftp_user
/share
specifically for the user, and assigns ownership to the user and their group.
Testing the Configuration
- Test SFTP Access: Use an SFTP client (e.g., FileZilla, Cyberduck, or the
sftp
command-line tool) to connect to your server using the new user. Verify that you can successfully upload, download, and manage files within the chroot directory. - Test SSH Access:
- Open a new SSH connection to the server using the new user. Verify that you can successfully log in. If using
ForceCommand internal-sftp
, you will only be able to connect via SFTP. If you want SSH, then use a non-ForceCommand internal-sftp
setting. - If you are having problems with SSH access, review the logs for problems.
- Open a new SSH connection to the server using the new user. Verify that you can successfully log in. If using
Troubleshooting and Advanced Configurations
Even with careful configuration, problems may arise. Here are some troubleshooting tips and advanced settings.
Common Issues and Solutions
- Connection Refused: Check the SSH daemon’s status (
sudo systemctl status sshd
), firewall rules (sudo ufw status
orsudo iptables -L
), and thePort
directive insshd_config
. - Authentication Failures: Verify the username, password, and key authentication settings. Examine the SSH logs (
/var/log/auth.log
or/var/log/auth.log
) for clues. Check that theAuthorizedKeysFile
is correctly configured. - SFTP Errors: Ensure that the
internal-sftp
subsystem is enabled insshd_config
. Examine file permissions, and double-check theChrootDirectory
configuration. The user’s home directory, or the root directory should not be writable by others. - “This service allows sftp connections only”: This message suggests that
ForceCommand internal-sftp
is being triggered when you attempt to connect over SSH. Modify yourMatch User
orMatch Group
configurations to allow standard SSH sessions or comment out theForceCommand
.
Logging and Auditing
- SSH Logs: The primary source of information for troubleshooting SSH issues is the SSH logs, usually located in
/var/log/auth.log
or/var/log/auth.log
. Enable verbose logging insshd_config
(LogLevel DEBUG3
) for more detailed information. - Audit Logs: Consider using audit logging (e.g.,
auditd
) to monitor SSH and SFTP activity. This helps you detect and investigate suspicious activities. - Regularly Review Logs: Make it a habit to regularly review the SSH logs to identify potential security breaches, failed login attempts, and configuration problems.
Advanced Security Considerations
- Key-Based Authentication: Always use key-based authentication over password-based authentication for security reasons.
- Disable Password Authentication (Recommended): In
/etc/ssh/sshd_config
, setPasswordAuthentication no
to disable password-based authentication completely. This significantly reduces the attack surface. - Two-Factor Authentication (2FA): Implement two-factor authentication (2FA) for added security. This adds another layer of verification to the login process.
- Fail2ban: Install and configure Fail2ban to automatically ban IP addresses that repeatedly fail to authenticate.
- Regular Security Audits: Conduct regular security audits of your SSH configuration and overall server security posture.
Conclusion: Mastering SSH and SFTP Configuration
Configuring sshd
to provide both SSH and SFTP access is a crucial skill for any system administrator. By understanding the key directives, employing best practices, and implementing robust security measures, you can create a secure and flexible remote access environment. Remember to always prioritize security and thoroughly test any configuration changes before applying them in a production environment. This comprehensive guide will equip you with the knowledge and tools to effectively manage your SSH and SFTP configurations, ensuring secure and seamless remote access to your Linux servers. The recommendations above ensure that users can make informed decisions about their systems. By following these guidelines, you can successfully configure sshd
for both SSH and SFTP access while maintaining a secure and manageable environment.