Febrero 27

Using SFTP with ProFTPd

ProFTPd is a daemon designed for FTP access. But did you know it also handles the SFTP protocol ? The main advantages over FTP are:

  • the flows are encrypted (auth and data)
  • there are no issues about active/passive modes

These reasons make SFTP more appealing than FTP (or FTPS: too complex)

ProFTPd also brings enhancements over OpenSSH SFTP chroot:

  • you don’t need to expose the port 22 (SSH+SFTP)
  • the settings remain focused on share options
  • you don’t need to tweak sshd_config to allow chrooted SFTP
  • you can manage virtual accounts
  • you can chroot into any directory (OpenSSH’s SFTP requires a root owner)

Method 1: SFTP with ProFTPd (password auth)

This is the easiest one. It consists in declaring virtual users who will have their own home and own password.

Into /etc/proftpd/proftpd.conf

Now enable SFTP with these settings :

SFTPEngine         on

Port               2222
SFTPLog            /var/log/proftpd/sftp.log
TransferLog        /var/log/proftpd/sftp-xferlog

# Host Keys
SFTPHostKey        /etc/ssh/ssh_host_rsa_key
SFTPHostKey        /etc/ssh/ssh_host_dsa_key

# Auth methods
SFTPAuthMethods    password
AuthUserFile       /etc/proftpd/sftp.passwd

# SFTP specific configuration
DefaultRoot        ~

I have arbitrarily chosen the port 2222, but you can use any other port that is not used.

Create the user

Now we create the virtual users config file:

touch /etc/proftpd/sftp.passwd
chown proftpd /etc/proftpd/sftp.passwd
chmod go-rwx /etc/proftpd/sftp.passwd

Now we generate the password, with ‘pwgen’:

PASS=$(pwgen -Bs1 15); echo $PASS
mkpasswd --hash=md5 $PASS

Now create the new virtual user and map his UID and GID on an existing user (i.e. www-data, 33:33):

vi /etc/proftpd/sftp.passwd

virtual1:HASSSSSHHHH:33:33::/var/www/magento/medias:/bin/bash

Restart ProFTPd and test your connexion

/etc/init.d/proftpd restart
sftp -P 2222 virtual1@localhost

Method 2: SFTP with ProFTPd (key auth)

Using private/public key brings a much stronger authentication, moreover if you use a passphrase. I will assume that you already have your keys (else: man ssh-keygen). The procedure remains close to the previous one:

Into /etc/proftpd/proftpd.conf

The SFTP configuration is the same as previous method. But there is a change in the section # Auth methods:

SFTPEngine on

Port                    2222
SFTPLog                 /var/log/proftpd/sftp.log
TransferLog             /var/log/proftpd/sftp-xferlog

# Host Keys
SFTPHostKey             /etc/ssh/ssh_host_rsa_key
SFTPHostKey             /etc/ssh/ssh_host_dsa_key

# Auth methods
SFTPAuthMethods         publickey
SFTPAuthorizedUserKeys  file:/etc/proftpd/sftp.passwd.keys/%u

# SFTP specific configuration
DefaultRoot             ~

Create the users

Our virtual users are going to be stored in a singular way:

  • one config file per virtual user
  • the filename will be interpreted as login
  • in this file, you will copy any public key you need
  • the user MUST exists in the system as well

In our configuration, these users are stored in the folder /etc/proftpd/sftp.passwd:

mkdir /etc/proftpd/sftp.passwd.keys
chown proftpd /etc/proftpd/sftp.passwd.keys
chmod go-rwx /etc/proftpd/sftp.passwd.keys

Now we will create a system user. That’s where ProFTPD documentation lacks, they don’t explain that you need this, nor why. So if we need this physical user it’s because there are several points that ProFTPd can’t define with “key” users :

  • the system rights for the virtual user (classic)
  • his shell (else he can’t interact with the filesystem)
  • his (chrooted) home (the most important point !!)

So let’s create the user virtual2 in the operating system. His home will be chrooted. I suggest you create it with a UID > 5000, in order to easily find these SFTP users in /etc/passwd :

adduser --home /var/www/mangento/dir --uid 5000 virtual2

Now, create the user in ProFTPd. Be carefull, ProFTPd will check the virtual user info with the system user. So their name MUST be exactly the same:

touch /etc/proftpd/sftp.passwd.keys/virtual2

