Ошибка gnutls 15 an unexpected tls packet was received

How can I fix this error when I try connecting to the ftp server on filezila:

GnuTLS error -15: An unexpected TLS packet was received.

And this error on sublime ftpsync plugin:

ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1515)

This are my vsftpd settings:

listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
nopriv_user=vsftpd
virtual_use_local_privs=YES
guest_enable=YES
user_sub_token=$USER
local_root=/var/www/$USER
chroot_local_user=YES
hide_ids=YES
guest_username=vsftpd

rsa_cert_file=/etc/ssl/private/vsftpd.pem
rsa_private_key_file=/etc/ssl/private/vsftpd.pem

ssl_enable=YES
allow_anon_ssl=NO
force_local_data_ssl=YES
force_local_logins_ssl=YES

ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO

require_ssl_reuse=NO
ssl_ciphers=HIGH

asked Jun 17, 2015 at 22:55

Francisc I.B's user avatar

I tried adding a line to my configuration file. Open the config here:

sudo nano /etc/vsftpd.conf

And put this line at the bottom:

allow_writeable_chroot=YES

Afterwards, restart the service:

sudo service vsftpd restart

That fix it for me.

answered Jun 18, 2015 at 0:15

Francisc I.B's user avatar

Francisc I.BFrancisc I.B

3411 gold badge2 silver badges9 bronze badges

2

May be you have an error that has no relation with SSL.

  1. Try to deactivate SSL (ssl_enable=NO)
  2. Connect with your favorite FTP client.

Then you probably see the real error.

That’s why the Francisc I.B answer has no relation with SSL.

d a i s y's user avatar

d a i s y

5,3919 gold badges40 silver badges59 bronze badges

answered Nov 23, 2016 at 13:52

Jean-Marc Delafont's user avatar

1

I ran into this same issue. Another thread advises against setting allow_writeable_chroot=YES for security reasons, namely to mitigate a «ROARING BEAST ATTACK».

Setting allow_writeable_chroot=YES means that vsftpd should allow the situation where the user’s home directory is writeable by that user. Instead for security reasons I changed the permissions on the user’s root folder from 777 to 555.

Original: drwxrwxrwx /home/ftpuser/

Changed to: dr-xr-xr-x /home/ftpuser/

This made the user’s home directory NOT writeable by the user and thus I didn’t have to use the allow_writeable_chroot=YES parameter. This is fine (and more secure) for my situation as I have a preset directory structure and don’t want the user making new files or directories in their root folder anyways.

I figured this out when I switched the home directory to /var/ftp via the local_root=[path] parameter for vsftpd and it worked without having to set allow_writeable_chroot=YES. This folder /var/ftp is (755) but owned by root and thus not writeable by ftpuser.

answered Sep 6, 2019 at 19:27

Daystrom75's user avatar

Weirdly for me this issue cropped up when trying to ls after logging in.

It turned out to be that I had uninstalled httpd in favour of nginx and the folder I was using was owned apache:apache and the user got removed when I removed httpd.
I chcon‘d the directories to nginx:nginx and then replaced the user in these lines in my config file:

guest_username=nginx
nopriv_user=nginx

Hopefully this helps someone out there because the error messages weren’t helpful at all.

answered Nov 14, 2018 at 13:27

Elven Spellmaker's user avatar

I found so many confusing answers. I will post an

/etc/vsftpd.conf

that worked flawlessly for me in Ubuntu 18.04 using fileZilla as a client on 2019-09-04. The FTPS is deployed in an EC2 instance regulated by a very strict security group that only allows specific public IPS to access.

