Linux ftp client ssl tls

Использование SSL/TLS на vsftpd (Ubuntu)

Предупреждение: FTP по своей сути небезопасен! В большинстве случаев рекомендуется использовать SFTP вместо FTP.

Раньше FTP (или File Transfer Protocol – протокол передачи файлов) был очень популярным способом обмена файлами между локальным и удаленным компьютерами. Тем не менее, он небезопасен, потому его использование подвергает компьютер определенному риску.

При необходимости использовать именно FTP (вместо более безопасного SFTP, который для передачи файлов использует протокол SSH) его можно несколько обезопасить при помощи SSL.

Данное руководство демонстрирует, как настроить vsftpd для использования SSL-сертификатов на сервере Ubuntu 12.04.

Установка vsftpd

Сервер vsftpd можно получить из репозиториев Ubuntu по умолчанию. Чтобы установить его, наберите:

sudo apt-get install vsftpd

Теперь vsftpd установлен, можно приступить к его настройке.

Настройка основных функций

По умолчанию конфигурационный файл находится в /etc/vsftpd.conf. Откройте его с привилегиями root:

Отключите возможность входа в систему анонимно: найдите параметр anonymous_enable и измените его значение на “NO”:

Затем нужно позволить вход пользователям, использующим локальные файлы аутентификации, так как анонимный доступ отключен. Раскомментируйте данную строку:

Чтобы разрешить пользователям вносить изменения в файловую систему, раскомментируйте параметр:

Кроме того, необходимо раскомментировать опцию chroot_local_user, чтобы ограничить пользователей их домашними каталогами:

Сохраните изменения и закройте файл.

Создание FTP-пользователя

Поскольку vsftpd защищает все jail-ы chroot, chroot не должен принадлежать пользователю и не должен иметь право на изменение. Поэтому удобнее всего создать отдельного пользователя для работы с FTP.

Установите пароль; на остальные извещения можно нажать ENTER. Теперь нужно передать root -привилегии домашнему каталогу пользователя ftpuser.

sudo chown root:root /home/ftpuser

Внутри этого домашнего каталога создайте отдельный каталог, в который можно выгрузить файлы. Затем передайте этот каталог пользователю FTP:

sudo mkdir /home/ftpuser/files
sudo chown ftpuser:ftpuser /home/ftpuser/files

Теперь можно установить (незащищенное) соединение как ftpuser и выгрузить файлы в каталог files.

Настройка SSL для работы с vsftpd

Теперь нужно создать сертификаты SSL, чтобы использовать их с vsftpd. Это делается так:

sudo openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout /etc/ssl/private/vsftpd.pem -out /etc/ssl/private/vsftpd.pem

Это создаст сертификат, действительный на протяжении года. Он будет размещен в каталоге /etc/ssl/private/, который нужно добавить в конфигурационный файл.

Внесение SSL в конфигурации Vsftpd

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

В нижней части файла найдите строку, соответствующую только что созданному сертификату SSL:

Под этой строкой нужно внести дополнительную информацию об SSL.

При создании сертификата ключевой файл и сертификат были помещены в один файл, поэтому можно указать строку закрытого ключа:

Затем нужно внести следующие строки, которые ограничат доступ клиентов к TLS.

Читайте также:  Krb5 conf astra linux

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

Затем нужно настроить сервер на использование TLS (преемник SSL):

ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO

Чтобы расширить конфигурационный файл, необходимо внести дополнительные опции:

Сохранив изменения, закройте файл.

Затем перезапустите сервер, чтоб активировать внесенные изменения:

sudo service vsftpd restart

Подключение к серверу через FileZilla

Современные клиенты FTP могут использовать механизмы шифрования SSL и TLS. Ниже будет продемонстрировано, как установить подключение с помощью FileZilla (используя поперечные платформы).

Слева на конфигурационной панели найдите и нажмите кнопку, которая открывает “Site Manager”.

Затем нажмите на кнопку “New Site” в правом нижнем углу появившегося окна.

Введите IP-адрес. В поле “Encryption” разверните меню и выберите “Require explicit FTP over TLS”.

В поле “Logon Type” выберите “Ask for password”. В поле “User” укажите ранее созданного пользователя ftp.

Затем нажмите “Connect” в нижней части интерфейса, после чего введите пароль пользователя ftp.

На данном этапе нужно будет принять TLS-сертификат.

Готово! Теперь соединение с сервером с помощью механизма шифрования TLS/SSL установлено.

Итоги

Инструкции данного руководства помогут повысить защиту FTP; тем не менее, FTP по-прежнему имеет некоторые уязвимости при установлении соединения. Если это возможно, некоторые операции лучше выполнять по SFTP. В любом случае, при работе с FTP настоятельно рекомендуется использовать TLS/SSL.

Источник

How to Enable FTP SSL/TLS Security on Linux via the Command Line

Siteground WordPress Hosting

Once you’ve installed an FTP server on your Linux machine, it’s time to look into security. Earlier, I showed you how to set up an FTP server using “Pure-FTPd” because of its ease of use and its inbuilt support for virtual users. This allows you to maintain a distinction between FTP users and system users. While other programs like vsftpd also support virtual users, it’s not as seamless.

But FTP is an inherently insecure protocol. Here’s why.

Plain Text Username and Password Transmission

When your FTP client connects with the remote server, it sends the username/password credentials. By default this contains no encryption whatsoever. It means that anyone intercepting your transmission will have no difficulties reading your authentication data and can then connect themselves without a hitch. Here’s a proof of concept.

