FTP server VSFTPd and virtual users MySQL on CentOS 7, Web-admin for VSFTP
A series of articles on setting up a VSFTPd FTP server on Centos 7
- Installing and configuring the VSFTPd FTP server on Centos 7. Local users
- FTP server VSFTPd and virtual users MySQL on CentOS 7, Web-admin for VSFTP
Installing Apache, PHP, MySQL
Add EPEL repository and update
[[email protected]]# yum install epel-release
[[email protected]]# yum update
We install software for the convenience of work
[[email protected]]# yum install nano htop mc wget
Install the MySQL server MariaDB, Apache web server and PHP. The installation instructions can be read at the links below:
Installation Apache web servers on Centos 7
Installation MySQL servers (MariaDB) on Centos 7
Installation PHP 7 on Centos 7
Restart Apache
[[email protected]]# systemctl restart httpd.service
Disabling Selinux
Disable Selinux
[[email protected]]# setenforce 0
[[email protected]]# nano /etc/selinux/config
And edit the following line:
...
SELINUX=disabled
...
Apache configuration
Configuring Apache, add vhosts – multiple sites on one ip-address
[[email protected]]# nano /etc/httpd/conf.d/vhosts.conf
# Загрузка моих vhosts
IncludeOptional vhosts.d/*.conf
Create a directory where vhosts configurations will be located
[[email protected]]# mkdir /etc/httpd/vhosts.d
Create config file for local IP
[[email protected]]# nano /etc/httpd/vhosts.d/192.168.1.19.conf
<VirtualHost 192.168.1.19:80>
ServerAdmin [email protected]
DocumentRoot "/var/www/192.168.1.19/html/"
ServerName 192.168.1.19
ErrorLog "/var/www/192.168.1.19/logs/error_log"
CustomLog "/var/www/192.168.1.19/logs/access_log" combined
<Directory "/var/www/192.168.1.19/html/">
DirectoryIndex index.html index.php
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
We create the necessary directories and set access rights
[[email protected]]# mkdir -p /var/www/192.168.1.19/html
[[email protected]]# mkdir -p /var/www/192.168.1.19/logs
[[email protected]]# chown -R apache:apache /var/www/192.168.1.19/
Restart Apache
[[email protected]]# systemctl restart httpd.service
Installing VSFTPd
Installing an FTP server
[[email protected]]# yum install vsftpd
Editing the configuration file
[[email protected]]# nano /etc/vsftpd/vsftpd.conf
[[email protected] ~]# cat /etc/vsftpd/vsftpd.conf
# Запуск сервера в режиме службы
listen=YES
# Работа в фоновом режиме
background=YES
# Разрешить подключаться виртуальным пользователям
guest_enable=YES
# Системный пользователь от имени котрого подключаются виртуальные
guest_username=apache
# Виртуальные пользователи имеют те же привелегии, что и локальные
virtual_use_local_privs=YES
# Автоматическое назначение домашнего каталога для виртуальных пользователей
user_sub_token=$USER
local_root=/home/ftp/$USER
# Имя pam сервиса для vsftpd
pam_service_name=vsftpd
# Входящие соединения контроллируются через tcp_wrappers
tcp_wrappers=YES
# Запрещает подключение анонимных пользователей
anonymous_enable=NO
# Каталог, куда будут попадать анонимные пользователи, если они разрешены
#anon_root=/ftp
# Разрешает вход для локальных пользователей
local_enable=YES
# Разрешены команды на запись и изменение
write_enable=YES
# Указывает исходящим с сервера соединениям использовать 20-й порт
connect_from_port_20=YES
# Логирование всех действий на сервере
xferlog_enable=YES
# Путь к лог-файлу
xferlog_file=/var/log/vsftpd.log
# Включение специальных ftp команд, некоторые клиенты без этого могут зависать
async_abor_enable=YES
# Локальные пользователи по-умолчанию не могут выходить за пределы своего домашнего каталога
chroot_local_user=YES
# Разрешить список пользователей, которые могут выходить за пределы домашнего каталога
chroot_list_enable=YES
# Список пользователей, которым разрешен выход из домашнего каталога
chroot_list_file=/etc/vsftpd/chroot_list
# Разрешить запись в корень chroot каталога пользователя
allow_writeable_chroot=YES
# Контроль доступа к серверу через отдельный список пользователей
#userlist_enable=YES
# Файл со списками разрешенных к подключению пользователей
#userlist_file=/etc/vsftpd/user_list
# Пользователь будет отклонен, если его нет в user_list
#userlist_deny=NO
# Директория с настройками пользователей
user_config_dir=/etc/vsftpd/users
# Показывать файлы, начинающиеся с точки
force_dot_files=YES
# Маска прав доступа к создаваемым файлам
local_umask=022
# Приветствие
ftpd_banner=Welcome to FTP service.
#set maximum allowed connections per single IP address (0 = no limits)
max_per_ip=10
# Порты для пассивного режима работы
pasv_min_port=40900
pasv_max_port=40999
data_connection_timeout=900
idle_session_timeout=900
We open ports 20-21 (active mode of the ftp server) and 40900-40999 (passive mode of the ftp server)
[[email protected]]# firewall-cmd --permanent --add-port=20-21/tcp
[[email protected]]# firewall-cmd --permanent --add-port=40900-40999/tcp
[[email protected]]# firewall-cmd --reload
Add the server to startup, start it and check the status
[[email protected]]# systemctl enable vsftpd
[[email protected]]# systemctl start vsftpd
[[email protected]]# systemctl status vsftpd
MySQL setup
Connecting to MySQL
mysql -u root -p
Create a database and a user with only rights to this database
> CREATE DATABASE vsftpd;
> GRANT SELECT ON vsftpd.* TO 'vsftpd'@'localhost' IDENTIFIED BY 'passwordftp';
> USE vsftpd;
We select this base and create a table. The structure of the table is set taking into account the use of the functionality of the web admin panel
> USE vsftpd;
> CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 30 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL ,
`password` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL ,
`email` varchar(80) CHARACTER SET utf8 NOT NULL,
`date` datetime NOT NULL,
`date_end` date NOT NULL,
`temp` int(1) NOT NULL,
`dir` varchar(80) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`local_ip` varchar(30) CHARACTER SET utf8 NOT NULL,
UNIQUE (`username`)
) ENGINE = MYISAM ;
My dump of the database
-- Хост: localhost
-- Время создания: Июл 27 2018 г., 12:08
-- Версия сервера: 5.5.56-MariaDB
-- Версия PHP: 7.2.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `vsftpd`
--
-- --------------------------------------------------------
--
-- Структура таблицы `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(80) CHARACTER SET utf8 NOT NULL,
`date` datetime NOT NULL,
`date_end` date NOT NULL,
`temp` int(1) NOT NULL,
`dir` varchar(80) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`local_ip` varchar(30) CHARACTER SET utf8 NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Дамп данных таблицы `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `email`, `date`, `date_end`, `temp`, `dir`, `local_ip`) VALUES
(104, 'user', md5('password'), '[email protected]', '2018-03-12 13:39:24', '2018-04-12', 0, '/home/ftp/user', '');
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=143;
COMMIT;
Exiting MySQL
> q
Install the pam_mysql module
[[email protected]]# 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
Save a copy of the pam file
[[email protected]]# mv /etc/pam.d/vsftpd /etc/pam.d/vsftpd.back
Create a new pam file
[[email protected]]# nano /etc/pam.d/vsftpd
session optional pam_keyinit.so force revoke
auth required pam_mysql.so user=vsftpd_user passwd=passwordftp host=localhost db=vsftpd table=users usercolumn=username passwdcolumn=password crypt=3
account required pam_mysql.so user=vsftpd_user passwd=passwordftp host=localhost db=vsftpd table=users usercolumn=username passwdcolumn=password crypt=3
- user = vsftpd_user – login password for connecting to the database;
- passwd = passwordftp – password for connecting to the database;
- db = vsftpd – name of the created database;
- table = users – table with users;
- usercolumn = username – the name of the column from which we retrieve the login;
- passwdcolumn = password – the name of the column from which we extract the password;
Create a file with logs for vsftpd and set the rights to it
[[email protected]]# touch /var/log/vsftpd.log && chmod 600 /var/log/vsftpd.log
Create a file that will list the list of users who are allowed to leave the home directory. And add the root user to it
[[email protected]]# touch /etc/vsftpd/chroot_list
[[email protected]]# echo 'root' >> /etc/vsftpd/chroot_list
Set a user and group for the directory where the FTP user directories will be stored
[[email protected]]# chown -R apache:apache /home/ftp
Web-Admin for VSFTP
Web admin panel can be downloaded from the link below
The main functionality of the admin panel:
- Add FTP User
- Delete FTP User
- Change password for FTP user
Additional admin functionality:
- The user can be permanent or temporary. Temporary is automatically deleted after a month
- To extend the validity period of a temporary user account, you need to update his password, then the account will be valid for another month.
- When adding a user, the password is generated automatically, it can be re-generated, but you cannot enter the password manually
- When adding a user, you can specify an e-mail. All information will be sent to it (login / password when first adding, new password when changing, warning about deleting a temporary account the day before deleting, informing about the final deletion of a temporary account)
- The same letters are sent to the administrator of the Web-admin (e-mail is set in php)