# FTPS Shim TLS configuration /etc/vsftpd.conf
# Run standalone?  vsftpd can run either from an inetd or as a standalone
# daemon started from an initscript.
# This directive enables listening on IPv6 sockets. By default, listening
# on the IPv6 "any" address (::) will accept connections from both IPv6
# and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6
# sockets. If you want that (perhaps because you want to listen on specific
# addresses) then you must run two copies of vsftpd with two configuration
# files.
listen=YES
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=NO
listen_port=38250
ftp_data_port=38255
# Allow anonymous FTP? (Disabled by default).
anonymous_enable=NO
# Uncomment this to allow local users to log in.
local_enable=YES
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
local_umask=022
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
# If enabled, vsftpd will display directory listings with the time
# in  your  local  time  zone.  The default is to display GMT. The
# times returned by the MDTM FTP command are also affected by this
# option.
use_localtime=YES
# Activate logging of uploads/downloads.
xferlog_enable=YES
# If you want, you can have your log file in standard ftpd xferlog format.
# Note that the default log file location is /var/log/xferlog in this case.
xferlog_std_format=NO
# You may override where the log file goes if you like. The default is shown below.
xferlog_file=/var/log/vsftpd.log
log_ftp_protocol=YES
debug_ssl=YES
# You may change the default value for timing out an idle session.
idle_session_timeout=600
# You may change the default value for timing out a data connection.
data_connection_timeout=120
# You may fully customise the login banner string:
ftpd_banner=Welcome to Read-Only FTPS Shim service.
# You may restrict local users to their home directories.  See the FAQ for
# the possible risks in this before using chroot_local_user or
# chroot_list_enable below.
chroot_local_user=YES
allow_writeable_chroot=YES
# This option should be the name of a directory which is empty.  Also, the
# directory should not be writable by the ftp user. This directory is used
# as a secure chroot() jail at times vsftpd does not require filesystem
# access.
secure_chroot_dir=/var/run/vsftpd/empty
# This string is the name of the PAM service vsftpd will use.
pam_service_name=ftp
# FTPS Passive Mode. -Define port range for passive mode connections
pasv_enable=Yes
pasv_min_port=10100
pasv_max_port=10110
ssl_enable=YES
# force client to use TLS when logging in
allow_anon_ssl=NO
force_local_data_ssl=YES
force_local_logins_ssl=YES
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO
require_ssl_reuse=NO
ssl_ciphers=HIGH
# specify TSL certificate/private key
rsa_cert_file=/etc/ssl/certs/fullchain.pem
rsa_private_key_file=/etc/ssl/private/privkey.pem
force_local_logins_ssl=YES
force_anon_logins_ssl=YES
# Uncomment this to indicate that vsftpd use a utf8 filesystem.
utf8_filesystem=YES
# Users
userlist_enable=YES
userlist_file=/etc/vsftpd.user_list
userlist_deny=NO

answered Sep 4, 2019 at 3:54

Andre Leon Rangel's user avatar

Moderator: Project members

dryuk94

504 Command not implemented
Posts: 6
Joined: 2020-01-10 15:42
First name: Davide
Last name: Russo

[Solved] GnuTLS error -15: An unexpected TLS packet was received

#1

Post

by dryuk94 » 2020-01-14 11:13

Code: Select all

Status:	Connecting to 3x.xxx.xxx.91:21...
Status:	Connection established, waiting for welcome message...
Status:	Initializing TLS...
Status:	Verifying certificate...
Status:	TLS connection established.
Status:	Logged in
Status:	Retrieving directory listing...
Status:	Server sent passive reply with unroutable address. Using server address instead.
Command:	MLSD
Error:	GnuTLS error -15: An unexpected TLS packet was received.
Error:	The data connection could not be established: ECONNABORTED - Connection aborted

Hello everyone!
Let me explain the problem: I have a Western Digital NAS where I have activated the FTP protocol. If I use a plain TLS connection (without explicit and implicit TLS) I can connect to the server both locally (192.168.1.5) and remotely (3x.xxx.xxx.91). The moment I activate explicit TLS, it connects without problems locally, while remotely I have this error. Attached I also entered the settings of the NAS of the WD and the ports open in the modem. What could be the problem?

Attachments
Modem Setting.PNG
Modem Setting.PNG (15.04 KiB) Viewed 16107 times
NAS Setting-4.PNG
NAS Setting-4.PNG (30.37 KiB) Viewed 16107 times
NAS Setting-3.PNG
NAS Setting-3.PNG (25.24 KiB) Viewed 16107 times
NAS Setting-2.PNG
NAS Setting-2.PNG (22.82 KiB) Viewed 16107 times
NAS Setting-1.PNG
NAS Setting-1.PNG (21.92 KiB) Viewed 16107 times

Last edited by dryuk94 on 2020-01-15 17:48, edited 4 times in total.



dryuk94

504 Command not implemented
Posts: 6
Joined: 2020-01-10 15:42
First name: Davide
Last name: Russo

Re: GnuTLS error -15: An unexpected TLS packet was received

#3

Post

by dryuk94 » 2020-01-14 13:05