I used a popular Windows program called “Wireshark” to monitor my network traffic. It allows me to choose a network interface, and then filter out the traffic based on a variety of parameters. In this example, I selected to monitor traffic to and from the server IP address and filtered them with the word “ftp”. Here’s what I captured:

As you can see, not only are my username and password sent in plain text, they’re also clearly marked as such! If this was a hacker snooping on network transmissions, they would now be able to connect to my FTP server. If you read my previous article on setting up an FTP server, you’ll know that I created a user called “testftpuser”. And that is exactly what is displayed in the network traffic data.

Clearly this is a huge security risk. The notion of sending usernames and passwords in plaintext over the Internet is unthinkable in today’s day and age. Luckily for us, we have a few options to enable encryption with our FTP server so that we’re not exposed to such a glaring vulnerability. Pure-FTPd can utilize existing server certificates and keys to encrypt our traffic to and from the FTP client.

Читайте также:  Изменить default route linux

Reusing Existing Certificates and Keys

We can achieve FPT SSL/TLS security by providing Pure-FTPd with a certificate and key file combined into one. If you use the “HTTPS” protocol with your website, it means that you already have the necessary certificate for encrypting traffic. In an earlier tutorial, I’d shown you how to generate your own self signed certificates for HTTPS. If you follow that tutorial, you will now have the following in your server folder:

For use with FTP SSL or TLS, we need to combine these two files into a single “.pem” file. navigate to the directory containing these two files and type in the following command:

cat 104.236.92.101.crt 104.236.92.101.key > 104.236.92.101.pem

Here, replace the sections in bold with the actual names of your .crt and .key files. In this example, I’ve chosen to keep the names as my IP address. You can use whatever names you want as long as you can keep track of them! The above command will concatenate the two files into a single “.pem” file that is accepted by the Pure-FTPd configuration. Now we just need to move the newly created “.pem” file to the default location where Pure-FTPd looks for it. Type in:

mkdir /etc/ssl/private/ cp 104.236.92.101.pem /etc/ssl/private/pure-ftpd.pem

The first command creates the directory. The second transfers the newly created pem file into it. As before, replace the text in bold with the name of your own file.

Configuring Pure-FTPd with the Certificate Name

Now that we have the certificate in the right location, we have to inform Pure-FTPd about it and also enable TLS authentication. To do this, open the Pure-FTPd configuration file located at “/etc/pure-ftpd/pure-ftpd.conf”. You can open it with a text editor like this:

vi /etc/pure-ftpd/pure-ftpd.conf

In this file, we need to make two changes. The first is to uncomment the line specifying the location of the certificate file like this:

#CertFile /etc/ssl/private/pure-ftpd.pem

Remove the “#” symbol at the beginning of the line to uncomment it. The second change is to enable TLS functionality by uncommenting the following line as well:

After removing the “#” symbols from both these lines, Pure-FTPd is configured to encrypt all FTP communications.

Opening the Necessary Ports

There’s one more thing we need to take care of. If you try and use Pure-FTPd “as is”, it might not work depending on your firewall. You might get an error that says:

This is because FTP SSL or TLS changes the mode of FTP to something called “Passive Mode”. The details of this mode are not important. What’s important is that it no longer uses Port 21 which is the default for regular FTP communications. As a result if you have a firewall that doesn’t take this into consideration, the the FTP connection will fail with the above error.

Читайте также:  Webstorm reset trial linux

To resolve this, we need to do two things. First, we enable a higher range of ports for passive FTP in the Pure-FTPd configuration file itself. Uncomment the following line:

#PassivePortRange 30000 50000

By activating this line, you tell Pure-FTPd to use the port range of 30,000 to 50,000. The next step is to open up the same ports in your firewall. The method for this will depend on the kind of firewall you’re using. Personally I use csf, so that involves going into the csf configuration file and adding the range of ports to the TCP_IN and TCP_OUT lines. The csf configuration file is called “/etc/csf/csf.conf”. So the changes to the lines would look like this:

Notice that you can input IP ranges separated by the “:” character. So in this case, it’s 30000:50:000. As I mentioned earlier, this will depend on which firewall you’re using. Just make sure that the ports you open in the firewall are the same ports mentioned in the Pure-FTPd client under “PassivePortRange”.

Restarting Pure-FTPd and the Firewall

We’re almost done. After all the configuration changes, we need to restart both Pure-FTPd and the firewall for the changes to take effect. To restart Pure-FTPd, type in:

And to restart csf, just type:

Or use whatever command for your particular firewall. Just make sure that the rule changes have taken effect, otherwise you may not be able to connect to FTP SSL.

Connecting from the Client

That completes our server side changes. It’s now ready to accept incoming FTP SSL/TLS connections. On the client side, you need to ensure that TLS is enabled. This will vary from client to client. For example, I use “WinSCP” and in that, I need to select the option called “TLS Explicit encryption” from the drop down box as shown here:

Now the connection proceeds as normal. If you have a self-signed certificate (like me), you’ll get a certificate warning that you can ignore:’

And here is the successful connection:

Checking if Encryption Works

Finally, let’s repeat the very first step and see if we can snoop the FTP username/password using Wireshark as we did at the beginning. Here’s the screenshot this time when I filter FTP traffic to that particular IP address:

As you can see, the data makes no sense now. That’s because it’s encrypted and no one will be able to see the username or the password, even if they have full access to the network packets. Congratulations! You have secured your FTP connection and rendered it invulnerable to hackers.

Источник

Оцените статью
Adblock
detector