Now fill the file with the SSH public keys you want. You need to convert it in RFC4716 style before:

ssh-keygen -e -f id_rsa.pub > /etc/proftpd/sftp.passwd.keys/virtual2

You can also add as many keys as you want:

cat /etc/proftpd/sftp.passwd.keys/virtual2

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20120924"
AAAAB3NzaC1yc2EAAAABJQAAAIEAu3z7yClfzTgNx18jwcfgSL4L53SsRUAdpbUQ
uhwdHUgPu1NEcVjbvfdff3fgjlfg5hHpBVGQw2IOV+mXSQ8lty1Oi49vVXlxVaLM
n2QS2Ss8daHeAHENth4i3TEffe58jK+JUJutulekOIRaXo+V461zk9hDtrATluPH
ANl6UpE=
---- END SSH2 PUBLIC KEY ----
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "2048-bit RSA"
AAAAB3NzaC1yc2EAAAADAQABAAABAQDJ5j8b7rt32s5e8wcv/MzIMRSvL5EmaysD/XtJWx
XACZ5m1MKq/SC9rDZdzghjgvsqE4eT3TtIK88h44ztr+tXxW6BKgCS203GgBdV5Ng20a6
t06QgBIQ0HlAiTsDW8Rj5Wg18xUsh1NFyx67aI+IAGh58quTd2I9DvKsIyFUsjz9DfLUJA
Ovz/wEGbNsy//PwLr4YrtYu00+EffehAdf46fsjkYhVhW7lpzIwYc7C7Jpmf4UwyDmPpzW
sFZrVokcMGercVF5HJe0ZW2UZOkPYwB4gu1vhdJd972g/+UxdDTLxtYDvtLPMXz7Rc2ixp
5jrV3/7ESy48mgoFonNMSr
---- END SSH2 PUBLIC KEY ----

Restart ProFTPd and test your connexion

/etc/init.d/proftpd restart
sftp -P 2222 virtual2@localhost

Note: proftpd reload is used to crash proftpd. You need to start it then. Therefore restart solution is cleaner.

SFTP and FTP with ProFTPd

If you want to have both FTP and SFTP methods at the same time in ProFTPd, you will need to use a virtual host. First, define your FTP configuration as normally. Then put the whole SFTP configuration into the virtualhost, this way:

# FTP settings
[...]

<VirtualHost PUBLIC_IP_HERE>
    SFTPEngine on

    # Usefull option
    AllowOverwrite     on

	# classical confs 
	Port                    2222
    SFTPLog                 /var/log/proftpd/sftp.log
    [...]

</VirtualHost>

SFTP auth key + password

You can mix both authentication methods if you need to. I will not describe the both procedures again, there are just a few directives to adapt in configuration you need in ProFTPd :

# Auth methods
SFTPAuthMethods         publickey password
SFTPAuthorizedUserKeys  file:/etc/proftpd/sftp.passwd.keys/%u
AuthUserFile            /etc/proftpd/sftp.passwd

Then you have to create both virtual users files as described in previous methods above.

Category: PROFTPD, TIPS AND TRICKS | Los comentarios están deshabilitados en Using SFTP with ProFTPd
Febrero 27

How to Setup Chroot SFTP in Linux (Allow Only SFTP, not SSH)

f you want to setup an account on your system that will be used only to transfer files (and not to ssh to the system), you should setup SFTP Chroot Jail as explained in this article.

In a typical sftp scenario (when chroot sftp is not setup), if you use sftp, you can see root’s file as shown below.

If you want to give sftp access on your system to outside vendors to transfer files, you should not use standard sftp. Instead, you should setup Chroot SFTP Jail as explained below.

Non-Chroot SFTP Environment

In the following example (a typical sftp environment), john can sftp to the system, and view /etc folder and download the files from there.

# sftp john@thegeekstuff.com
john@thegeekstuff's password:
sftp> pwd
Remote working directory: /home/john

sftp> ls
projects  john.txt documents 

sftp> cd /etc
sftp> ls -l passwd
-rw-r--r--    0 0        0            3750 Dec 29 23:09 passwd

sftp> get passwd
Fetching /etc/passwd to passwd
/etc/passwd     100% 3750     3.7KB/s   00:00

Chroot SFTP Environment

In the following example, john can sftp to the system, and view only the directory that you’ve designated for john to perform sftp (i.e /incoming).

When john tries to perform ‘cd /etc’, it will give an error message. Since SFTP is setup in an chroot environment, john cannot view any other files in the system.

# sftp john@thegeekstuff.com
john@thegeekstuff's password:
sftp> pwd
Remote working directory: /home/john

sftp> ls
sftp> cd /etc
Couldn't canonicalise: No such file or directory

Now that you know what Chroot SFTP environment is, let us see how to set this up.

1. Create a New Group

Create a group called sftpusers. Only users who belong to this group will be automatically restricted to the SFTP chroot environment on this system.

# groupadd sftpusers

2. Create Users (or Modify Existing User)

Let us say you want to create an user guestuser who should be allowed only to perform SFTP in a chroot environment, and should not be allowed to perform SSH.

The following command creates guestuser, assigns this user to sftpusers group, make /incoming as the home directory, set /sbin/nologin as shell (which will not allow the user to ssh and get shell access).

# useradd -g sftpusers -d /incoming -s /sbin/nologin guestuser
# passwd guestuser

Verify that the user got created properly.

# grep guestuser /etc/passwd
guestuser:x:500:500::/incoming:/sbin/nologin

If you want to modify an existing user and make him an sftp user only and put him in the chroot sftp jail, do the following:

# usermod -g sftpusers -d /incoming -s /sbin/nologin john

On a related note, if you have to transfer files from windows to Linux, use any one of the sftp client mentioned in this top 7 sftp client list.

3. Setup sftp-server Subsystem in sshd_config

You should instruct sshd to use the internal-sftp for sftp (instead of the default sftp-server).

Modify the the /etc/ssh/sshd_config file and comment out the following line:

#Subsystem       sftp    /usr/libexec/openssh/sftp-server

Next, add the following line to the /etc/ssh/sshd_config file

Subsystem       sftp    internal-sftp
# grep sftp /etc/ssh/sshd_config
#Subsystem      sftp    /usr/libexec/openssh/sftp-server
Subsystem       sftp    internal-sftp

4. Specify Chroot Directory for a Group

You want to put only certain users (i.e users who belongs to sftpusers group) in the chroot jail environment. Add the following lines at the end of /etc/ssh/sshd_config

# tail /etc/ssh/sshd_config
Match Group sftpusers
        ChrootDirectory /sftp/%u
        ForceCommand internal-sftp

In the above:

  • Match Group sftpusers – This indicates that the following lines will be matched only for users who belong to group sftpusers
  • ChrootDirectory /sftp/%u – This is the path that will be used for chroot after the user is authenticated. %u indicates the user. So, for john, this will be /sftp/john.
  • ForceCommand internal-sftp – This forces the execution of the internal-sftp and ignores any command that are mentioned in the ~/.ssh/rc file.

5. Create sftp Home Directory

Since we’ve specified /sftp as ChrootDirectory above, create this directory (which iw equivalent of your typical /home directory).

# mkdir /sftp

Now, under /sftp, create the individual directories for the users who are part of the sftpusers group. i.e the users who will be allowed only to perform sftp and will be in chroot environment.

# mkdir /sftp/guestuser

So, /sftp/guestuser is equivalent to / for the guestuser. When guestuser sftp to the system, and performs “cd /”, they’ll be seeing only the content of the directories under “/sftp/guestuser” (and not the real / of the system). This is the power of the chroot.

So, under this directory /sftp/guestuser, create any subdirectory that you like user to see. For example, create a incoming directory where users can sftp their files.

# mkdir /sftp/guestuser/incoming

6. Setup Appropriate Permission

For chroot to work properly, you need to make sure appropriate permissions are setup properly on the directory you just created above.

Set the owenership to the user, and group to the sftpusers group as shown below.

# chown guestuser:sftpusers /sftp/guestuser/incoming

The permission will look like the following for the incoming directory.

# ls -ld /sftp/guestuser/incoming
drwxr-xr-x 2 guestuser sftpusers 4096 Dec 28 23:49 /sftp/guestuser/incoming

The permission will look like the following for the /sftp/guestuser directory

# ls -ld /sftp/guestuser
drwxr-xr-x 3 root root 4096 Dec 28 23:49 /sftp/guestuser

# ls -ld /sftp
drwxr-xr-x 3 root root 4096 Dec 28 23:49 /sftp

7. Restart sshd and Test Chroot SFTP

Restart sshd:

# service sshd restart

Test chroot sftp environment. As you see below, when gusetuser does sftp, and does “cd /”, they’ll only see incoming directory.

# sftp guestuser@thegeekstuff.com
guestuser@thegeekstuff's password:

sftp> pwd
Remote working directory: /incoming

sftp> cd /
sftp> ls
incoming

When guestuser transfers any files to the /incoming directory from the sftp, they’ll be really located under /sftp/guestuser/incoming directory on the system.

Category: TOOLS | Los comentarios están deshabilitados en How to Setup Chroot SFTP in Linux (Allow Only SFTP, not SSH)
Febrero 12

Iptables DDOS rules

Los firewalls de juniper vienen con una plantilla de configuración contra determinados ataques conocida como screening que previene contra diferentes tipos de ataques.

El objetivo de este artículo es hacer un compendio de directivas que puedan cubrir un espectro de reglas útiles que puedan añadirse a iptables a modo del screening de juniper, siempre con precaución y no haciéndolas permanentes (no grabándolas a fichero), hasta que se compruebe que no se bloquea ningún servicio que no se debiera.

Una de los primeros problemas que nos enfrentaremos con iptables es intentar parar ataques de denegación de servicio, bien sea distribuido bien sea desde un único origen:

ANTIDoS/ANTIDDoS:

Bloqueamos paquetes con determinada longitud:

iptables -A INPUT -p tcp -d IP -m length –length 40:48 -j DROP
Bloqueamos paquetes con determinado ttl:
iptables -A INPUT -p tcp -s 0.0.0.0/0 -d IP -m ttl –ttl 111 -j DROP

SYN FLOOD PREVENTION:

$IPT -N syn-flood
$IPT -A INPUT -i eth+ -p tcp –tcp-flags SYN,ACK,FIN,RST RST -j syn-flood
$IPT -A FORWARD -i eth+ -p tcp –tcp-flags SYN,ACK,FIN,RST RST -j syn-flood
$IPT -A syn-flood -m limit –limit 4/s –limit-burst 16 -j RETURN
$IPT -A syn-flood -m limit –limit 75/s –limit-burst 100 -j RETURN -A syn-flood -j LOG –log-prefix “SYN FLOOD ” –log-tcp-sequence –log-tcp-options –log-ip-options -m limit –limit 1/second
$IPT -A syn-flood -j DROP

UDP FLOOD PREVENTION:

$IPT -A OUTPUT -p udp -m state –state NEW -j ACCEPT
$IPT -A OUTPUT -p udp -m limit –limit 100/s -j ACCEPT
$IPT -A OUTPUT -p udp -j DROP

Limitando el máximo de conexiones al puerto 80 (o otro puerto, en general defensa en capa 7):

$IPT -A INPUT -p tcp –dport 80 -m hashlimit –hashlimit-upto 50/min –hashlimit-burst 80 –hashlimit-mode srcip –hashlimit-name http -j ACCEPT
$IPT -A INPUT -p tcp –dport 80 -j DROP

Limita el máximo número de conexiones por minuto contra apache:

iptables -A INPUT -p tcp –dport 80 -m state –state NEW -m limit –limit 50/minute –limit-burst 200 -j ACCEPT

ICMP FLOOD:
Permite ping, pero a 1 paquete por segundo, evitar ataques ICMP Flood

$IPT -A INPUT -p icmp -m state –state NEW –icmp-type echo-request -m limit –limit 1/s –limit-burst 1 -j ACCEPT
$IPT -A INPUT -p icmp -j DROP

RECENT TABLE:
Por por cada ip en la tabla de recent si hace mas de x hits en x segundos, se descarta.

$IPT -I INPUT -p tcp –syn -m recent –set
$IPT -I INPUT -p tcp –syn -m recent –update –seconds 10 –hitcount 30 -j DROP

Nota: Algunas de las siguientes reglas de bloqueo DDOS (más bien mitigación), utilizan un parámetro como iplimit-above que quizás no venga con iptables que tengas instalado (con un man, deberías de poder ver si viene en la ayuda de iptables). Si es así, quizás te toque compilar el kernel con plugins para iptables/netfilter.

echo “Block DOS – Ping of Death” Bloquea por tamaño de paquetes icmp.
iptables -A INPUT -p ICMP –icmp-type echo-request -m length –length 60:65535 -j ACCEPT
echo “Block DOS – Teardrop” Bloque tráfico de entrada udp fragmentado
iptables -A INPUT -p UDP -f -j DROP
echo “Block DDOS – SYN-flood”
iptables -A INPUT -p TCP –syn -m iplimit –iplimit-above 9 -j DROP
echo “Block DDOS – Smurf”
iptables -A INPUT -m pkttype –pkt-type broadcast -j DROP
iptables -A INPUT -p ICMP –icmp-type echo-request -m pkttype –pkttype broadcast -j DROP
iptables -A INPUT -p ICMP –icmp-type echo-request -m limit –limit 3/s -j ACCEPT
echo “Block DDOS – Connection-flood”
iptables -A INPUT -p TCP –syn -m iplimit –iplimit-above 3 -j DROP
echo “Block DDOS – Fraggle” Bloquea tráfico udp de entrada broadcast y limitándolo a 3 paquetes por segundo
iptables -A INPUT -p UDP -m pkttype –pkt-type broadcast -j DROP
iptables -A INPUT -p UDP -m limit –limit 3/s -j ACCEPT
echo “Block DDOS – Jolt” Bloquea paquetes fragmentados ICMP:
iptables -A INPUT -p ICMP -f -j DROP
echo “Block DDOS – SMBnuke” Esta regla más que para parar un ataque DDOS es para bloquear el acceso al troyano SMBnuke
iptables -A INPUT -p UDP –dport 135:139 -j DROP
iptables -A INPUT -p TCP –dport 135:139 -j DROP
Category: TIPS AND TRICKS | Los comentarios están deshabilitados en Iptables DDOS rules
Febrero 7

Postfix domain rewriting with canonical maps

 

In some cases you want to rewrite all email for a specific domain to another domains. For example all incoming email for example.org should be rewritten to example.com. Postfix uses canonical maps to rewrite domains or mail addresses. Insert the following line to the /etc/postfix/main.cf:

canonical_maps = hash:/etc/postfix/canonical

Create the file /etc/postfix/canonical and add the following line:

@example.org   @example.com

Create the hash map of the canonical file by:

$ postmap /etc/postfix/canonical

Reload Postfix to active the changes.

$ /etc/init.d/postfix reload

All emails send to milo@example.org will now be displayed as milo@example.com in the TO field of the mail client. It’s still necessary to have the address milo@example.com as a local or virtual alias. This is not necessary for the address milo@example.org. But the domain example.org should be listed in the mydestination or virtual_domain option, otherwise Postfix will block all incoming emails for this domain. | In some cases you want to rewrite all email for a specific domain to another domains. For example all incoming email for example.org should be rewritten to example.com. Postfix uses canonical maps to rewrite domains or mail addresses. Insert the following line to the /etc/postfix/main.cf:

canonical_maps = hash:/etc/postfix/canonical

Create the file /etc/postfix/canonical and add the following line:

@example.org   @example.com

Create the hash map of the canonical file by:

$ postmap /etc/postfix/canonical
Category: POSTFIX, TIPS AND TRICKS | Los comentarios están deshabilitados en Postfix domain rewriting with canonical maps
Febrero 6

Debian – Lista de paquetes instalados

 


Para listar el total de paquetes instalados utilizamos el siguiente comando:

dpkg --get-selections

Gracias a este herramienta también es posible exportar la lista de paquetes instalados:

dpkg --get-selections > mis_paquetes

Luego podemos instalarlos en otra máquina:
Obtención de la lista precedente:

dpkg --set-selections < mis_paquetes

Instalación de la lista:

apt-get dselect-upgrade



## Update dpkg's database of known packages
# <strong class="userinput"><code>avail=`mktemp`</code></strong>
# <strong class="userinput"><code>apt-cache dumpavail &gt; "$avail"</code></strong>
# <strong class="userinput"><code>dpkg --merge-avail "$avail"</code></strong>
# <strong class="userinput"><code>rm -f "$avail"</code></strong>
## Update dpkg's selections
# <strong class="userinput"><code>dpkg --set-selections &lt; pkg-list</code></strong>
## Ask apt-get to install the selected packages
# <strong class="userinput"><code>apt-get dselect-upgrade</code></strong>

El comando dpkg –l da la lista de paquetes instalados pero con mayor información. Sin embargo, no es posible utilizarlo para instalar una lista de paquetes.

Category: TOOLS | Los comentarios están deshabilitados en Debian – Lista de paquetes instalados