Меню

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

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.

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 14889 times
NAS Setting-4.PNG
NAS Setting-4.PNG (30.37 KiB) Viewed 14889 times
NAS Setting-3.PNG
NAS Setting-3.PNG (25.24 KiB) Viewed 14889 times
NAS Setting-2.PNG
NAS Setting-2.PNG (22.82 KiB) Viewed 14889 times
NAS Setting-1.PNG
NAS Setting-1.PNG (21.92 KiB) Viewed 14889 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 14877 times
FileZilla-1.PNG
FileZilla-1.PNG (13.51 KiB) Viewed 14877 times
NAS Settings.PNG
NAS Settings.PNG (54.45 KiB) Viewed 14877 times
Modem Setting-6.PNG
Modem Setting-6.PNG (16.93 KiB) Viewed 14877 times
Modem Setting-5.PNG
Modem Setting-5.PNG (40.89 KiB) Viewed 14877 times
Modem Setting-4.PNG
Modem Setting-4.PNG (23.04 KiB) Viewed 14877 times
Modem Setting-3.PNG
Modem Setting-3.PNG (62.58 KiB) Viewed 14877 times
Modem Setting-2.PNG
Modem Setting-2.PNG (43.29 KiB) Viewed 14877 times
Modem Setting-1.PNG
Modem Setting-1.PNG (41.94 KiB) Viewed 14877 times


User avatar

boco

Contributor
Posts: 26431
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? 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: 34713
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.


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,3739 gold badges39 silver badges58 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

TL;DR: Configuring vsftp is a difficult work and we always meet various of errors. In this post, I am going to introduce one possible solution of error «GnuTLS error -15: An unexpected TLS packet was received.» when you are using vsftpd.

After finished configuration of vsftpd, we are trying to connect to the ftp server, and then, an error seems as follow:

Status:         Connection established, waiting for welcome message...
Status:         Initializing TLS...
Status:         Verifying certificate...
Status:         TLS connection established.
Command:    USER my_ftp_user
Response:   331 Please specify the password.
Command:    PASS ************
Error:          GnuTLS error -15: An unexpected TLS packet was received.
Error:          Could not connect to server
Status:         Waiting to retry...

It seems like an error in SSL/TLS, but sometimes it isn’t.

Firstly, we may check the configuration of SSL/TLS.

Here is a sample of my configuration , you may check your configruation, and make sure your SSL configuration is correct.

And then, we may comment the lines for SSL temporary, and try to connect again.

As for me, the error message has been changed as follow:

Command:    USER my_ftp_user
Response:   331 Please specify the password.
Command:    PASS ************
Response:   500 OOPS: vsftpd: refusing to run with writable root inside chroot()
Error:          Critical error: Could not connect to server

It is pretty easy to find a solution here , which is adding another line:

allow_writeable_chroot=YES

in somewhere.

Actually, I am just supposed to provide an approach in debugging, if we are meeting some errors similar to «GnuTLS error -15: An unexpected TLS packet was received.», This situation may just tell us one unexpected message comes (always error message), instead of normal TLS package. Temporarily close the SSL may make everything easy.

—- Updated ——

According to this QA you may required to update configure file as follow if you are using ubuntu…

pam_service_name=ftp


Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

Обновлено Обновлено: 23.02.2022
Опубликовано Опубликовано: 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

Если это не помогло, отключите шифрование, закомментировав строку 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

I have an Ubuntu 14.04 on EC2 with vsftpd 3.0.2

I have set up the SSL certs and my vsftpd.conf is:

listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
dirmessage_enable=YES
use_localtime=YES
connect_from_port_20=YES
xferlog_std_format=YES
chroot_local_user=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=vsftpd
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO
ssl_enable=YES
allow_anon_ssl=NO
force_local_data_ssl=NO
force_local_logins_ssl=NO
require_ssl_reuse=NO
debug_ssl=YES
validate_cert=NO
ssl_ciphers=HIGH
pasv_address=[***** public IP ******]
pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048

When connecting from FileZilla using ‘FTP with explicit FTP over TLS’ I get the following:

