Pureftpd, chiffrement et MySQL

Billet posté le 12 févr. 2012

Introduction

Cette documentation a pour but d’expliquer comment compiler pure-ftpd avec le support mysql et TLS ainsi que l’exécution de script lors d’un upload.

Pureftpd

Les pré-requis

Il est nécessaire d’installer des logiciels avant de compiler pure-ftpd :

apt-get install libmysqlclient-dev libssl-dev libpam0g-dev

Il est aussi nécessaire de créer un groupe ainsi qu’un utilisateur particulier :

groupadd ftpgroup
useradd -d /srv/ftpgroup -m -g ftpgroup ftpuser

Il est aussi nécessaire de créer une base de données ainsi qu’un utilisateur et mot de passe. Pour ce faire on utilise phpmyadmin avec la procédure suivante :

  • cliquer sur l’onglet privileges
  • cliquer sur ajouter un utilisateur
  • nom d’utilisateur : saisir un nom
  • serveur : saisir local (valeur localhost)
  • saisir deux fois le mot de passe
  • cocher : Créer une base portant son nom et donner à cet utilisateur tous les privilèges sur cette base
  • cocher toutes les cases données
  • cocher toutes les cases Structure
  • cliquer sur le bouton exécuter
  • cliquer de nouveau sur le bouton privilèges
  • cliquer sur le lien recharger les privilèges

Il est possible de tester la connexion à la nouvelle base avec le nouvel utilisateur en faisant :

mysql -u <utilisateur> -p <db>

Certificat SSL

mkdir -p /etc/ssl/private
openssl req -x509 -nodes -newkey rsa:1024 -keyout /etc/ssl/private/pure-ftpd.pem -out /etc/ssl/private/pure-ftpd.pem
Generating a 1024 bit RSA private key
.++++++
..................++++++
writing new private key to '/etc/ssl/private/pure-ftpd.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:FR
State or Province Name (full name) [Some-State]:Indre et Loire
Locality Name (eg, city) []:Tours
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Lovetux
Organizational Unit Name (eg, section) []:
Common Name (eg, YOUR name) []:ftp.lovetux.net
Email Address []:hindy@lovetux.net
chmod 600 /etc/ssl/private/pure-ftpd.pem

Structure de la table :

CREATE TABLE IF NOT EXISTS `ftp` (
`User` varchar(16) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL DEFAULT '',
`Password` varchar(64) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL DEFAULT '',
`Uid` int(11) NOT NULL DEFAULT '1003',
`Gid` int(11) NOT NULL DEFAULT '1004',
`Dir` varchar(128) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL DEFAULT '/srv/ftpgroup/./',
`ULBandwidth` int(4) NOT NULL DEFAULT '0',
`DLBandwidth` int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`User`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Récupération des sources

Le site officiel est disponible ici : https://download.pureftpd.org/pub/pure-ftpd/releases/

Et on passe à la compilation :

$ ./configure -without-inetd --with-throttling --with-ftpwho --with-welcomemsg --with-mysql --with-language=french --with-extauth --with-cookie --with-peruserlimits \
--with-tls --with-virtualchroot --with-pam --prefix=/usr/local/pure-ftpd --with-altlog --localstatedir=/usr/local/pure-ftpd/var
make
make install

Le dossier d’installation

Tous les fichiers d’installation se trouvent dans le dossier : /usr/local/pure-ftpd, il faut créer un nouveau dossier pour stocker le pid :

mkdir -p /usr/local/pure-ftpd/var/run/pure-ftpd

Script d’init

Le script suivant est à placer dans le fichier suivant : /etc/init.d/pure-ftpd

#! /bin/sh
### BEGIN INIT INFO
# Provides:          skeleton
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      S 0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d.
### END INIT INFO

# Author: Foo Bar &lt;foobar@baz.org&gt;
#
# Please remove the "Author" lines above and replace them
# with your own name if you copy and modify this script.

# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/usr/sbin:/usr/bin:/sbin:/bin
DESC="pure-ftpd"
NAME=pure-ftpd
DAEMON=/usr/local/pure-ftpd/sbin/$NAME
#DAEMON_ARGS="--tls=3 -l mysql:/usr/local/pure-ftpd/etc/mysql.conf -l pam -u 1000 -E -H -O stats:/var/log/pureftpd.log -B"
DAEMON_ARGS="--tls=3 -l mysql:/usr/local/pure-ftpd/etc/mysql.conf -4 -l pam -u 1000 -E -H -O stats:/srv/ftpgroup/logs/pureftpd.log -B"
PIDFILE=/usr/local/pure-ftpd/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] &amp;&amp; . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] &amp;&amp; . /etc/default/rcS

# Define LSB log_* functions.
# Depend on lsb-base (&gt;= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#
# Function that starts the daemon/service
#
do_start()
{
# Return
#   0 if daemon has been started
#   1 if daemon was already running
#   2 if daemon could not be started
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test &gt; /dev/null \
|| return 1
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
$DAEMON_ARGS \
|| return 2
# Add code here, if necessary, that waits for the process to be ready
# to handle requests from services started subsequently which depend
# on this one.  As a last resort, sleep for some time.
}

#
# Function that stops the daemon/service
#
do_stop()
{
# Return
#   0 if daemon has been stopped
#   1 if daemon was already stopped
#   2 if daemon could not be stopped
#   other if a failure occurred
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
RETVAL="$?"
[ "$RETVAL" = 2 ] &amp;&amp; return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently.  A last resort is to
# sleep for some time.
start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
[ "$?" = 2 ] &amp;&amp; return 2
# Many daemons don't delete their pidfiles when they exit.
rm -f $PIDFILE
return "$RETVAL"
}