boco wrote: ↑

2020-01-14 11:56


Does it work if you select the «Report external IP in PASV mode?

Did you configure the router correctly? Network Configuration

I have selected the «Report external IP in PASV mode» and entered as the IP address «3x.xxx.xxx.91» (the public IPv4 address of the router). This is the result:

Code: Select all

Status:	Connecting to 3x.xxx.xxx.91:21...
Status:	Connection established, waiting for welcome message...
Status:	Initializing TLS...
Status:	Verifying certificate...
Status:	TLS connection established.
Status:	Server does not support non-ASCII characters.
Status:	Logged in
Status:	Retrieving directory listing...
Command:	PWD
Response:	257 "/" is your current location
Command:	TYPE I
Response:	200 TYPE is now 8-bit binary
Command:	PASV
Response:	227 Entering Passive Mode (3x,xxx,xxx,91,234,34)
Command:	MLSD
Error:	GnuTLS error -15: An unexpected TLS packet was received.
Error:	The data connection could not be established: ECONNABORTED - Connection aborted

Attached I enter the settings of the router, NAS and FileZilla Client.

Attachments
FileZilla-3.PNG
FileZilla-3.PNG (6.86 KiB) Viewed 16095 times
FileZilla-1.PNG
FileZilla-1.PNG (13.51 KiB) Viewed 16095 times
NAS Settings.PNG
NAS Settings.PNG (54.45 KiB) Viewed 16095 times
Modem Setting-6.PNG
Modem Setting-6.PNG (16.93 KiB) Viewed 16095 times
Modem Setting-5.PNG
Modem Setting-5.PNG (40.89 KiB) Viewed 16095 times
Modem Setting-4.PNG
Modem Setting-4.PNG (23.04 KiB) Viewed 16095 times
Modem Setting-3.PNG
Modem Setting-3.PNG (62.58 KiB) Viewed 16095 times
Modem Setting-2.PNG
Modem Setting-2.PNG (43.29 KiB) Viewed 16095 times
Modem Setting-1.PNG
Modem Setting-1.PNG (41.94 KiB) Viewed 16095 times


User avatar

boco

Contributor
Posts: 26611
Joined: 2006-05-01 03:28
Location: Germany

Re: GnuTLS error -15: An unexpected TLS packet was received

#4

Post

by boco » 2020-01-14 14:17

The bottom port forwarding in your router is wrong (the 49153-65534).

«Public door» 49153-65534 is correct, but the local port isn’t. If you cannot enter the same port range as in «Public door», but only a single port, enter the first port of the range (49153) and the router will figure out the rest.

Test again. Note that we have a test facility: https://ftptest.net

### BEGIN SIGNATURE BLOCK ###
No support requests per PM! You will NOT get any reply!!!
FTP connection problems? Please do yourself a favor and read Network Configuration.
FileZilla connection test: https://filezilla-project.org/conntest.php
### END SIGNATURE BLOCK ###


dryuk94

504 Command not implemented
Posts: 6
Joined: 2020-01-10 15:42
First name: Davide
Last name: Russo

Re: GnuTLS error -15: An unexpected TLS packet was received

#5

Post

by dryuk94 » 2020-01-14 14:34

boco wrote: ↑

2020-01-14 14:17


The bottom port forwarding in your router is wrong (the 49153-65534).

«Public door» 49153-65534 is correct, but the local port isn’t. If you cannot enter the same port range as in «Public door», but only a single port, enter the first port of the range (49153) and the router will figure out the rest.

Test again. Note that we have a test facility: https://ftptest.net

I changed the port setting:
— local port 49153
— public door 49153-65534

Now I have this error:

Code: Select all

Status:	Connecting to 3x.xxx.xxx.91:21...
Status:	Connection established, waiting for welcome message...
Status:	Initializing TLS...
Status:	Verifying certificate...
Status:	TLS connection established.
Status:	Server does not support non-ASCII characters.
Status:	Logged in
Status:	Retrieving directory listing...
Command:	PWD
Response:	257 "/" is your current location
Command:	TYPE I
Response:	200 TYPE is now 8-bit binary
Command:	PASV
Response:	227 Entering Passive Mode (3x,xxx,xxx,91,213,167)
Command:	MLSD
Error:	The data connection could not be established: ECONNREFUSED - Connection refused by server

Instead from the test facility https://ftptest.net:

