LinuxでSFTPのPermission Deniedエラーをトラブルシューティングする方法

LinuxLinuxBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

Introduction

SFTP (Secure File Transfer Protocol) is a powerful and secure solution for transferring files over a network. This tutorial will guide you through understanding SFTP, troubleshooting 'Permission Denied' errors, and resolving SFTP permission issues on your Linux system. You will learn how to set up an SFTP server, create users with appropriate permissions, and diagnose common permission problems that occur during file transfers.

Setting Up SFTP Server on Ubuntu

SFTP (Secure File Transfer Protocol) provides a secure method for transferring files between systems. Unlike regular FTP, SFTP encrypts both commands and data during transmission, protecting your information from unauthorized access.

In this step, we will set up a basic SFTP server on our Ubuntu system.

Installing OpenSSH Server

First, let's ensure our system is up to date and install the OpenSSH server, which includes SFTP capabilities:

sudo apt update
sudo apt install -y openssh-server

After running these commands, you should see output similar to:

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
openssh-server is already the newest version (1:8.9p1-3ubuntu0.1).

Verifying SSH Service Status

Since we're in a Docker container, the standard systemctl command won't work. Let's check if the SSH service is running using the process status command:

ps aux | grep sshd

You should see output indicating that sshd is running:

root      1234  0.0  0.1  12016  5604 ?        Ss   10:20   0:00 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups

Creating a Test User for SFTP

Let's create a dedicated user for testing SFTP functionality:

sudo adduser sftpuser

When prompted, enter a simple password like password123 and you can press Enter to skip the additional user information fields. You should see output similar to:

Adding user `sftpuser' ...
Adding new group `sftpuser' (1001) ...
Adding new user `sftpuser' (1001) with group `sftpuser' ...
Creating home directory `/home/sftpuser' ...
Copying files from `/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully

Creating Test Files for SFTP Transfer

Now, let's create some test files in our home directory that we'll use for SFTP transfers:

cd ~/project
echo "This is a test file for SFTP transfers" > testfile.txt
echo "This file has different permissions" > restrictedfile.txt

Let's verify the files were created correctly:

ls -l testfile.txt restrictedfile.txt

You should see output similar to:

-rw-rw-r-- 1 labex labex 37 Sep 28 10:30 restrictedfile.txt
-rw-rw-r-- 1 labex labex 38 Sep 28 10:30 testfile.txt

By default, both files have read and write permissions for the owner and group, and read-only permissions for others. We'll experiment with changing these permissions in the next steps.

Understanding File Permissions and Their Impact on SFTP

Before we explore SFTP permission issues, let's understand the Linux file permission system and how it affects SFTP operations.

Linux File Permission Basics

In Linux, every file and directory has three types of permissions:

  • Read (r): Allows viewing file contents or listing directory contents
  • Write (w): Allows modifying files or creating/deleting files in a directory
  • Execute (x): Allows executing files or accessing a directory

These permissions are assigned to three user categories:

  • Owner: The user who created the file
  • Group: The group assigned to the file
  • Others: Everyone else

Viewing Current Permissions

Let's check the current permissions of our test files:

ls -l ~/project/testfile.txt ~/project/restrictedfile.txt

You'll see output similar to:

-rw-rw-r-- 1 labex labex 38 Sep 28 10:30 /home/labex/project/testfile.txt
-rw-rw-r-- 1 labex labex 37 Sep 28 10:30 /home/labex/project/restrictedfile.txt

The permission string -rw-rw-r-- can be broken down as:

  • First character - indicates a regular file (would be d for directory)
  • Next three characters rw- show owner permissions (read, write, no execute)
  • Next three characters rw- show group permissions (read, write, no execute)
  • Last three characters r-- show others permissions (read only)

Modifying File Permissions

Let's modify the permissions of our files to create scenarios that might lead to permission denied errors in SFTP:

## Make testfile.txt readable by everyone but writable only by owner
chmod 644 ~/project/testfile.txt

## Make restrictedfile.txt accessible only to the owner
chmod 600 ~/project/restrictedfile.txt

Now, let's verify the changes:

ls -l ~/project/testfile.txt ~/project/restrictedfile.txt

You should see the updated permissions:

-rw-r--r-- 1 labex labex 38 Sep 28 10:30 /home/labex/project/testfile.txt
-rw------- 1 labex labex 37 Sep 28 10:30 /home/labex/project/restrictedfile.txt