#
# Function that sends a SIGHUP to the daemon/service
#
do_reload() {
#
# If the daemon can reload its configuration without
# restarting (for example, when it is sent a SIGHUP),
# then implement that here.
#
start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
return 0
}

case "$1" in
start)
[ "$VERBOSE" != no ] &amp;&amp; log_daemon_msg "Starting $DESC" "$NAME"
do_start
case "$?" in
0|1) [ "$VERBOSE" != no ] &amp;&amp; log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] &amp;&amp; log_end_msg 1 ;;
esac
;;
stop)
[ "$VERBOSE" != no ] &amp;&amp; log_daemon_msg "Stopping $DESC" "$NAME"
do_stop
case "$?" in
0|1) [ "$VERBOSE" != no ] &amp;&amp; log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] &amp;&amp; log_end_msg 1 ;;
esac
;;
#reload|force-reload)
#
# If do_reload() is not implemented then leave this commented out
# and leave 'force-reload' as an alias for 'restart'.
#
#log_daemon_msg "Reloading $DESC" "$NAME"
#do_reload
#log_end_msg $?
#;;
restart|force-reload)
#
# If the "reload" option is implemented then remove the
# 'force-reload' alias
#
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
case "$?" in
0|1)
do_start
case "$?" in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
*)
#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" &gt;&amp;2
echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" &gt;&amp;2
exit 3
;;
esac

Puis faire les commandes suivantes :

chmod a+x /etc/init.d/pure-ftpd update-rc.d pure-ftpd defaults

Fichier de configuration

Le fichier à créer est le suivant : /usr/local/pure-ftpd/etc/mysql.conf avec le contenu suivant :

##############################################
#                                            #
# Sample Pure-FTPd Mysql configuration file. #
# See README.MySQL for explanations.         #
#                                            #
##############################################

# Optional : MySQL server name or IP. Don't define this for unix sockets.

# MYSQLServer     127.0.0.1

# Optional : MySQL port. Don't define this if a local unix socket is used.

# MYSQLPort       3306

# Optional : define the location of mysql.sock if the server runs on this host.

MYSQLSocket      /var/run/mysqld/mysqld.sock

# Mandatory : user to bind the server as.

MYSQLUser       hindy

# Mandatory : user password. You must have a password.

MYSQLPassword   unmotdepasse

# Mandatory : database to open.

MYSQLDatabase   hindy

# Mandatory : how passwords are stored
# Valid values are : "cleartext", "crypt", "md5" and "password"
# ("password" = MySQL password() function)
# You can also use "any" to try "crypt", "md5" *and* "password"

MYSQLCrypt      any

# In the following directives, parts of the strings are replaced at
# run-time before performing queries :
#
# \L is replaced by the login of the user trying to authenticate.
# \I is replaced by the IP address the user connected to.
# \P is replaced by the port number the user connected to.
# \R is replaced by the IP address the user connected from.
# \D is replaced by the remote IP address, as a long decimal number.
#
# Very complex queries can be performed using these substitution strings,
# especially for virtual hosting.

# Query to execute in order to fetch the password

MYSQLGetPW      SELECT Password FROM ftp WHERE User="\L"

# Query to execute in order to fetch the system user name or uid

MYSQLGetUID     SELECT Uid FROM ftp WHERE User="\L"

# Optional : default UID - if set this overrides MYSQLGetUID

#MYSQLDefaultUID 1000

# Query to execute in order to fetch the system user group or gid

MYSQLGetGID     SELECT Gid FROM ftp WHERE User="\L"

# Optional : default GID - if set this overrides MYSQLGetGID

#MYSQLDefaultGID 1000

# Query to execute in order to fetch the home directory

MYSQLGetDir     SELECT Dir FROM ftp WHERE User="\L"

# Optional : query to get the maximal number of files
# Pure-FTPd must have been compiled with virtual quotas support.

# MySQLGetQTAFS  SELECT QuotaFiles FROM ftp WHERE User="\L"

# Optional : query to get the maximal disk usage (virtual quotas)
# The number should be in Megabytes.
# Pure-FTPd must have been compiled with virtual quotas support.

# MySQLGetQTASZ  SELECT QuotaSize FROM ftp WHERE User="\L"

# Optional : ratios. The server has to be compiled with ratio support.

# MySQLGetRatioUL SELECT ULRatio FROM ftp WHERE User="\L"
# MySQLGetRatioDL SELECT DLRatio FROM ftp WHERE User="\L"

# Optional : bandwidth throttling.
# The server has to be compiled with throttling support.
# Values are in KB/s .

MySQLGetBandwidthUL SELECT ULBandwidth FROM ftp WHERE User="\L"
MySQLGetBandwidthDL SELECT DLBandwidth FROM ftp WHERE User="\L"

# Enable ~ expansion. NEVER ENABLE THIS BLINDLY UNLESS :
# 1) You know what you are doing.
# 2) Real and virtual users match.

# MySQLForceTildeExpansion 1

# If you upgraded your tables to transactionnal tables (Gemini,
# BerkeleyDB, Innobase...), you can enable SQL transactions to
# avoid races. Leave this commented if you are using the
# traditionnal MyIsam databases or old (&lt; 3.23.x) MySQL versions.

Dernière chose

Ne pas oublier de démarrer le daemon par la commande suivante :

/etc/init.d/pure-ftpd start

Si ça ne fonctionne pas je vous conseille de regarder les fichiers de logs et de s’assurer que le daemon pure-ftpd est bien dans les tables de processus et enfin que les permissions sont mises correctement. Documentation officielle

Pas de secret, la documentation officielle se trouve ici : http://download.pureftpd.org/pub/pure-ftpd/doc/README.TLS