# uname -a

Switch

Mot-clé -

Fil des billets

vendredi 13 mars 2015

Configure sender rate limits to prevent spam, using cluebringer (policyd) with Postfix

This small how-to will show you how to configure cluebringer (aka policyd) to set a per-hour/per-user limit for sent mails. Note that sending to multiple recipient will count like multiple mails were sent.

This how-to is Debian-oriented but should apply to any unix operating system.

Lire la suite...

vendredi 20 février 2015

Set up an incremental backup with duplicity, rsync, and backupninja on Debian

Version française.

This is a not-so-concise how-to about setting up an incremental backup, using Backupninja with Duplicity backend on Debian.

Abstract

If you know what a backup is, you should know there are several types of backups :

  • A full backup is when you just copy all your files, hoping that the hard drive on the backup server will not explode after 3 backups.
  • An incremental backup consist in a base full backup, and the next backups are just "diffs" sent to the backup server, to keep track of modified files.

Obviously, a full backup is easier to read and to restore because it's just plain files, whereas an incremental backup has a specific file format to represent diffs. But considering the gain in speed, bandwidth, and disk space, your choice for a long-term backup solution should be the incremental backup.

The tools

Duplicity is an opensource software similar to rdiff-backup. It creates incremental backups. Duplicity can also encrypt your backups, so they can be safely sent to any remote disk provider. A classic setup for Duplicity would be using rsync as a backend to send files faster to the remote backup server, but you can also use a local drive, a remote FTP server, or an Amazon E3 cloud server. As the title says, I will be using rsync for that setup.

But what about databases ? Databases can't be saved by simply copying files, it could lead to corrupted and unusable data in your backups, so you would use a backup script to fetch your databases before sending it to Duplicity.

Good news : backupninja is the global solution you need. Backupninja is a sort of "backup-master" : it can fetch different type of data (files, databases...) from different sources and sent it to different destinations (plain backup, duplicity, etc). you just have to write a specific config file for each source !

We will use backupninja to fetch our databases, we will add these SQL archives to our files backup, send this to Duplicity backend, and finally send it to our backup server with rsync. And with just 3 config files (one by SQL type, one for Duplicity and rsync).

Let's go !

Lire la suite...

samedi 8 février 2014

Conflict between broken Apache packages makes FCGI angry (mod_fcgid: can't lock process table)

Here is is a quick note on the fix I made today for a messed up Apache server.

The environment

Apache2 + Debian + mod_suexec + mod_fcgi

The problem

The server was down only for PHP-running websites. It triggered a connexion reset when trying to run PHP scripts. Static content and reverse proxies were working correctly, as if nothing was happening.

In the server logs, the following error was present :

mod_fcgid: can't lock process table

The suexec log was showing no anomaly.

The server wasn’t gracefully stopping anymore, and I had to kill him with the -9 signal to stop it.

The cause

Searching around the web was giving me very few clues on the problem. I couldn’t find why the CGI subprocess was broken, it is spawned by Apache and so it should not be missing permissions (there is no CGI daemon listening in Apache setup, contrary to Nginx)

What causes the Apache subprocesses to get spawned ? Either the Apache mpm-workers, or mpm-prefork, or mpm-event or mpm-itk. I knew I was using workers, but a glance in APT installed packages showed me broken packages on workers and ITK. Wait… ITK ?

Actually, I run Puppet, and Puppet was configured to keep Apache ot its latest version from repositories. With the release of a newer version of Apache, it had updated the apache2 package … and installed apache2-mpm-itk while apache2-mpm-workers was still present !

The result was a conflict while trying to spawn CGI processes, and a crash of the subprocess.

The fix

Doing a remove apache2-mpm-itk, and force-reinstall apache2-mpm-workers did the job.

samedi 1 février 2014

Configure Postfix as standalone single-domain SMTP server using Unix users and PAM on Debian

Here is a quick setup to configure Postfix mail server, using existing Unix users.

The server will process mails for only one domain, and every existing user on the server will have a mail box inside his home directory.

Abstract

Postfix is an SMTP server, it receives incoming mail from other SMTP servers, and allows client to send mails to other SMTP servers.

What we don't want is an open mail relay. A mail relay is a SMTP server that take anything from any client, and send it to any SMTP server. We only want trusted users to send emails, to prevent anonymous clients from sending spam.

Incoming mail will be processed either if :

  • The domain name of one of the recipient matches the mail server domain, and the mail user name is also a system user (SMTP servers can send us incoming mails).
  • The client who tries to sends the mail has successfully authenticated.

Postfix authentication for clients can be handled by SASL. SASL is a standard protocol to provide an authentication layer. It can query PAM, or other authentication providers (MySQL users, etc).

Notes :

  • We will use PAM for Unix users SMTP authentication.
  • Unix users are stored in /etc/passwd and their passwords are stored in /etc/shadow.
  • Mails will be stored in the ~/Maildir/ of each users, in Maildir format.

Postfix : installation and configuration

Install Postfix : apt-get install postfix

Answer the questions during installation to setup your mail domain (the "example.com" in user@example.com).

Modify config files :

/etc/postfix/main.cf :

Configure TLS and Maildir :

# TLS parameters
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = mail.example.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = example.com, localhost
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +

home_mailbox = Maildir/

# These are the "no relay" restrictions
smtpd_recipient_restrictions = permit_mynetworks permit_inet_interfaces permit_sasl_authenticated reject_unauth_destination

/etc/postfix/master.cf :

Enable TLS and alternate (submission) ports :

submission inet n       -       -       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       -       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING

SASL : installation and configuration

SASL plugin for Postfix (Cyrus) is part of the dependencies of Postfix server.

Install SASL administration tools : apt-get install sasl2-bin

Enable SASL daemon at startup : edit /etc/default/saslauthd and switch START to yes.

Start it manually for the first time : service saslauthd start

Enable PAM authentication for SASL

Check that PAM is part of the MECHANISMS variable in /etc/default/saslauthd :

MECHANISMS="pam"

Create /etc/pam.d/smtp :

#
# /etc/pam.d/smtp - specify PAM SMTP behavior
#

@include common-auth
@include common-account
@include common-password
@include common-session

Enable SASL for Postfix

Add to /etc/postfix/main.cf :

smtpd_sasl_auth_enable = yes

Create /etc/postfix/sasl/smtpd.conf :

pwcheck_method: saslauthd
mech_list: PLAIN LOGIN

Adjust OPTIONS in /etc/default/saslauthd :

OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd"

Add postfix user to sasl group :

adduser postfix sasl

Configuration check

Restart all services (postfix, salsauthd).

Try authentication using SASL : testsaslauthd -u user -p password

Try authentication from command line, without mail client : https://qmail.jms1.net/test-auth.shtml

Try SMTP reception by sending mail to your domain (your MX fields in domain has to be configured accordingly).

Sources

lundi 25 novembre 2013

Un serveur au régime : faites tourner un serveur complet dans un mouchoir de poche

Introduction

Ce n’est pas la période pour les régimes et pourtant aujourd’hui, dans un billet volontairement cryptique aux non-initiés, je vais vous dévoiler les quelques secrets qui permettent à des nerds invétérés de donner vie à des machines ridiculement pauvres en RAM. Pour la beauté du geste, mais pas que.

Je me souviens que l’on s’est souvent moqué de moi quand je disais qu’avec 512 mégas de RAM on pouvait faire tourner un serveur complet mail+ftp+web+sql. En remplaçant quelques programmes, vous pouvez parfaitement faire tourner votre application web standalone, un noeud de CDN performant, un miroir FTP, ou un relais mail.

Cet article va simplement vous présenter des alternatives, et terminer avec quelques astuces plus générales. Le but est de remplacer notre célèbre LAMP par des solutions moins gourmandes en mémoire.

Remplacer Apache

Pour remplacer Apache, nous avons le choix entre Nginx et Lighttpd (Lighty).

Lighttpd est le serveur le plus léger au monde. Sa structure est très simple, et l’impact d’une connexion en mémoire est très faible.

Nginx est un serveur qui consomme un peu plus au démarrage, mais qui utilise une gestion intelligente de ses connexions ouvertes pour optimiser son impact mémoire.

Inconvénients : oubliez les .htaccess, préparez-vous à faire un peu de configuration pour remplacer votre “a2enmod php5”, et changez vos habitudes pour redémarrer les services.

Remplacer MySQL

Ce n’est pas facile de remplacer MySQL, tellement le nombre de programme qui en dépendent est conséquent. Cependant, si c’est possible, n’hésitez pas une seconde, voici les deux alternatives “lowcost” possibles :

SQLite : une base SQLite est simplement un fichier qui est chargé en mémoire au moment où l’on veut lire dedans. Pas de démon résident, pas d’impact lorsque la base est inactive. Par contre, préparez vous à attendre un peu si votre base est conséquente : lire des données en n’utilisant que le cache disque,  ça peut prendre du temps.

PostgreSQL : PostgreSQL est un peu le nouveau MySQL, mais en mieux. de faible impact mémoire au démarrage, doté de plus de fonctionnalités que MySQL et proposant de meilleures performances, il reste encore marginal mais a tout pour concurrencer les équivalents propriétaires comme Oracle. On peut l’utiliser dans un environnement limité, en configurant correctement les limites dans sa configuration.

Remplacer ProFTPd

Si vous proposez un hébergement, vous proposerez certainement un serveur FTP.

Si les utilisateurs du serveur sont des utilisateurs “de confiance” (ie : que vous connaissez), vous pouvez leur laisser utiliser le serveur SFTP fourni par le serveur SSH (à activer dans la configuration). De très faible impact mémoire, pour une meilleure sécurité et moins de configuration, le protocole SFTP est supporté par la majorité des clients FTP. C’est LA solution des flemmards pour mettre en place un serveur FTP.

Sinon, vous pouvez vous rabattre sur un VSFTPd, qui en plus de vous combler au niveau impact mémoire, vous comblera au niveau rapidité. Il gère aussi le FTPS.

Remplacer Postfix

Si vous n’utilisez pas la réception des mails et que vous ne faites que de l’envoi (avec ou sans smarthost), Exim vous comblera au moins autant que Postfix, vous proposant même sous Debian une interface de configuration “pour les nuls” : dpkg-reconfigure exim4-config.

Éviter la catastrophe

En cas de gonflement inattendu de la mémoire, et lorsque celle-ci commence à manquer, le système d’exploitation commence à sacrifier des programmes pour libérer de la RAM. C’est dommage, on aimerait éviter d’en arriver à de telles extrémités sur un serveur de production.

La solution est assez simple, bien qu’imparfaite : il suffit de rajouter de la SWAP. La SWAP est un fichier d’échange placé sur le disque dur, lorsque il n’y a plus de mémoire en RAM, une partie de la RAM est déchargée (ie copiée) sur la SWAP, pour laisser de la place aux programmes “actifs”. Bien entendu, cette mémoire déchargée devra être rechargée dès lors qu’un programme a besoin d’un bloc mémoire qui a été placé en SWAP, ralentissant le traitement à la vitesse des temps d’accès disque (pas cool).

Faire dormir tout le monde

Ce qui est pénible avec les serveurs, c’est la quantité de RAM qui est là, utilisée en permanence, pour finalement un seul pic d’utilisation. Si on pouvait récupérer la RAM des programmes qui n’interagissent pas avec l’extérieur, et ne les lancer que quand on en a besoin ? Inetd est fait pour ça !

Inetd c’est un “super démon” qui va écouter sur les ports demandés à la place des programmes, et qui va lancer les programmes pour traiter l’événement, dès lors qu’une connexion est ouverte sur un de ses ports d’écoute. On peut donc imaginer avoir un Lighttpd non lancé qui se fait réveiller lorsque Inetd reçoit une connexion sur le port 80. Lighttpd traite alors la requête et s’arrête immédiatement après, laissant la place pour d’autres programmes.

L’inconvénient ici vient des temps de traitement forcément plus longs qu’avec des démons résidents (démarrer le programme prend du temps).

Conclusion

Voilà, c’est à peu près tout, j’espère qu’avec ces petits changements dans votre configuration, vous aurez quelques pistes pour alléger votre serveur, si jamais l’expérience vous tente. ;)

- page 4 de 6 -