Setting Up a Directory for SFTP Tests

Let's create a dedicated directory for SFTP testing:

mkdir -p ~/project/sftp_test
echo "This file is in the SFTP test directory" > ~/project/sftp_test/test_file.txt
chmod 755 ~/project/sftp_test

Now, let's create a directory with restricted permissions:

mkdir -p ~/project/restricted_sftp
echo "This file is in the restricted directory" > ~/project/restricted_sftp/restricted_file.txt
chmod 700 ~/project/restricted_sftp

Let's verify the directory permissions:

ls -ld ~/project/sftp_test ~/project/restricted_sftp

You should see:

drwxr-xr-x 2 labex labex 4096 Sep 28 10:35 /home/labex/project/sftp_test
drwx------ 2 labex labex 4096 Sep 28 10:35 /home/labex/project/restricted_sftp

The sftp_test directory can be accessed by anyone, while the restricted_sftp directory can only be accessed by the owner (labex user).

Experiencing and Diagnosing SFTP Permission Denied Errors

In this step, we'll connect to our SFTP server and experience permission denied errors firsthand. This will help us understand how permission settings affect SFTP operations.

Connecting to SFTP Server Locally

Since we're working in a local environment, we can connect to our SFTP server using the localhost address. Let's connect using the sftpuser we created earlier:

sftp sftpuser@localhost

When prompted for the password, enter the password you set for the sftpuser account (e.g., password123). If the connection is successful, you'll see a prompt like:

Connected to localhost.
sftp>

If you encounter connection issues, it could be because the SSH service isn't running properly in the container. You can try exiting with exit and proceeding with the next steps using theoretical examples.

Basic SFTP Commands

Let's explore some basic SFTP commands:

  1. View the current directory on the remote server:
sftp> pwd
Remote working directory: /home/sftpuser
  1. List files in the current directory:
sftp> ls
  1. Navigate to a different directory:
sftp> cd /tmp
sftp> pwd
Remote working directory: /tmp
  1. Return to your home directory:
sftp> cd
sftp> pwd
Remote working directory: /home/sftpuser

Attempting to Access Files with Different Permissions

Now, let's try to access our test files from the SFTP session:

  1. Try to get a file from our project directory:
sftp> get /home/labex/project/testfile.txt
Fetching /home/labex/project/testfile.txt to testfile.txt
Permission denied

You'll notice a "Permission denied" error. This is because the sftpuser doesn't have permission to access files in the labex user's home directory.

Exit the SFTP Session

Let's exit the SFTP session to continue:

sftp> exit

Understanding Permission Denied Errors

There are several common reasons for "Permission denied" errors in SFTP:

  1. File Permissions: The user doesn't have read/write access to the file
  2. Directory Permissions: The user can't access the directory containing the file
  3. Ownership Issues: The file/directory belongs to a different user or group
  4. Path Traversal Restrictions: SFTP configuration might restrict users to certain directories

Let's make one of our test files accessible to our SFTP user:

## Create a directory that can be accessed by others
mkdir -p /tmp/shared
echo "This is a shared file for SFTP testing" > /tmp/shared/shared_file.txt
chmod 777 /tmp/shared
chmod 666 /tmp/shared/shared_file.txt

Now, reconnect to SFTP and try accessing this file:

sftp sftpuser@localhost

After connecting, try:

sftp> get /tmp/shared/shared_file.txt
Fetching /tmp/shared/shared_file.txt to shared_file.txt
/tmp/shared/shared_file.txt                        100%   36     1.0KB/s   00:00

This should work because we've given everyone read/write permissions to both the directory and the file.

Exit the SFTP session again:

sftp> exit

Using SFTP with Debug Mode

To get more information about permission errors, you can use SFTP in debug mode:

sftp -v sftpuser@localhost

The verbose output will show you detailed information about the connection and any errors that occur:

debug1: Sending subsystem: sftp
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 2412, received 2876 bytes, in 0.1 seconds
Bytes per second: sent 30074.7, received 35857.2
debug1: Exit status 0

Resolving SFTP Permission Denied Errors

Now that we understand how permissions affect SFTP access, let's learn how to resolve common permission denied errors.

Solution 1: Adjusting File and Directory Permissions