Code: Select all

Status: Resolving address of 3x.xxx.xxx.91
Status: Connecting to 3x.xxx.xxx.91
Warning: The entered address does not resolve to an IPv6 address.
Status: Connected, waiting for welcome message...
Reply: 220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
Reply: 220-You are user number 3 of 10 allowed.
Reply: 220-Local time is now 15:27. Server port: 21.
Reply: 220-IPv6 connections are also welcome on this server.
Reply: 220 You will be disconnected after 10 minutes of inactivity.
Command: CLNT https://ftptest.net on behalf of 3x.xxx.xxx.91
Reply: 530 You aren't logged in
Command: AUTH TLS
Reply: 234 AUTH TLS OK.
Status: Performing TLS handshake...
Status: TLS handshake successful, verifying certificate...
Status: Received 1 certificates from server.
Status: cert[0]: subject='CN=192.168.1.5' issuer='CN=192.168.1.5'
Command: USER xxxx
Reply: 331 User xxxx OK. Password required
Command: PASS ***********
Reply: 230 OK. Current restricted directory is /
Command: SYST
Reply: 215 UNIX Type: L8
Command: FEAT
Reply: 211-Extensions supported:
Reply: EPRT
Reply: IDLE
Reply: MDTM
Reply: SIZE
Reply: REST STREAM
Reply: MLST type*;size*;sizd*;modify*;UNIX.mode*;UNIX.uid*;UNIX.gid*;unique*;
Reply: MLSD
Reply: ESTP
Reply: PASV
Reply: EPSV
Reply: SPSV
Reply: ESTA
Reply: AUTH TLS
Reply: PBSZ
Error: Carriage return without line feed received

Results
Error: Carriage return without line feed received
— The replies sent by your server are violating the FTP specifications.
— You have to upgrade to a proper server.


dryuk94

504 Command not implemented
Posts: 6
Joined: 2020-01-10 15:42
First name: Davide
Last name: Russo

Re: GnuTLS error -15: An unexpected TLS packet was received

#6

Post

by dryuk94 » 2020-01-15 11:45

I tried using Cyberduck instead of FileZilla, and was able to connect remotely with Active mode. But I can’t download the files. The moment I try to download a file it gives me an error: 500 — I won’t opean a connection to xxx.xxx.xx.xxx (only to 3x.xxx.xxx.91). Why does Cyberduck connect, instead FileZilla doesn’t? I can only see the folders and files, but I can’t download them(remotely).


dryuk94

504 Command not implemented
Posts: 6
Joined: 2020-01-10 15:42
First name: Davide
Last name: Russo

Re: GnuTLS error -15: An unexpected TLS packet was received

#7

Post

by dryuk94 » 2020-01-15 16:15

I decreased the public port range to 65523-65534. Now I can access the folders remotely from FileZilla, but as soon as I try to download a file it gives me this error:

Code: Select all

Status:	Connecting to 3x.xxx.xxx.91:21...
Status:	Connection established, waiting for welcome message...
Status:	Initializing TLS...
Status:	Verifying certificate...
Status:	TLS connection established.
Status:	Server does not support non-ASCII characters.
Status:	Logged in
Status:	Retrieving directory listing...
Status:	Directory listing of "/" successful
Status:	Disconnected from server
Status:	Connecting to 3x.xxx.xxx.91:21...
Status:	Connection established, waiting for welcome message...
Status:	Initializing TLS...
Status:	Verifying certificate...
Status:	TLS connection established.
Status:	Server does not support non-ASCII characters.
Status:	Logged in
Status:	Starting download of /D-Russo/Desktop/stampa.bollettino.pagamento_rotated.pdf
Command:	CWD /D-Russo/Desktop
Response:	250 OK. Current directory is /D-Russo/Desktop
Command:	PWD
Response:	257 "/D-Russo/Desktop" is your current location
Command:	TYPE I
Response:	200 TYPE is now 8-bit binary
Command:	PASV
Response:	227 Entering Passive Mode (3x,xxx,xxx,91,255,249)
Command:	RETR stampa.bollettino.pagamento_rotated.pdf
Error:	The data connection could not be established: ECONNREFUSED - Connection refused by server
Error:	Connection timed out after 20 seconds of inactivity
Error:	File transfer failed

Instead with WinSCP I have this error:

Code: Select all

