Vsftpd ошибка не удалось получить список каталогов


14.01.2023 admin   

0

vsftpd  установлен на сервере на сервере за NAT («внешний» IP отличается от «внутреннего» на сетевом интерфейсе). После базовой настройки все вроде бы работает, но при соединении по FTP  дело доходит до 

...

Команда: PASV
Ответ: 227 Entering Passive Mode (100,70,68,1,47,5).
Команда: LIST
Ошибка: Соединение прервано после 20 секунд неактивности
Ошибка: Не удалось получить список каталогов
Статус: Отключен от сервера

Для устранения ошибки добавляем в конфиг vsftpd (обычно, /etc/vsftpd.conf) строки

pasv_address=_EXTERNAL_IP
write_enable=YES
pasv_enable=YES
chroot_local_user=YES

где, EXTERNAL_IP — внешний IP сервера за NAT

и перезапускаем vsftpd 

systemctl restart vsftpd


Нет комментариев

Something is really not working here. I have the following error in using FileZilla to connect to a remote machine running vsftpd:

Command:    LIST
Error:  Connection timed out
Error:  Failed to retrieve directory listing

I am trying to set up FTP services on 3 machines behind a residential ISP firewall. All are Ubuntu 12.04 Server LTS, and I am restricted from using port 21 externally at the remote site.

Well.. Ok, I confess, it’s myself who is imposing the restriction. I just wanted to sound like I was working for a real company. Anyway, only 1 of the 3 systems could have been assigned to 21, so it would still be an issue.

I have tried the solutions for adding «pasv_…» lines, but I still cannot get past the LIST stage of connecting.

  • https://stackoverflow.com/questions/4723023/vsftpd-error-listing-directories
  • http://www.linuxquestions.org/questions/linux-server-73/vsftpd-error-failed-to-retrieve-directory-listing-878838/
  • https://serverfault.com/questions/421161/how-to-configure-vsftpd-to-work-with-passive-mode
  • http://www.linuxquestions.org/questions/linux-networking-3/vsftpd-cannot-list-files-but-can-change-dirs-519340/

So, having failed that, what might the problem be?

I read on this site that I need to forward ports 20 and 21. Right now the remote sites have ports like 10000, 11000, 12000 forwarded to the internal port 21 on each of the systems. Should I forward some additional ports in to 20? it doesn’t make sense because that port isn’t even open, vsftpd is only listening on 21.

All I want is for a successful ftp connection through these forwarded ports, I am frustrated because I have successfully forwarded for services like SSH, apache2, etc and I don’t get what is broken here.

thx Joren for correcting my formatting!


EDIT: I have been messing around with my testing VPS which is directly exposed to the internet, I installed vsftpd just to see what happens, and the output of ‘netstat -tuna’ shows that a successful connection from my filezilla client looks like this:

tcp        0      0 vps.vps.vps.vps:21       fi.le.zil.la:54288      ESTABLISHED
tcp        0      0 vps.vps.vps.vps:46403    fi.le.zil.la:54289      TIME_WAIT

Note: the FTP server at my VPS also didn’t work at first, due to a completely unrelated issue involving virtualized environments («500 OOPS: priv_sock_get_cmd»). Read: I am starting to see that Ubuntu’s vsftpd doesn’t work ‘out-of-the-box’ like apache2 and sshd do, for any frustrated novice sysadmins out there, don’t think you’re stupid if it isn’t working first thing…

My testing VPS doesn’t have a firewall, so all ports are directly available for access by the FTP daemon. After running this test, I see that it is possible that this secondary connection is being blocked at the remote site where I’m having issues (random ports such as 46403).

At least now I have confirmed that there are no NAT issues with my Filezilla, because clearly filezilla is opening random ports and talking with my VPS ok.

The one thing that makes no sense, is the config ‘connect_from_port_20=YES’ is set on my VPS FTP config, yet I can’t see any connections using port 20!!! This is why I don’t even know if this port needs to be forwarded behind a firewall.

One of my knowledge deficiencies is I don’t even know what port 20 does, and I can’t learn through experience because I’ve never seen any indication the port is ever used duing connecting, downloading or uploading.


OK, I found some problems (there’s clearly more then one thing wrong) — This has to do with port forwarding.