The most straightforward solution to permission issues is to adjust file and directory permissions. Let's create a new test case:

## Create a new test file with restrictive permissions
echo "This file has restricted permissions" > ~/project/restricted_access.txt
chmod 600 ~/project/restricted_access.txt

Check the current permissions:

ls -l ~/project/restricted_access.txt

Output:

-rw------- 1 labex labex 35 Sep 28 11:05 /home/labex/project/restricted_access.txt

Now, let's make this file accessible to others by changing its permissions:

chmod 644 ~/project/restricted_access.txt
ls -l ~/project/restricted_access.txt

Output:

-rw-r--r-- 1 labex labex 35 Sep 28 11:05 /home/labex/project/restricted_access.txt

With these permissions (644), the file owner (labex) can read and write to the file, while the group members and others can only read it.

Solution 2: Changing File Ownership

Another solution is to change the ownership of files to match the SFTP user. Let's create another test file:

echo "This file will be owned by sftpuser" > ~/project/ownership_test.txt

Now, let's change the ownership to our SFTP user:

sudo chown sftpuser:sftpuser ~/project/ownership_test.txt
ls -l ~/project/ownership_test.txt

Output:

-rw-rw-r-- 1 sftpuser sftpuser 36 Sep 28 11:10 /home/labex/project/ownership_test.txt

Now the file is owned by sftpuser, who can read and write to it.

Solution 3: Creating a Shared Directory

A common solution for SFTP file sharing is to create a directory with appropriate permissions that multiple users can access:

## Create a new shared directory with appropriate permissions
mkdir -p /tmp/sftp_shared
sudo chown labex:labex /tmp/sftp_shared
chmod 755 /tmp/sftp_shared

## Create a subdirectory for uploads that's writable by everyone
mkdir -p /tmp/sftp_shared/uploads
chmod 777 /tmp/sftp_shared/uploads

## Create a sample file in the shared directory
echo "This file is in the shared SFTP directory" > /tmp/sftp_shared/sample.txt
chmod 644 /tmp/sftp_shared/sample.txt

Let's verify our setup:

ls -la /tmp/sftp_shared/

Output:

total 12
drwxr-xr-x 3 labex   labex   4096 Sep 28 11:15 .
drwxrwxrwt 4 root    root    4096 Sep 28 11:15 ..
-rw-r--r-- 1 labex   labex     39 Sep 28 11:15 sample.txt
drwxrwxrwx 2 labex   labex   4096 Sep 28 11:15 uploads

With this setup:

  • The main directory is readable and executable by everyone, but only writable by the owner
  • The uploads subdirectory is writable by everyone (suitable for SFTP uploads)
  • The sample.txt file is readable by everyone but only writable by the owner

This configuration allows the SFTP user to:

  • Navigate to the shared directory
  • Read the sample file
  • Upload files to the uploads directory

Solution 4: Using ACLs for More Fine-Grained Control

Access Control Lists (ACLs) provide more detailed permission management. Let's install the necessary package and use ACLs:

sudo apt install -y acl

Now, let's create a file and set specific permissions using ACLs:

echo "This file uses ACLs for permissions" > ~/project/acl_test.txt

## Set basic permissions
chmod 640 ~/project/acl_test.txt

## Add ACL permission for sftpuser
sudo setfacl -m u:sftpuser:r ~/project/acl_test.txt

## View the ACL settings
getfacl ~/project/acl_test.txt

Output:

## file: /home/labex/project/acl_test.txt
## owner: labex
## group: labex
user::rw-
user:sftpuser:r--
group::r--
mask::r--
other::---

This ACL configuration allows:

  • The file owner (labex) to read and write
  • The sftpuser to read the file
  • The group to read the file
  • Others have no access

Best Practices for SFTP Permissions Management

In this final step, we'll cover some best practices for managing SFTP permissions and troubleshooting permission issues effectively.

Creating a Dedicated SFTP User Group

It's a good practice to create a dedicated group for SFTP users:

sudo groupadd sftp_users
sudo usermod -a -G sftp_users sftpuser

Verify that the user was added to the group:

groups sftpuser

Output:

sftpuser : sftpuser sftp_users

Setting Up a Group-Managed Directory

Now let's create a directory that's managed by the sftp_users group:

## Create a new directory for the SFTP group
sudo mkdir -p /tmp/sftp_group_shared
sudo chown labex:sftp_users /tmp/sftp_group_shared
sudo chmod 770 /tmp/sftp_group_shared