Failed to get the folder list
I won't open a connection to 192.168.1.8 (only to 3x.xxx.xxx.91)


dryuk94

504 Command not implemented
Posts: 6
Joined: 2020-01-10 15:42
First name: Davide
Last name: Russo

Re: GnuTLS error -15: An unexpected TLS packet was received

#8

Post

by dryuk94 » 2020-01-15 17:48

Problem solved!
I had to assign a number of ports equal to the number of users that can be connected (10). Also I created port forwarding in the router for each port and not an interval. The connection is in passive mode and I can also download the files.


User avatar

botg

Site Admin
Posts: 34948
Joined: 2004-02-23 20:49
First name: Tim
Last name: Kosse
Contact:

Re: [Solved] GnuTLS error -15: An unexpected TLS packet was received

#9

Post

by botg » 2020-01-16 08:40

As a rule of thumb you need at least as many ports as transfers that can possibly be done in 4 minutes.


I am posting this answer in hopes that it might help someone in the future, possibly me, as I suffered solving this problem.

I did not have local_root in the /etc/vsftpd/vsftpd.conf file set properly. The setting pointed to a folder, which did not exist.

What through me was that I saw the failure on the password command in FileZilla, so I thought that it did not like the password. What got me thinking in the right direction was that I took the time to research why I was not receiving detailed logs. I received no logs. Once I started receiving debug logs, where I saw the FTP protocols, I saw that the FTP server said OK to the password. Sadly, there was no logging of any kind, but I came across the thought that negotiating the local root would be the next course of action after authenticating the password. I was right and that led me to the problem.

Here is the code fragment in the /etc/vsftpd/vsftpd.conf file, containing the local root.

# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
# (Warning! chroot'ing can be very dangerous. If using chroot, make sure that
# the user does not have write access to the top level directory within the
# chroot)
chroot_local_user=YES
#local_root=/mnt/raid1
local_root=/ftproot
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd/chroot_list

Here is how I finally turned on verbose logging, though I will turn that off now to conserve disk space and improve performance.

# Activate logging of uploads/downloads.
xferlog_enable=YES
#
# If you want, you can have your log file in standard ftpd xferlog format.
# Note that the default log file location is /var/log/xferlog in this case.
xferlog_std_format=NO
log_ftp_protocol=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES

IMHO, I would consider the comment a bug, as xferlog_enable is more than the actual upload and download of files. This property also turns on logging. A Google research proves that log_ftp_protocol=YES requires xferlog_enable=YES.


0

1

Всем здравствуйте!
На Centos 7 решил настроить ftps. Но при попытке подключиться через Filezilla получаю ошибку — GnuTLS -15: An unexpected TLS packet was received.
Это из-за библиотеки GnuTLS на сервере?
Это вижу при подключении:

Трассировка:	CControlSocket::SendNextCommand()
Трассировка:	CFtpLogonOpData::Send() in state 0
Статус:	Определение IP-адреса для мой_домен
Статус:	Соединяюсь с мой_айпи:21...
Статус:	Соединение установлено, ожидание приглашения...
Трассировка:	CFtpControlSocket::OnReceive()
Ответ:	220 (vsFTPd 3.0.2)
Трассировка:	CFtpLogonOpData::ParseResponse() in state 1
Трассировка:	CControlSocket::SendNextCommand()
Трассировка:	CFtpLogonOpData::Send() in state 2
Команда:	AUTH TLS
Трассировка:	CFtpControlSocket::OnReceive()
Ответ:	234 Proceed with negotiation.
Трассировка:	CFtpLogonOpData::ParseResponse() in state 2
Статус:	Инициализирую TLS...
Трассировка:	CTlsSocketImpl::Handshake()
Трассировка:	CTlsSocketImpl::ContinueHandshake()
Трассировка:	CTlsSocketImpl::ContinueHandshake()
Трассировка:	CTlsSocketImpl::ContinueHandshake()
Трассировка:	CTlsSocketImpl::ContinueHandshake()
Трассировка:	TLS Handshake successful
Трассировка:	Protocol: TLS1.2, Key exchange: ECDHE-RSA, Cipher: AES-128-CBC, MAC: SHA1
Статус:	Проверка сертификата...
Статус:	TLS соединение установлено.
Трассировка:	CControlSocket::SendNextCommand()
Трассировка:	CFtpLogonOpData::Send() in state 5
Команда:	USER мой_юзер
Трассировка:	CFtpControlSocket::OnReceive()
Ответ:	331 Please specify the password.
Трассировка:	CFtpLogonOpData::ParseResponse() in state 5
Трассировка:	CControlSocket::SendNextCommand()
Трассировка:	CFtpLogonOpData::Send() in state 5
Команда:	PASS ************
Ошибка:	Ошибка GnuTLS -15: An unexpected TLS packet was received.
Трассировка:	CRealControlSocket::OnClose(106)
Трассировка:	CFtpControlSocket::ResetOperation(66)
Трассировка:	CControlSocket::ResetOperation(66)
Ошибка:	Невозможно подключиться к серверу

Это уже мои настройки?

ssl_enable=YES
allow_anon_ssl=NO
force_local_data_ssl=YES
force_local_logins_ssl=YES

rsa_cert_file=/etc/ssl/private/vsftpd.pem
rsa_private_key_file=/etc/ssl/private/vsftpd.pem

ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO

Спасибо!

Обновлено Обновлено: 20.05.2023
Опубликовано Опубликовано: 27.03.2017

Термины по теме: FTP, CentOS

На текущий момент есть две удачные реализации FTP-сервера для Linux: vsFTPd и proFTPd. В данной инструкции речь пойдет о первом, так как его актуальная версия более свежая, в то время, как последняя версия proFTPd выпущена в 2013 году.

Установка и настройка
vsFTPd через TLS
Виртуальные пользователи
Хранение пользователей в БД
Возможные проблемы
SFTP
FTP-клиент

Установка и базовая настройка vsFTPd

Обновляем систему:

yum update

Запускаем процесс установки:

yum install vsftpd

После открываем на редактирование следующий файл:

vi /etc/vsftpd/vsftpd.conf

И приводим его к следующему виду:

anonymous_enable=NO
chroot_local_user=YES

allow_writeable_chroot=YES
pasv_min_port=40900
pasv_max_port=40999

* первые две строчки мы редактируем: anonymous_enable разрешает подключение анонимных пользователей, поэтому мы отключаем такую возможность; chroot_local_user запрещает выход за пределы домашней директории пользователя. Третью, четвертую и пятую строки мы дописываем — allow_writeable_chroot разрешает подключения пользователю, у которого есть права на запись в корневую директорию; это диапазон динамических портов, которые будут использоваться vsFTPd. Данный диапазон важно указывать, если используется брандмауэр. Сам диапазон можно задать любой из незарегистрированных портов.

Отключаем SELinux следующими командами:

setenforce 0

sed -i «s/SELINUX=enforcing/SELINUX=disabled/» /etc/selinux/config

* первая команда отключит SELinux, вторая — отключит его автозапуск после перезагрузки.

Добавляем правила в брандмауэр для корректной работы FTP-сервера:

firewall-cmd —permanent —add-port=20-21/tcp

firewall-cmd —permanent —add-port=40900-40999/tcp

firewall-cmd —reload

Разрешаем автозапуск vsFTPd и запускаем его:

systemctl enable vsftpd

systemctl start vsftpd

По умолчанию, к vsFTPd нельзя подключиться с использованием учетной записи root. Поэтому нужно использовать другую пользовательскую запись или создать новую следующей командой:

useradd ftpuser -d /var/www -s /sbin/nologin

ftpuser — имя учетной записи; /var/www — домашняя директория; /sbin/nologin запрещает локальный вход в систему.

Задаем пароль новому пользователю:

passwd ftpuser

Базовая настройка закончена — можно пробовать подключаться к FTP-серверу.

vsFTPd через TLS

TLS позволяет настроить безопасный FTP, передача данных через который осуществляется по зашифрованному каналу.

Для начала создаем сертификат:

openssl req -new -x509 -days 1461 -nodes -out /etc/vsftpd/vsftpd.pem -keyout /etc/vsftpd/vsftpd.key -subj «/C=RU/ST=SPb/L=SPb/O=Global Security/OU=IT Department/CN=test.dmosk.local/CN=test»

* в данном примере мы создаем самоподписный сертификат на 4 года для URL test.dmosk.local или test. В итоге, мы получим 2 ключа — открытый PEM и закрытый KEY.
** самоподписанный сертификат лучше использовать для тестовой настройки. Для продуктивной среды лучше купить сертификат или получить бесплатный от Let’s Encrypt.