Suspect original problem (before customizing vsftpd.conf)

  1. Filezilla initially connects to remote port 10000, ==> goes to 21 on internal FTP server (ok)
  2. FTP server opens a random port (NOT 20) like 45678, but the router obviously doesn’t have a rule for this randomly assigned port. It sends a message telling filezilla to also connect to 45678.
  3. Filezilla client opens up its own port on my end behind NAT(ok)
  4. Filezilla sends connection request to 45678, but the remote router doesn’t accept the connection, as there is no forwarding rule for that port.

Now, the problem(s) I created:

pasv_enable=YES
pasv_min_port=10000
pasv_max_port=10000
  1. Filezilla connects to remote port 10000, ==> goes to 21 on internal FTP server (ok)
  2. FTP server opens the only port it can, 10000, [stupid moment] because I have that port in my head associated with that system. But 10000 is actually the WAN side counterpart for 21 on this system. Server sends a message for FileZilla to connect to 10000, and listens internally on 10000
  3. Filezilla client opens up its own random port on my end (ok)
  4. Filezilla tries the secondary connection at port 10000, the remote router deflects it to port 21 again where it must be ignored or lost, while the FTP server waits for a connection to internal port 10000 that never arrives. (fail)

Second problem I created: I tried to bind port 21 this time, but I think that messed up filezilla.

pasv_enable=YES
pasv_min_port=21
pasv_max_port=21
  1. Filezilla connects to remote port 10000, ==> goes to 21 on internal FTP server (ok)
  2. FTP server opens port 21 (or maybe fails because 21 is already used) if it succeeded, it sent a message for filezilla to connect to port 21.
  3. Filezilla client opens up its own random port on my end (ok)
  4. Filezilla sends a request for LIST to 21, which the router is not going to accept…(fail)

Conclusion: as long as the port is being changed by a router, the FTP server will never be able to tell the client to connect to the right port. If you try to use the internal port, the client will run up against the router. If you try to specifiy the external port, the router will deflect the incoming connection to a different number — which the server was not expecting.


I will test a solution and report back here with the results.

I think, because the FTP server protocol appears to tell the client which port to connect to, that secondary connection MUST have the same external port number as internal.

I will call this a ‘secondary connection’ and I think it has something to do with the port 20 thing that I don’t understand.

So, I will contact the remote site and have an additional port forwarded directly, so the FTP server can open a connection internally, and the client will be able to send a connection request to that exact port number.

New plan:

(note: the ‘%’ is meant to show the port getting changed by the remote router.)

 

server #1
    primary connection: 21 <--%--> 10000 
    secondary connection 10001 <-----> 10001
    vsftp.conf:
        pasv_min_port=10001
        pasv_max_port=10001

server #2
    primary connection 21 <--%--> 11000
    secondary connection 11001 <-----> 11001
    vsftp.conf:
        pasv_min_port=11001
        pasv_max_port=11001

server #3
    primary connection 21 <--%--> 12000
    secondary connection 12001 <-----> 12001
    vsftp.conf:
        pasv_min_port=12001
        pasv_max_port=12001

I installed vsftpd on amazon ec2 with fedora instance and it is the latest version but I am getting the error:
In CuteFTP:

COMMAND:> PASV 227 Entering Passive Mode (192,168,10,46,14,20)
COMMAND:> LIST
ERROR:> Can’t connect to remote server. Socket error = #10065.
ERROR:> PASV failed, trying PORT.

In Filezilla:

Command: PASV Response: 227 Entering Passive Mode (192,168,10,46,14,20)
Command: LIST Error: Connection timed out
Error: Failed to retrieve directory listing.

Trying to Connect thro’ Shell and showing me list of directories.

Alfred Huang's user avatar

Alfred Huang

17.7k32 gold badges118 silver badges189 bronze badges

asked Jan 18, 2011 at 10:33

onkar's user avatar

Just had this same exact issue… this typically only affects GUI ftp clients that use a passive mode (which is pretty common). For instance, when using the standard ftp command line tool, I was able to successfully login and upload files to my ftp server.

The steps to correct are:

  1. Add the following settings to your /etc/vsftpd.conf file:

    pasv_enable=YES
    pasv_min_port=64000
    pasv_max_port=64321
    port_enable=YES

  2. Also add one of the following config chunks to your /etc/vsftpd.conf file, based on your situation (either way, this needs to resolve to a public accessible IP):

a:

pasv_address=<your-static-ip-most-likely-from-elastic-ips>
pasv_addr_resolve=NO

-OR-

b:

