総数:26 今日:1 昨日:1

もくじ

参考URL
How to Setup an SFTP Server on Ubuntu 22.04 using OpenSSH
How To Setup SFTP Server on Ubuntu 22.04 LTS
Linux サーバーに SFTP をインストールして使用する方法

IP固定化しておく

参考url
Ubuntu 22.04 LTS ServerのIPを固定する

192.168.3.9

Install OpenSSH

~$ sudo apt update
~$ sudo apt install openssh-server

View SSH Status

verify that OpenSSH is installed on your system and actively running.
Use the below command and confirm that you see “active (running)” on the third line.

~$ sudo systemctl status ssh
● ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2023-07-19 14:36:02 JST; 40min ago
       Docs: man:sshd(8)
             man:sshd_config(5)
    Process: 764 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
   Main PID: 798 (sshd)
      Tasks: 1 (limit: 18946)
     Memory: 3.8M
        CPU: 34ms
     CGroup: /system.slice/ssh.service
             └─798 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"

 7月 19 14:36:00 OptiPlex-790 systemd[1]: Starting OpenBSD Secure Shell server...
 7月 19 14:36:02 OptiPlex-790 sshd[798]: Server listening on 0.0.0.0 port 22.
 7月 19 14:36:02 OptiPlex-790 sshd[798]: Server listening on :: port 22.
 7月 19 14:36:02 OptiPlex-790 systemd[1]: Started OpenBSD Secure Shell server.

Create New User

create a new user for logging into the SFTP server.

$ sudo adduser sftpuser
ユーザー `sftpuser' を追加しています...
新しいグループ `sftpuser' (1001) を追加しています...
新しいユーザー `sftpuser' (1001) をグループ `sftpuser' に追加しています...
ホームディレクトリ `/home/sftpuser' を作成しています...
`/etc/skel' からファイルをコピーしています...
新しい パスワード: →例)sftpuser と入力した
正しくないパスワード: このパスワードには、一部に何らかの形でユーザー名が含まれています
新しい パスワードを再入力してください: →例)sftpuser と入力した
passwd: パスワードは正しく更新されました
sftpuser のユーザ情報を変更中
新しい値を入力してください。標準設定値を使うならリターンを押してください
	フルネーム []: 
	部屋番号 []: 
	職場電話番号 []: 
	自宅電話番号 []: 
	その他 []: 
以上で正しいですか? [Y/n] Y

Create New Group

create a new group for our sftpuser.
We will configure SSH to give SFTP access to any user in this group.