Status: Resolving address of tcff-ftp.zuriar.net
Status: Connecting to [********]:21...
Status: Connection established, waiting for welcome message...
Response:   220 (vsFTPd 3.0.2)
Command:    AUTH TLS
Response:   234 Proceed with negotiation.
Status: Initializing TLS...
Status: Verifying certificate...
Command:    USER [******]
Status: TLS/SSL connection established.
Response:   331 Please specify the password.
Command:    PASS ************
Response:   230 Login successful.
Command:    OPTS UTF8 ON
Response:   200 Always in UTF8 mode.
Command:    PBSZ 0
Response:   200 PBSZ set to 0.
Command:    PROT P
Response:   200 PROT now Private.
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/"
Command:    TYPE I
Response:   200 Switching to Binary mode.
Command:    PASV
Error:  GnuTLS error -15: An unexpected TLS packet was received.
Error:  Disconnected from server: ECONNABORTED - Connection aborted
Error:  Failed to retrieve directory listing

What is this error message, and how do I fix it? As far as I can tell it is something to do with switching to passive mode… thanks.

I have an Ubuntu 14.04 on EC2 with vsftpd 3.0.2

I have set up the SSL certs and my vsftpd.conf is:

listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
dirmessage_enable=YES
use_localtime=YES
connect_from_port_20=YES
xferlog_std_format=YES
chroot_local_user=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=vsftpd
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO
ssl_enable=YES
allow_anon_ssl=NO
force_local_data_ssl=NO
force_local_logins_ssl=NO
require_ssl_reuse=NO
debug_ssl=YES
validate_cert=NO
ssl_ciphers=HIGH
pasv_address=[***** public IP ******]
pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048

When connecting from FileZilla using ‘FTP with explicit FTP over TLS’ I get the following:

Status: Resolving address of tcff-ftp.zuriar.net
Status: Connecting to [********]:21...
Status: Connection established, waiting for welcome message...
Response:   220 (vsFTPd 3.0.2)
Command:    AUTH TLS
Response:   234 Proceed with negotiation.
Status: Initializing TLS...
Status: Verifying certificate...
Command:    USER [******]
Status: TLS/SSL connection established.
Response:   331 Please specify the password.
Command:    PASS ************
Response:   230 Login successful.
Command:    OPTS UTF8 ON
Response:   200 Always in UTF8 mode.
Command:    PBSZ 0
Response:   200 PBSZ set to 0.
Command:    PROT P
Response:   200 PROT now Private.
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/"
Command:    TYPE I
Response:   200 Switching to Binary mode.
Command:    PASV
Error:  GnuTLS error -15: An unexpected TLS packet was received.
Error:  Disconnected from server: ECONNABORTED - Connection aborted
Error:  Failed to retrieve directory listing

What is this error message, and how do I fix it? As far as I can tell it is something to do with switching to passive mode… thanks.

Hello,

Lots of googling with no solutions to this problem unfortunately and after at least a solid 12 hours trying to solve this i’m loosing it a bit! hmm

Problem already exists here however none of the provided solutions helped and noticed it was already solved after I necrobumped (oops). Also went through at least first 2 pages of search results on google so can’t say I haven’t tried with this one!

As the title describes I am trying to enable SSL on my VSFTPD. I get different errors on different FTP clients however on FileZilla I get the most helpful one:

GnuTLS error -15: An unexpected TLS packet was received

Attemping to mount the FTP server with curlftpfs gives the following error:

Error connecting to ftp: error:1408F10B:SSL routines:ssl3_get_record:wrong version number

.

A lot of sites have suggested that SSL is hiding the actual issue however everything works fine when SSL is disabled.

Here is my vsftpd.conf file:

# Example config file /etc/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
# Allow anonymous FTP? (Beware - allowed by default if you comment this out).
anonymous_enable=NO
#
# Uncomment this to allow local users to log in.
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
write_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
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
#anon_upload_enable=YES
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
#anon_mkdir_write_enable=YES
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# You may override where the log file goes if you like. The default is shown
# below.
#xferlog_file=/var/log/vsftpd.log
#
# 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=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
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
nopriv_user=ftp
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
#ftpd_banner=Welcome to blah FTP service.
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd.banned_emails
#
# 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
#chroot_list_enable=NO
# (default follows)
#chroot_list_file=/etc/vsftpd.chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
# When "listen" directive is enabled, vsftpd runs in standalone mode and
# listens on IPv4 sockets. This directive cannot be used in conjunction
# with the listen_ipv6 directive.
listen=YES
#
# This directive enables listening on IPv6 sockets. To listen on IPv4 and IPv6
# sockets, you must run two copies of vsftpd with two configuration files.
# Make sure, that one of the listen options is commented !!
#listen_ipv6=YES

# Set own PAM service name to detect authentication settings specified
# for vsftpd by the system package.
pam_service_name=vsftpd

ssl_enable=YES

# if you accept anonymous connections, you may want to enable this setting
allow_anon_ssl=NO

# by default all non anonymous logins and forced to use SSL to send and receive password and data, set to NO to allow non secure connections
force_local_logins_ssl=NO
force_local_data_ssl=NO

# TLS v1 protocol connections are preferred and this mode is enabled by default while SSL v2 and v3 are disabled
# the settings below are the default ones and do not need to be changed unless you specifically need SSL
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO

# provide the path of your certificate and of your private key
# note that both can be contained in the same file or in different files
rsa_cert_file=/etc/ssl/certs/vsftpdCertificate.pem
rsa_private_key_file=/etc/ssl/certs/vsftpdServerkey.pem

# this setting is set to YES by default and requires all data connections exhibit session reuse which proves they know the secret of the control channel.
# this is more secure but is not supported by many FTP clients, set to NO for better compatibility
require_ssl_reuse=NO

#ssl_ciphers=AES128-SHA256
ssl_ciphers=HIGH

#pasv_enable=YES
#pasv_min_port=6000
#pasv_max_port=7000
#pasv_address=127.0.0.1

#debug_ssl=YES

In addition the full trace of FileZilla in debug mode:

Trace:	CRealControlSocket::DoClose(66)
Trace:	CControlSocket::DoClose(66)
Trace:	CControlSocket::DoClose(66)
Trace:	CControlSocket::SendNextCommand()
Trace:	CFtpLogonOpData::Send() in state 0
Status:	Connecting to 127.0.0.1:21...
Status:	Connection established, waiting for welcome message...
Trace:	CFtpControlSocket::OnReceive()
Response:	220 (vsFTPd 3.0.3)
Trace:	CFtpLogonOpData::ParseResponse() in state 1
Trace:	CControlSocket::SendNextCommand()
Trace:	CFtpLogonOpData::Send() in state 2
Command:	AUTH TLS
Trace:	CFtpControlSocket::OnReceive()
Response:	234 Proceed with negotiation.
Trace:	CFtpLogonOpData::ParseResponse() in state 2
Status:	Initializing TLS...
Trace:	tls_layer_impl::client_handshake()
Trace:	tls_layer_impl::continue_handshake()
Trace:	TLS handshake: About to send CLIENT HELLO
Trace:	TLS handshake: Sent CLIENT HELLO
Trace:	tls_layer_impl::on_send()
Trace:	tls_layer_impl::continue_handshake()
Trace:	tls_layer_impl::on_read()
Trace:	tls_layer_impl::continue_handshake()
Trace:	tls_layer_impl::on_read()
Trace:	tls_layer_impl::continue_handshake()
Trace:	tls_layer_impl::failure(-15)
Error:	GnuTLS error -15: An unexpected TLS packet was received.
Status:	Connection attempt failed with "ECONNABORTED - Connection aborted".
Trace:	CRealControlSocket::OnSocketError(103)
Trace:	CRealControlSocket::DoClose(66)
Trace:	CControlSocket::DoClose(66)
Trace:	CFtpControlSocket::ResetOperation(66)
Trace:	CControlSocket::ResetOperation(66)
Trace:	CFtpLogonOpData::Reset(66) in state 4
Error:	Could not connect to server
Trace:	CFileZillaEnginePrivate::ResetOperation(66)

Any advise on how to fix this would be greatly appreciated!

Many Thanks

Last edited by doctorzeus (2019-09-27 03:29:24)

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ятрогенная патология врачебные ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка g69 потенциометр дроссельной заслонки