pasv_address=<your-publicly-resolvable-host-name>
pasv_addr_resolve=YES
  1. In your security group configuration for ec2 instances, add the following custom inbound tcp rules:
  • Enable ports 20-21 for standard ftp
  • Enable your passive ports as defined in the config sections above (I used 64000-64321)
  1. Restart your vsftpd service (varies depending on your flavor of linux)

Note: pasv port range should be visible outside from the firewall, NAT

References for more info:

  • http://www.adrianworlddesign.com/Knowledge-Base/Web-Hosting/Amazon-Web-Services/Enable-FTP-in-EC2
  • http://www.synergycode.com/knowledgebase/blog/item/ftp-server-on-amazon-ec2
  • https://www.gosquared.com/blog/fix-ftp-passive-mode-problems-on-amazon-ec2-instances

Elon Zito's user avatar

Elon Zito

2,8721 gold badge24 silver badges28 bronze badges

answered Aug 7, 2012 at 0:07

longda's user avatar

longdalongda

10.2k7 gold badges46 silver badges66 bronze badges

3

With version vsftpd-3.0.2-1.el5.x86_64.rpm for me helped the following settings:

pasv_enable=YES
pasv_min_port=64000
pasv_max_port=64321
port_enable=YES
pasv_address=<your-static-ip-most-likely-from-elastic-ips>
pasv_addr_resolve=NO

Thanks to the longda!

answered Sep 23, 2014 at 12:43

Alex's user avatar

This work for me;

Below is configuration in /etc/vsftpd.conf

listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
xferlog_file=/var/log/vsftpd.log
xferlog_std_format=YES
chroot_local_user=YES
allow_writeable_chroot=YES
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list
pam_service_name=ftp
pasv_enable=YES
pasv_min_port=13000
pasv_max_port=13100
port_enable=YES
pasv_address=AWS-IP-Address
pasv_addr_resolve=no

SAVE and Restart the service

$ sudo service vsftpd restart

Open below ports in security group

  • custom TCP 20 from 0.0.0.0/0
  • custom TCP 21 from 0.0.0.0/0
  • custom TCP 13000 from 0.0.0.0/0
  • custom TCP 13100 from 0.0.0.0/0

You may get below error while connecting from FileZilla FTP client;

Error:  Connection timed out
Error:  Failed to retrieve directory listing

To resolve this;

  • Open Filezilla, go to Edit -> Settings
  • Click on Connection -> FTP: Choose Active
  • Click on Connection -> FTP -> Active Mode: Select «Ask your operating
    system for the external IP address»
  • Click on Connection -> FTP -> Passive Mode: Choose Fall Back to
    Active Mode Press OK.

Try connecting to your FTP site once again.

Tunaki's user avatar

Tunaki

133k46 gold badges342 silver badges424 bronze badges

answered Apr 24, 2016 at 13:50

Pramod Waikar's user avatar

answered Feb 3, 2011 at 13:27

Bucho's user avatar

BuchoBucho

291 bronze badge

1

You want to use passive mode if possible. As I said in the article Bucho linked to, you just have to define a port range for PASV mode and open that range in your EC2 security group

answered Nov 17, 2011 at 18:37

TheDeveloper's user avatar

if some configuration like below in vsftpd.conf:

pasv_enable=YES
pasv_min_port=64000
pasv_max_port=64321

try to open firewall:

# yum install -y epel-release
# yum install -y ufw
# sudo ufw allow from any to any proto tcp port 64000:64321

sudo iptables -A INPUT -p tcp –dport 64000:64321 -j ACCEPT

answered Oct 16, 2019 at 10:01

sailfish009's user avatar

sailfish009sailfish009

2,5611 gold badge24 silver badges31 bronze badges


0

1

Добрый день!

Никак не могу понять, в чём дело. С отключенным шифрованием фтп работает корректно, но если его включить, то сервер не отвечает на команду LIST. VSFTPD крутится на Redhut 6.

Вот лог файлзиллы:

Статус: Определение IP-адреса для ftp://ftp.xxx.ru

Статус: Соединяюсь с xxx.xxx.xxx.xxx:21…

Статус: Соединение установлено, ожидание приглашения…

Статус: Инициализирую TLS…

Статус: Проверка сертификата…

Статус: TLS соединение установлено.

Статус: Соединение установлено

Статус: Получение списка каталогов…

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

Команда: LIST

Ошибка: Соединение передачи данных не может быть установлено: ETIMEDOUT — Превышено время ожидания соединения