$ sudo addgroup sftpusers
グループ `sftpusers' (GID 1002) を追加しています...
完了。

Add User to Group

add the user to the new group.
Run the usermod command to add the sftpuser to the sftpusers group.

$ sudo usermod -a -G sftpusers sftpuser

Change User’s Home Permissions

set new permissions on the sftpuser’s home directory.
This will allow the SFTP server to access these files.
First execute the chown command followed by the chmod command.
The sftpuser’s home will be the folder you access when you connect to the SFTP server.

$ sudo chown root:root /home/sftpuser
$ sudo chmod 755 /home/sftpuser

確認

$ ls -la ..|grep -i --color -e "sftpuser"
drwxr-xr-x  2 root root 4096  7月 19 15:28 sftpuser

変更前は下記の状態

drwxr-x---  2 sftpuser sftpuser 4096  7月 19 15:28 sftpuser

sftpユーザの鍵ファイルを準備しておく

あらかじめsftpユーザの鍵ファイルid_rsa_of_sftp_user.pubを準備しておく

sftpユーザの鍵ファイルをセットアップ

$ sudo bash
# cd /home/sftpuser/
# mkdir .ssh
# chown root:root .ssh
# chmod 700 .ssh
# cd .ssh
# cat id_rsa_of_sftp_user.pub >> authorized_keys
# chown root:root authorized_keys
# chmod 600 authorized_keys

確認

# ls -la /home/ | grep -i --color -e "sftpuser"
drwxr-xr-x 15 root root 4096  7月 21 14:55 sftpuser
# ls -la /home/sftpuser/ | grep -i --color -e "ssh"
drwx------  2 root     root     4096  7月 21 14:56 .ssh
# ls -la /home/sftpuser/.ssh/
合計 12
drwx------  2 root root 4096  7月 21 14:56 .
drwxr-xr-x 15 root root 4096  7月 21 14:55 ..
-rw-------  1 root root  410  7月 21 14:56 authorized_keys

Edit the SSH Config File

edit the sshd_config file and edit a few lines.
Open the configuration file using the gvim text editor as shown below.

$ sudo gvim -f /etc/ssh/sshd_config

comment out Subsystem directive

original line 115

Subsystem	sftp	/usr/lib/openssh/sftp-server

modified

#Subsystem	sftp	/usr/lib/openssh/sftp-server

PasswordAuthentication yes のコメントをはずす

original line 58

#PasswordAuthentication yes

modified

PasswordAuthentication yes

Add New Lines at line 116

Subsystem sftp internal-sftp

Match Group sftpusers
     ChrootDirectory /home/%u
     X11Forwarding no
     AllowTCPForwarding no
     ForceCommand internal-sftp

まとめ

$ diff -uprN /etc/ssh/sshd_config_original /etc/ssh/sshd_config
--- /etc/ssh/sshd_config_original	2022-11-23 16:38:19.000000000 +0900
+++ /etc/ssh/sshd_config	2023-07-21 17:14:57.110675372 +0900
@@ -26,6 +26,7 @@ Include /etc/ssh/sshd_config.d/*.conf
 # Logging
 #SyslogFacility AUTH
 #LogLevel INFO
+LogLevel VERBOSE
  
 # Authentication:
 
@@ -54,7 +55,7 @@ Include /etc/ssh/sshd_config.d/*.conf
 #IgnoreRhosts yes
 
 # To disable tunneled clear text passwords, change to no here!
-#PasswordAuthentication yes
+PasswordAuthentication yes
 #PermitEmptyPasswords no
 
 # Change to yes to enable challenge-response passwords (beware issues with
@@ -112,7 +113,14 @@ PrintMotd no
 AcceptEnv LANG LC_*
 
 # override default of no subsystems
-Subsystem	sftp	/usr/lib/openssh/sftp-server
+#Subsystem	sftp	/usr/lib/openssh/sftp-server
+Subsystem sftp internal-sftp
+
+Match Group sftpusers
+     ChrootDirectory /home/%u
+     X11Forwarding no
+     AllowTCPForwarding no
+     ForceCommand internal-sftp
 
 # Example of overriding settings on a per-user basis
 #Match User anoncvs

Restart SSH

$ sudo service ssh restart

Configure the Firewall

configure the firewall using UFW to control access to our SFTP server.
Start by denying all incoming traffic, and allowing all outgoing.

$ sudo ufw default deny incoming
$ sudo ufw default allow outgoing

Allow SSH

There are two options when allowing SSH through the firewall.
You can either allow any IP to access port 22 (not recommended).
Or you can only allow specific IP(s) through the firewall.
I recommend the second option as it offers higher security.

Allow SSH (All IP’s)

If you want to allow any IP, run the following command.

$ sudo ufw allow ssh

Allow SSH (Specific IP’s)

If you want to only allow specific IP’s to access the server,
run the following command for each IP you want to have access.
You need to replace “IP-ADDRESS” with your own IP.
This is highly recommended as it offers the highest level of security.

$ sudo ufw allow from IP-ADDRESS to any port ssh

Enable UFW

After you have allow the IP’s (or everyone) who you want to have access,
you will need to enable UFW. Run the following command.

$ sudo ufw enable

Check Firewall Status

To check the firewall status and verify your configuration.
Check it using the ufw status command.
If you allowed access to only specific IP’s you will see them in the “From” column.

$ sudo ufw status
状態: アクティブ

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere                  
22/tcp (v6)                ALLOW       Anywhere (v6)

ubuntuのSFTPサーバ(SSH)設定で最も重要なこと

適切なパーミッションと所有者の設定です。SSH/SFTPは、権限が緩すぎるとセキュリティ上ログインを拒否(または警告)する仕組みになっています。
以下に重要なポイントと、具体的なアクセス権限のコマンドをまとめました。

重要な所有者・アクセス権のルール

.sshディレクトリと鍵ファイルの権限が正しく設定されていないと、接続エラー(エラーコード: Permission denied など)の原因になります。

ディレクトリ / ファイル所有者(Owner)グループ(Group)アクセス権限(パーミッション)
ホームディレクトリ (~)対象ユーザー対象ユーザー755 または 750
.ssh フォルダ (~/.ssh)対象ユーザー対象ユーザー700 (drwx------)
公開鍵ファイル (authorized_keys)対象ユーザー対象ユーザー600 (-rw-------)
秘密鍵ファイル (id_rsa など)対象ユーザー対象ユーザー600 (-rw-------)

具体的な設定コマンド

SSH/SFTPでログインする対象のユーザーでサーバにログインし、以下のコマンドを実行します。

1. .ssh ディレクトリの作成とパーミッション設定

ディレクトリが存在しない場合は作成し、厳格なアクセス権限を付与します。

# .sshディレクトリの作成
mkdir -p ~/.ssh

# パーミッションを 700 (所有者のみ読み書き実行可能) に変更
chmod 700 ~/.ssh

2. 公開鍵(authorized_keys)の配置と権限設定

手元のPCなどで作成した公開鍵(id_rsa.pub など)をサーバの ~/.ssh/authorized_keys として保存または追記します。

# 権限を 600 (所有者のみ読み取り・書き込み可能) に変更
chmod 600 ~/.ssh/authorized_keys

3. ディレクトリの制限とSSH設定(Chroot)

他のディレクトリへの移動を制限し、SFTP専用のルートディレクトリに閉じ込める(Chroot)場合、親ディレクトリの所有者と権限も重要になります。

SFTP専用ディレクトリ(例: /home/sftpuser/data)を作成する場合の設定例です。

1) chroot 用ディレクトリの所有者を root にする

sudo chown root:root /home/sftpuser
sudo chmod 755 /home/sftpuser

※ホームディレクトリ(sftpuser)の所有者は root にする必要があります。

2) ファイルをアップロードするディレクトリを作成する

sudo mkdir /home/sftpuser/uploads
sudo chown sftpuser:sftpuser /home/sftpuser/uploads
sudo chmod 755 /home/sftpuser/uploads

3) /etc/ssh/sshd_config の設定

SFTPのアクセスを制限するために、設定ファイルの最下部などに以下の記述を追加します。

Match User sftpuser
    ChrootDirectory /home/sftpuser
    ForceCommand internal-sftp
    PasswordAuthentication no
    AllowTcpForwarding no
    X11Forwarding no


設定変更後は、以下のコマンドでSSHサーバを再起動してください。

sudo systemctl restart ssh

その他の注意点

公開鍵のフォーマット:

クライアントソフト(WinSCPやFileZillaなど)で接続する際、Tera Termなどで生成した拡張子が .ssh の鍵はOpenSSH形式と互換性がない場合があります。
OpenSSH形式の鍵(通常は id_rsa と id_rsa.pub)を使用してください。

ログの確認:

接続がうまくいかない場合は、サーバ側のログ(/var/log/auth.log)を確認すると、どこで権限が弾かれているか
(例: Authentication refused: bad ownership or modes for directory など)の詳細が記録されています。


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS