miércoles, 30 de septiembre de 2009

Instalar y configurar VSFTP

Para instalar el servidor ftp lanzamos el comando siguiente

$sudo apt-get install vsftpd
El fichero que tiene toda la configuracion es:
$sudo vi /etc/vsftpd.conf

Deberiamos tener algo asi para que nos funcionara:

# 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.
#
#
# Run standalone? vsftpd can run either from an inetd or as a standalone
# daemon started from an initscript.
listen=YES
#
# Run standalone with IPv6?
# Like the listen parameter, except vsftpd will listen on an IPv6 socket
# instead of an IPv4 one. This parameter and the listen parameter are mutually
# exclusive.
listen_ipv6=NO
#
# 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.
dual_log_enable=YES
vsftpd_log_file=/var/log/vsftpd.log
xferlog_file=/var/log/xferlog
#
# If you want, you can have your log file in standard ftpd xferlog format
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=ftpsecure
#
# 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=Bienvenido al servidor FTP.
#
# 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 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
#
# 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().
chroot_list_enable=YES
# (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
#
#
# Debian customization
#
# Some of vsftpd's settings don't fit the Debian filesystem layout by
# default. These settings are more Debian-friendly.
#
# 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
#
# This string is the name of the PAM service vsftpd will use.
pam_service_name=vsftpd
#
# This option specifies the location of the RSA certificate to use for SSL
# encrypted connections.
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
# This option specifies the location of the RSA key to use for SSL
# encrypted connections.
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
#
#Esto lo incluyo para el tema de la velocidad y las conexiones
userlist_enable=YES
tcp_wrappers=YES
userlist_deny=NO
anon_max_rate=5100
local_max_rate=0
max_clients=20
max_per_ip=10
syslog_enable=YES
session_support=YES
#ya veremos si funciona

Para iniciar tu servidor FTP en modo standalone (individual, no iniciado por inetd) ejecuta el comando /usr/sbin/vsftpd & (recuerda quitar el comentario a la linea listen=YES de vsftpd.conf para que no te de error)
Si quieres que cada vez que tu ordenador suba, el servicio FTP inicie automaticamente, simplemente edita el archivo /etc/inetd.conf y descomenta la linea que dicen lo siguiente:

ftp stream tcp nowait root /usr/sbin/tcpd vsftpd

Y listo, subira automaticamente siempre

No olvides crear el archivo /etc/vsftpd.chroot_list si utilizaste esta opcion. Puedes crear uno vacio de la siguiente forma (como root, claro esta):
$touch /etc/vsftpd.chroot_list

Por defecto la instalacion crea el directorio /home/ftp como ruta para la creacion de los sitios
Se puede cambiar y crear otro directorio que contenga los ftp
$sudo mkdir /ftp

Creamos el grupo que va ha contener los usuarios para el FTP y que llamamos ftpusers
$sudo groupadd ftpusers

En /etc/passwd tenemos que tener la siguiente linea o parecida para que nos funcione
$sudo vi /etc/passwd
...
ftpsecure:x:107:65534::/tmp:/bin/false
...
Ahora creamos un usuario
$sudo adduser prueba1 --ingroup ftpusers --home /ftp/prueba1 --shell /bin/false
automaticamente se crea el directorio /ftp/prueba1

Ejemplo:
$sudo adduser --ingroup ftpusers --home /ftp/prueba4 -c "usuario de prueba4" prueba4 --shell /bin/false
adduser: `usuario de prueba4' no existe. Usando valores por defecto.
Añadiendo usuario 'prueba4' ...
Agregando nuevo usuario `prueba4' (1003) con grupo `ftpusers' ...
Creando el directorio personal '/ftp/prueba4' ...
Copiando archivos desde '/etc/skel' ...
Introduzca la nueva contraseña de UNIX:
Vuelva a escribir la nueva contraseña de UNIX:
passwd: contraseña actualizada correctamente
Cambiando la información de usuario para prueba4
Introduzca el nuevo valor, o presione ENTER para el predeterminado

Nombre completo []: prueba4

       Número de habitación []: la suya

       Teléfono del trabajo []: el tel

       Teléfono de casa []: tel_cas

       Otro []: nose

¿Es correcta la información? [y/N] y

Si vemos el fichero /etc/passwd tendria esta nueva linea
prueba4:x:1003:1001:prueba4,la suya,el tel,tel_cas,nose:/ftp/prueba4:/bin/false

El directorio que se crea tiene los siguientes permisos
$ls -l /ftp
drwxr-xr-x 2 prueba4 ftpusers 4096 2007-11-21 12:36 prueba4

Para que funcione con /bin/false tenemos que tener esa shell en el fichero /etc/shells y sino tenemos que ponerla
$vi /etc/shells
# /etc/shells: valid login shells
/bin/csh
/bin/sh
/usr/bin/es
/usr/bin/ksh
/bin/ksh
/usr/bin/rc
/usr/bin/tcsh
/bin/tcsh
/usr/bin/esh
/bin/bash
/bin/rbash
/bin/false

Se puede crear un usuario que tenga acceso a todas las carpetas que hay en el FTP
$sudo adduser --ingroup ftpusers --home /ftp -c "usuario moderador" ftpmoderador --shell /bin/false

Siempre que se crea un usuario se copia el contenido de /etc/skel al nuevo home del usuario creado (en este caso en /ftp/prueba4)
Se puede poner un enlace en /etc/skel para que todos los usuarios que hagamos tengan acceso a la ruta que digamos, y lo vean cuando arranquen con su usuario.
Ejemplo:
$cd /etc/skel
$sudo ln -s /tmp temporal
$ls -l /etc/skel
total 0
lrwxrwxrwx 1 root root 26 2007-11-07 10:29 Examples -> /usr/share/example-content
lrwxrwxrwx 1 root root 4 2007-11-21 12:53 temporal -> /tmp


Para asignar una contraseña a un usuario
$sudo passwd prueba1

Para borrar un usuario
$sudo userdel prueba1

Como el shell que usamos para los usuarios es /bin/false tenemos que ponerlo en el fichero de shell
$sudo vi /etc/shells

# /etc/shells: valid login shells
/bin/csh
/bin/sh
/usr/bin/es
/usr/bin/ksh
/bin/ksh
/usr/bin/rc
/usr/bin/tcsh
/bin/tcsh
/usr/bin/esh
/bin/dash
/usr/bin/screen
/bin/bash
/bin/rbash
/bin/false

Mediante 2 ficheros controlamos la lista de usuarios que pueden acceder al FTP y los que no.
Pongo unos ejemplos de como quedarian.
$vi /etc/vsftpd.chroot_list

  1. Usuarios que no pueden acceder al ftp
root
daemon
bin
sys
sync
games
man
lp
mail
news
uucp
proxy
www-data
backup
list
irc
gnats
nobody
dhcp
syslog
klog
messagebus
hplip
avahi-autoipd
avahi
haldaemon
gdm
jc
sshd
ftp

$sudo vi /etc/vsftpd.user_list
#usuarios que pueden usar el ftp
prueba1
prueba2
prueba3
prueba4
ftpmoderador

Una vez que tengamos todo configurado no nos olvidemos de reiniciar el servidor
$sudo /etc/init.d/vsftpd restart

Otras cosas:
$grep pru /etc/passwd
$sudo tail -f /var/log/vsftpd.log

Para conectar desde un navegador usamos lo siguiente:
ftp://tuusuario:tupassword@tudominio.com



Scripts para crear usuarios y sitios ftp asignados a una persona

En el directorio /home tenemos los siguientes scrip
$vi /home/create_pers_ftp.sh
#!/bin/sh
#Create persistent ftp account under /share/ftp_persistent_data
#$1 stores ftp_name
clear

LISTADO="/home/ftp_owner.txt"

if [ $# -ne 3 ]
then
   echo "Error in $0 - Invalid Argument Count"
   echo "Syntax: $0 ftp_name [permanente|temporal] nombre.apellido(del solicitante)"
   exit
fi

if [ $2 = "permanente" ]
then
  RUTA_BASE="/share/ftp_persistent_data/"
fi

if [ $2 = "temporal" ]
then
  RUTA_BASE="/share/ftp/"
  fi

if ( [ $2 != "temporal" ] && [ $2 != "permanente" ] )
then
  echo "Error in $0 - Invalid Argument Systaxis"
  echo "Syntax: $0 ftp_name (permanente|temporal)"
  exit 1
fi

propietario=$3

useradd -d ${RUTA_BASE}$1/ -s /bin/false $1
if [ $? = 9 ]
then
echo "Error: El usuario $1 ya existe. Intente otro nombre de usuario distinto"
exit
fi
passwd $1

mkdir ${RUTA_BASE}$1/
if [ $2 = "temporal" ]
then
mkdir ${RUTA_BASE}$1/LOS_DATOS_SE_BORRAN_AUTOMATICAMENTE_PASADOS_15_DIAS
mkdir ${RUTA_BASE}$1/THE_DATA_WILL_BE_DELETED_AUTOMATICALLY_AFTER_15_DAYS
fi
groupadd $3
echo "Se creo un nuevo sitio ftp en "${RUTA_BASE}$1/
chown -R $1:$3 ${RUTA_BASE}$1
echo "${1}:${3}" >> $LISTADO

echo $1 >> /etc/vsftpd.user_list
if [ $2 = "temporal" ]
then
chown root:root ${RUTA_BASE}$1/LOS_DATOS_SE_BORRAN_AUTOMATICAMENTE_PASADOS_15_DIAS
chown root:root ${RUTA_BASE}$1/THE_DATA_WILL_BE_DELETED_AUTOMATICALLY_AFTER_15_DAYS
chmod 444 ${RUTA_BASE}$1/LOS_DATOS_SE_BORRAN_AUTOMATICAMENTE_PASADOS_15_DIAS
chmod 444 ${RUTA_BASE}$1/THE_DATA_WILL_BE_DELETED_AUTOMATICALLY_AFTER_15_DAYS
fi


$vi /home/set_ftp_owner.sh
#!/bin/sh
# Este script recibe el nombre de una cuenta de ftp y el propietario de dicha cuenta (la persona que solicito la cuenta). Posteriormente cambia el grupo al que pertenece la carpeta home de dicho usuario (fichero /etc/passwd).
clear
if [ $# = 2 ]
then
  grep "^${1}:" /etc/passwd > /dev/null
  if [ $? != 0 ]
  then
   echo "ERROR: El usuario '$1' no existe en el sistema"
   exit
  fi
  RUTA=`grep "^${1}:" /etc/passwd | cut -d ":" -f 6`
  groupadd $2
  chown ${1}:${2} $RUTA
  if [ $? = 0 ]
  then
   echo "Exito al cambiar el grupo a la carpeta de usuario del ftp"
  else
   echo "Error! No se pudo cambiar el grupo a la carpeta de usuario del ftp"
  fi
else
  echo "Error! El numero de parametros no es correcto."
  echo " Introdujo $# parametros y deben ser 2: \"usuario_ftp nombre.apellido(solicitante de la cuenta ftp)\""
fi


Estos scripts modifican los siguientes ficheros
$ vi /etc/vsftpd.user_list
$ vi ftp_owner.txt
$ vi /etc/passwd
$ vi /etc/group


Controlar los ficheros del servidor FTP

$find /ftp/ -ctime +15 -type f -exec ls -l {} \; | tee - | wc -l
$find /ftp/ -ctime +15 -type f -exec ls -l {} \; | tee trash | wc -l
$find /ftp/panama -atime +30 -type f -exec ls -l {} \; > panama
Borra del ftp lo que tenga mas de 30 dias sin acceder
$find /ftp/ -atime +30 -type f -exec rm -f {} \;
$touch /ftp/usuarios-ftp.txt
Para que no nos borre los ficheros de un directorio los podemos cambiar el atributo (los tocamos)
$find /ftp/panama -type f -exec touch{} \;
Para poner un comando en segundo plano ctrl+z
$bg
$tail -f trash
$grep " Jul " trash
$grep " Jul " trash | grep -v 2007
$grep " Jul " trash | grep -v 2007 | less
$jobs
Para volver el comando a primer plano
$fg
$cat trash | wc -l
$grep daniel trash > dani.lst
$less dani.ls
$grep daniel trash | mail -s "List de borrados de Dani" juc@correo.es
$grep daniel trash | mailx -s "List de borrados de Dani" juc@correo.es

Tenemos un script en el servidor ftp con el cual controlamos que los ficheros que tengan mas de 30 dias sin ser modificados o accedidos (incluso de lectura) se borren
$sudo vi /etc/cron.daily/limpia_ftp30
...
#! /bin/bash

startdir=/ftp
max_atime=30

touch $startdir/usuarios_ftp.txt

[ -d $startdir ] || exit -1

find $startdir/ -atime +$max_atime -type f -exec rm -f {} \;

for dir in `find ${startdir}/* -maxdepth 0 -type d || exit`; do [ -z $dir ] && exit ; find ${dir}/* -depth -type d -empty -exec rmdir {} \; ; done > /dev/null 2>&1
...
Los permisos que tiene que tener son:
chmod 755 limpia_ftp30

Algunos comandos de interes
$tree /ftp
$pstree ls
$strace ls
$du -h --max-depth 1 /ftp
$du -h --max-depth 1 /ftp | cut -f 1
Para ver quien esta accediendo al servidor lo hacemos con tcpdump
$tcpdump -i eth0 tcp and port 21



Crear nuevo FTP o borrar usuario

Asi creamos el usuario
$sudo adduser prueba1 --ingroup ftpusers --home /ftp/prueba1 --shell /bin/false
automaticamente se crea el directorio /ftp/prueba1
Si nos falla y no nos deja hacer login en el servidor desde los clientes ftp, podemos poner otra shell
$sudo adduser prueba1 --ingroup ftpusers --home /ftp/prueba1 --shell /bin/sh
Siempre que se crea un usuario se copia el contenido de /etc/skel al nuevo home del usuario creado
Para asignar una contraseña a un usuario
$sudo passwd prueba1
Para borrar un usuario
$sudo userdel prueba1
Despues borramos el directorio que tenia si ya no accede nadie
$rm -fr /ftp/prueba1
Mediante 2 ficheros controlamos la lista de usuarios que pueden acceder al FTP y los que no.
Usuarios que no pueden acceder al ftp
$vi /etc/vsftpd.chroot_list
Usuarios que pueden usar el ftp
$sudo vi /etc/vsftpd.user_list
Una vez que tengamos todo configurado no nos olvidemos de reiniciar el servidor
$sudo /etc/init.d/vsftpd restart

Si queremos usar el navegador iexplorer, firefox... en su barra de direcciones tenemos que poner lo siguiente:

ftp://tuusuario:tupassword@tudominio.com


Salud para todos.



©jc_2009

No hay comentarios:

Publicar un comentario

Nota: solo los miembros de este blog pueden publicar comentarios.