Открываем на редактирование конфигурационный файл vsFTPd:

vi /etc/vsftpd/vsftpd.conf

И дописываем в него следующее:

ssl_enable=YES
allow_anon_ssl=NO
force_local_data_ssl=NO
force_local_logins_ssl=NO
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO
rsa_cert_file=/etc/vsftpd/vsftpd.pem
rsa_private_key_file=/etc/vsftpd/vsftpd.key

* где:

  • ssl_enable разрешает использование шифрования.
  • allow_anon_ssl разрешает использовать SSL анонимным пользователям.
  • force_local_data_ssl требует использования шифрования, и если установить.
  • YES, клиенты без шифрования не смогут подключиться.
  • force_local_logins_ssl также требует подключение по SSL.
  • ssl_tlsv1 — использовать TLS версии 1.
  • ssl_sslv2 — использовать SSL версии 2.
  • ssl_sslv3 — использовать SSL версии 3.
  • rsa_cert_file — путь к сертификату с открытым ключом.
  • rsa_private_key_file — путь к сертификату с закрытым ключом.

Перезапускаем FTP-сервер:

systemctl restart vsftpd

Готово.

Виртуальные пользователи

Устанавливаем пакет compat-db:

yum install compat-db

На всякий случай, сохраняем pam файл для авторизации vsftpd:

mv /etc/pam.d/vsftpd /etc/pam.d/vsftpd.back

Создаем новый файл со следующим содержимым:

vi /etc/pam.d/vsftpd

auth required pam_userdb.so db=/etc/vsftpd/virtual_users
account required pam_userdb.so db=/etc/vsftpd/virtual_users
session required pam_loginuid.so

* где /etc/vsftpd/virtual_users — файл, в котором мы будем хранить пользователей.

Открываем конфигурационный файл сервера FTP:

vi /etc/vsftpd/vsftpd.conf

И добавляем следующее:

guest_enable=YES
guest_username=ftp
virtual_use_local_privs=YES
user_sub_token=$USER
local_root=/home/$USER

* где guest_enable разрешает виртуальных пользователей; guest_username — имя системной учетной записи, от которой работаю виртуальные пользователи; virtual_use_local_privs — виртуальные пользователи с такими же привилегиями, что и локальные; user_sub_token — имя учетной записи храниться в переменной $USER; local_root задает домашнюю директорию виртуальному пользователю.

Создаем файл с виртуальными пользователями со следующим содержимым:

vi /etc/vsftpd/virtual_users

ftp1
passwd1
ftp2
passwd2

* где ftp1 и ftp2 — логины; passwd1 и passwd2 — пароли.

Сразу генерируем из файла базу:

db_load -T -t hash -f /etc/vsftpd/virtual_users /etc/vsftpd/virtual_users.db

Необходимо убедиться, что для пользователей есть соответствующие домашние директории:

mkdir /home/ftp{1,2}

И также у системной учетной записи есть соответствующие права:

chown -R :ftp /home/ftp{1,2}

Перезапускаем сервис:

systemctl restart vsftpd

Хранение пользователей в базе данных

В качестве базы данных можно использовать MySQL или MariaDB. В данном примере будет использоваться последняя.

Устанавливаем СУБД следующей командой:

yum install mariadb mariadb-server

Разрешаем автозапуск и запускаем сервис:

systemctl enable mariadb

systemctl start mariadb

Задаем пароль для пользователя root:

mysqladmin -u root password

Запускаем командную оболочку mariadb:

mysql -p

Создаем базу данных и пользователя с правами только на выборку данных:

> CREATE DATABASE vsftpd;

> GRANT SELECT ON vsftpd.* TO ‘vsftpd’@’localhost’ IDENTIFIED BY ‘passwordftp’;

* где vsftpd.* разрешает доступ на все таблицы базы vsftpd; ‘vsftpd’@’localhost’ — учетная запись, у которой есть право подключаться только с локального сервера; passwordftp — пароль для подключения.

Подключаемся к созданной базе и создаем таблицу:

> USE vsftpd;

> CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 30 ) NOT NULL ,
`password` VARCHAR( 50 ) NOT NULL ,
UNIQUE (`username`)
) ENGINE = MYISAM ;

Теперь добавим пользователя:

> INSERT INTO users (username, password) VALUES(‘ftpm1’, md5(‘password’));

* где ftpm1 — логин, password — пароль.

Выходим из оболочки mariadb:

> q

Устанавливаем модуль pam_mysql:

rpm -Uvh ftp://ftp.pbone.net/mirror/archive.fedoraproject.org/fedora/linux/releases/20/Everything/x86_64/os/Packages/p/pam_mysql-0.7-0.16.rc1.fc20.x86_64.rpm

Сохраняем копию pam файла:

mv /etc/pam.d/vsftpd /etc/pam.d/vsftpd.back

Создаем новый и приводим его к следующему виду:

vi /etc/pam.d/vsftpd

session optional pam_keyinit.so force revoke
auth required pam_mysql.so user=vsftpd passwd=passwordftp host=localhost db=vsftpd table=users usercolumn=username passwdcolumn=password crypt=3
account required pam_mysql.so user=vsftpd passwd=passwordftp host=localhost db=vsftpd table=users usercolumn=username passwdcolumn=password crypt=3

* где user=vsftpd passwd=passwordftp — логин и пароль для подключения к базе данных; db=vsftpd table=users — имя созданной базы данных и таблицы с пользователями; usercolumn=username passwdcolumn=password — название полей, из которых извлекаем логины и пароли для FTP-пользователей.

Настройка завешена, пробуем подключиться.

Возможные проблемы

Ошибка GnuTLS -15: An unexpected TLS packet was received

Ошибка возникает в том случае, когда у учетной записи, от которой идет подключения есть права на запись в корневую домашнюю директорию, а также используется безопасное соединение через TLS. В vsFTPd, по умолчанию, это приводит к ошибке.

Для решения проблемы воспользуйтесь любым из способов:

1. Убираем права на запись для корневой директории, например: chmod a-w /var/www

2. В конфигурационном файле vsftpd добавляем следующую строку:
allow_writeable_chroot=YES

3. Иногда, ошибка возникает, когда сервер работает на порту sftp (990 и 989). При смене портов на стандартные (21 и 20) подключение заработало. При этом не стоит переживать, что порты не sftp — при включенной опции ssl_enable=YES соединение будет с шифрованием.

Если ничего из вышеописанного не помогло, отключите шифрование, закомментировав строку ssl_enable=YES. После этого, при подключении будут появляться более информативные сообщения.

500 OOPS: vsftpd: refusing to run with writable root inside chroot()

Аналогично ошибке, описанной выше, возникает в том случае, когда у учетной записи, от которой идет подключения есть права на запись в корневую домашнюю директорию. В vsFTPd, по умолчанию, это приводит к ошибке.

Для решения проблемы воспользуйтесь любым из способов:

  1. Убираем права на запись для корневой директории, например: chmod a-w /var/www
  2. В конфигурационном файле vsftpd добавляем следующую строку:
    allow_writeable_chroot=YES

500 OOPS: cannot change directory:/…

Не существует директории или нет прав на чтение.

Проверьте правильность настроек и то, что директория, действительно существует.

SFTP как альтернатива FTP

Если необходимо разово перенести на сервер данные, можно обойтись протоколом SSH File Transfer Protocol или SFTP. Все, что для этого нужно — доступ по SSH и программа клиент, например, WinSCP.

FTP-клиент на CentOS

Для более удобной проверки настроек можно установить FTP-клиент прямо на сервер и с его помощью выполнять подключения.

Для этого выполняем установку клиента:

yum install ftp

И подключаемся к нашему серверу командой:

ftp localhost

Вводим логин и пароль, которые будут запрошены. После подключения мы увидим следующее:

Trying ::1…
Connected to localhost (::1).
220 (vsFTPd 3.0.2)
Name (localhost:root): ftpm1
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>

Для теста можно загрузить файл на сервер FTP:

> put testfile.txt

* сам файл должен быть в каталоге, в котором мы были перед подключение к серверу FTP.

Если мы получим ошибку 500 active mode is disabled, use passive mode instead, просто переключаемся в пассивный режим:

> passive

Понравилась статья? Поделить с друзьями:
  • Ошибка generals zero hour 8a 5 0945
  • Ошибка glfw error 65542 при запуске майнкрафт
  • Ошибка generals you have encountered a serious error
  • Ошибка glfw 65542 wgl драйвер не поддерживает opengl майнкрафт
  • Ошибка general protection fault при запуске splinter cell