Ответ: 425 Failed to establish connection.

Ошибка: Не удалось получить список каталогов

————

конфиг:

anonymous_enable=NO

local_enable=YES

write_enable=YES

local_umask=022

dirmessage_enable=YES

xferlog_enable=YES

vsftpd_log_file=/var/ftp/vsftpd.log

syslog_enable=NO

log_ftp_protocol=YES

connect_from_port_20=YES

xferlog_file=/var/log/xferlog

xferlog_std_format=YES

dual_log_enable=YES

listen=YES

pam_service_name=vsftpd

userlist_enable=YES

#tcp_wrappers=YES

pasv_min_port=13450

pasv_max_port=13500

chmod_enable=NO

local_max_rate=102400

delete_failed_uploads=YES

dirlist_enable=YES

hide_ids=YES

log_ftp_protocol=YES

chroot_local_user=YES

rsa_cert_file=/etc/ssl/private/vsftpd_rsa.pem

ssl_enable=YES

ssl_tlsv1=YES

ssl_sslv2=NO

ssl_sslv3=NO

ssl_ciphers=HIGH

require_ssl_reuse=NO

pasv_enable=YES

debug_ssl=YES

Что-то здесь действительно не работает. У меня есть следующая ошибка при использовании FileZilla для подключения к удаленной машине, работающей vsftpd:

Command:    LIST
Error:  Connection timed out
Error:  Failed to retrieve directory listing

Я пытаюсь настроить службы FTP на 3 компьютерах за домашним брандмауэром интернет-провайдера. Все они являются Ubuntu 12.04 Server LTS, и я не могу использовать порт 21 извне на удаленном сайте.

Ну, ладно, признаюсь, это ограничение накладывает я сам. Я просто хотел звучать так, будто я работаю в настоящей компании. В любом случае, только 1 из 3 систем могла быть назначена 21, так что это все равно будет проблемой.

Я пробовал решения для добавления строк «pasv _…», но я все еще не могу пройти этап подключения LIST.

  • https://stackoverflow.com/questions/4723023/vsftpd-error-listing-directories
  • http://www.linuxquestions.org/questions/linux-server-73/vsftpd-error-failed-to-retrieve-directory-listing-878838/
  • https://serverfault.com/questions/421161/how-to-configure-vsftpd-to-work-with-passive-mode
  • http://www.linuxquestions.org/questions/linux-networking-3/vsftpd-cannot-list-files-but-can-change-dirs-519340/

Итак, если это не удалось, в чем может быть проблема?

На этом сайте я прочитал, что мне нужно переадресовать порты 20 и 21. Сейчас у удаленных сайтов есть порты, такие как 10000, 11000, 12000, которые перенаправляются на внутренний порт 21 в каждой из систем. Должен ли я переслать несколько дополнительных портов на 20? это не имеет смысла, потому что этот порт даже не открыт, vsftpd только слушает 21.

Все, что я хочу, это для успешного соединения ftp через эти перенаправленные порты, я расстроен, потому что я успешно переадресован для таких служб, как SSH, apache2 и т. Д., И я не понимаю, что здесь сломано.

спасибо Джорен за исправление моего форматирования!


РЕДАКТИРОВАТЬ: я возился с моим тестированием VPS, который напрямую подключен к Интернету, я установил vsftpd, просто чтобы посмотреть, что происходит, и вывод ‘netstat -tuna’ показывает, что успешное соединение с моим клиентом filezilla выглядит так:

tcp        0      0 vps.vps.vps.vps:21       fi.le.zil.la:54288      ESTABLISHED
tcp        0      0 vps.vps.vps.vps:46403    fi.le.zil.la:54289      TIME_WAIT

Примечание: FTP-сервер на моем VPS также сначала не работал из-за совершенно не связанной проблемы, связанной с виртуализированными средами («500 OOPS: priv_sock_get_cmd»). Читайте: я начинаю видеть, что vsftpd в Ubuntu не работает «из коробки», как apache2 и sshd, для любых разочарованных начинающих системных администраторов, не думайте, что вы глупы, если это не так работает первым делом…

У моего тестируемого VPS нет брандмауэра, поэтому все порты напрямую доступны для доступа демону FTP. После выполнения этого теста я вижу, что возможно, что это вторичное соединение блокируется на удаленном сайте, где у меня возникают проблемы (случайные порты, такие как 46403).