## Set the SGID bit to ensure new files inherit the group
sudo chmod g+s /tmp/sftp_group_shared

## Create a test file in this directory
echo "This file is in the SFTP group directory" > /tmp/sftp_group_shared/group_file.txt

Let's verify the permissions:

ls -la /tmp/sftp_group_shared/

Output:

total 12
drwxrws--- 2 labex    sftp_users 4096 Sep 28 11:25 .
drwxrwxrwt 5 root     root       4096 Sep 28 11:25 ..
-rw-rw-r-- 1 labex    sftp_users   42 Sep 28 11:25 group_file.txt

The s in the group permissions indicates the SGID bit is set, which means new files created in this directory will inherit the sftp_users group.

Common Troubleshooting Commands for SFTP Permissions

When troubleshooting SFTP permission issues, these commands are particularly helpful:

  1. Check file permissions:
ls -la /path/to/file
  1. Check user groups:
groups username
  1. Check current user and group IDs:
id
  1. View SFTP server logs:
## In a production system, you would check system logs
## For our lab environment, we can simulate viewing logs
grep "sshd" /var/log/auth.log | tail
  1. Test file access from the command line:
sudo -u sftpuser cat /path/to/file

Permission Denied Error Decision Tree

When you encounter a permission denied error in SFTP, follow this decision tree:

  1. Can the SFTP user access the parent directory?

    • Check with: sudo -u sftpuser ls -la /path/to/directory/
    • Fix with: chmod o+x /path/to/directory/
  2. Can the SFTP user read the file?

    • Check with: sudo -u sftpuser cat /path/to/file
    • Fix with: chmod o+r /path/to/file or setfacl -m u:sftpuser:r /path/to/file
  3. Can the SFTP user write to the file or directory?

    • Check with: sudo -u sftpuser touch /path/to/directory/test_file
    • Fix with: chmod o+w /path/to/directory/ or setfacl -m u:sftpuser:w /path/to/directory/

Creating a Test Script for SFTP Permissions

Let's create a simple test script that checks if the SFTP user can access specific files and directories:

cat > ~/project/check_sftp_permissions.sh << 'EOF'
#!/bin/bash

USER="sftpuser"
echo "Testing SFTP permissions for user: $USER"
echo "-------------------------------------------"

## Test directories
for DIR in /tmp/shared /tmp/sftp_shared /tmp/sftp_group_shared /home/labex/project; do
  echo -n "Can $USER access $DIR? "
  if sudo -u $USER ls -la $DIR &>/dev/null; then
    echo "YES"
  else
    echo "NO"
  fi
done

## Test files
for FILE in /tmp/shared/shared_file.txt /tmp/sftp_shared/sample.txt /home/labex/project/testfile.txt; do
  echo -n "Can $USER read $FILE? "
  if sudo -u $USER cat $FILE &>/dev/null; then
    echo "YES"
  else
    echo "NO"
  fi
done

echo "-------------------------------------------"
echo "Testing complete!"
EOF

chmod +x ~/project/check_sftp_permissions.sh

Now run the test script:

sudo ~/project/check_sftp_permissions.sh

You should see output indicating which directories and files the SFTP user can access. This helps you identify permission issues quickly.

Final Tips for Managing SFTP Permissions

  1. Use the principle of least privilege: Only grant the minimum permissions necessary
  2. Regularly audit permissions: Use tools like find to identify files with inappropriate permissions
  3. Document your permission structure: Keep track of which users and groups have access to which directories
  4. Consider using SFTP chroot jails: For production environments, restrict users to specific directories
  5. Test from the user's perspective: Always verify permissions by testing as the actual SFTP user

Summary

In this tutorial, you have learned how to set up an SFTP server, create users with appropriate permissions, and troubleshoot common permission denied errors. You have gained practical experience with:

  • Installing and configuring an SFTP server on Ubuntu
  • Understanding Linux file permissions and their impact on SFTP access
  • Experiencing and diagnosing permission denied errors
  • Implementing various solutions to resolve permission issues
  • Applying best practices for SFTP permissions management

These skills will help you effectively manage file transfers in a secure environment while minimizing permission-related issues. Remember that proper permission management is essential for maintaining a secure yet functional SFTP server, balancing security requirements with user access needs.