По крайней мере, теперь я подтвердил, что с моим Filezilla нет проблем с NAT, потому что filezilla явно открывает случайные порты и общается с моим VPS.

Единственное, что не имеет смысла, это то, что config ‘connect_from_port_20=YES’ установлен в моей конфигурации VPS FTP, но я не вижу никаких соединений, используя порт 20!!! Вот почему я даже не знаю, нужно ли перенаправлять этот порт за брандмауэр.

Один из моих недостатков в знаниях — я даже не знаю, что делает порт 20, и я не могу учиться на опыте, потому что я никогда не видел признаков того, что порт когда-либо использовался из-за подключения, загрузки или выгрузки.


Хорошо, я обнаружил некоторые проблемы (явно больше, чем одна вещь не так) — Это связано с переадресацией портов.

Подозреваю оригинальную проблему (перед настройкой vsftpd.conf)

  1. Filezilla изначально подключается к удаленному порту 10000, ==> идет на 21 на внутреннем FTP-сервере (хорошо)
  2. FTP-сервер открывает случайный порт (НЕ 20), как 45678, но у маршрутизатора, очевидно, нет правила для этого случайно назначенного порта. Он отправляет сообщение о том, что filezilla также подключается к 45678.
  3. Клиент Filezilla открывает собственный порт на моем конце за NAT(хорошо)
  4. Filezilla отправляет запрос на соединение 45678, но удаленный маршрутизатор не принимает соединение, поскольку для этого порта нет правила переадресации.

Теперь проблема (ы), которые я создал:

pasv_enable=YES
pasv_min_port=10000
pasv_max_port=10000
  1. Filezilla подключается к удаленному порту 10000, ==> идет на 21 на внутреннем FTP-сервере (хорошо)
  2. FTP-сервер открывает единственный порт, который он может, 10000, [глупый момент], потому что у меня в голове этот порт связан с этой системой. Но 10000 — это фактически аналог стороны WAN для 21 в этой системе. Сервер отправляет сообщение для FileZilla для подключения к 10000 и прослушивает внутренне на 10000
  3. Клиент Filezilla открывает свой собственный случайный порт на моем конце (хорошо)
  4. Filezilla пробует вторичное соединение на порту 10000, удаленный маршрутизатор снова отклоняет его на порт 21, где его следует игнорировать или потерять, в то время как FTP-сервер ожидает подключения к внутреннему порту 10000, которое никогда не приходит. (потерпеть поражение)

Вторая проблема, которую я создал: я пытался связать порт 21 на этот раз, но я думаю, что испортил filezilla.

pasv_enable=YES
pasv_min_port=21
pasv_max_port=21
  1. Filezilla подключается к удаленному порту 10000, ==> идет на 21 на внутреннем FTP-сервере (хорошо)
  2. FTP-сервер открывает порт 21 (или, может быть, отказывает, потому что 21 уже используется), если это удалось, он отправил сообщение для filezilla для подключения к порту 21.
  3. Клиент Filezilla открывает свой собственный случайный порт на моем конце (хорошо)
  4. Filezilla отправляет запрос на LIST на 21, который маршрутизатор не собирается принимать…(ошибка)

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


Я опробую решение и сообщу здесь результаты.

Я думаю, поскольку протокол FTP-сервера сообщает клиенту, к какому порту подключаться, это вторичное соединение ДОЛЖНО иметь тот же номер внешнего порта, что и внутренний.

Я назову это «вторичным соединением», и я думаю, что оно как-то связано с портом 20, что я не понимаю.

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

Новый план:

(примечание: «%» означает, что порт был изменен удаленным маршрутизатором.)

 

сервер № 1
    первичное соединение: 21 <-% -> 10000 
    вторичное соединение 10001 <-----> 10001
    vsftp.conf:
        pasv_min_port = 10001
        pasv_max_port = 10001

сервер № 2
    первичное соединение 21 <-% -> 11000
    вторичное соединение 11001 <-----> 11001
    vsftp.conf:
        pasv_min_port = 11001
        pasv_max_port = 11001

сервер № 3
    первичное соединение 21 <-% -> 12000
    вторичное соединение 12001 <-----> 12001
    vsftp.conf:
        pasv_min_port = 12001
        pasv_max_port = 12001

Понравилась статья? Поделить с друзьями:
  • W210 ошибка b1755
  • Vscode eslint не подсвечивает ошибки
  • Vsc ошибка что значит
  • W210 ошибка b1010
  • Vsc ошибка тойота ярис