Si la connexion ssh est en principe très sûre, cette sécurité n'est liée qu'à l'existence d'un seul mot de passe, système de protection devenu insuffisant.
L' authentification de l'utilisateur par clés ssh, assure un meilleur niveau de sécurité.
Nous allons voir comment utiliser putty et se connecter à l'aide d'une authetification par clé depuis un poste sous windows
Installation de putty logiciel pour se connecter en SSH sur le serveurTélécharger l'installeurPage : http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html Lien dernière version à ce jour : http://the.earth.li/~sgtatham/putty/latest/x86/putty-0.60-installer.exe Télécharger le fichier (installer depuis la page) |
|
Génération des clésAllez dans le menu démarrer / tous les programmes / putty |
|
|
Selectionnez SSH-2 RSA |
|
|
Bougez la souris dans la fenetre de puttygen |
|
|
Dans l'écran suivant Cliquez sur Save private key et choisissez un nom de fichier. |
|
|
Selectionné votre clé publique en haut de la fenetre et faite un click droit / copier |
|
Utilisation de puttyLancez putty (menu démarrer / tous les programmes / putty) Dans "host name" entrez le nom ou l'ip de votre serveur : exemple "rXXXXX.ovh.net" ou "111.222.333.444" Entrez alors vos logins / mot de passe quand demandés. |
|
Ajout de la clé publique générée dans les clés acceptées par le serveurDans la fenetre ouverte sur putty
Commande
nano /root/.ssh/authorized_keys2Aller sous la derniere ligne (fleches pour se déplacer) Coller la clé SSH copiée (click droit dans la fenetre de putty) /etc/init.d/ssh restartPour prendre en compte les modification Fermer Putty |
Exemple
from="213.186.50.100" ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAt3XaIhEoRK5sEKm6wtYyazLOx3w+Yv9+bpfEvLftHr2hxZ2TY2A655iwMbgvhHqsMuGEjK9yGkZIQbUgB6HvOgOWOwJSX6Gc9Ac7GuH11xSU8tHDuTQot6fVtgcm2Y/VUFi65Knz9rLHz7h/Zy29ek+UYav5T7juhBIuk57cDxs= root@cache.ovh.net from="::ffff:213.186.50.100" ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAt3XaIhEoRK5sEKm6wtYyazLOx3w+Yv9+bpfEvLftHr2hxZ2TY2A655iwMbgvhHqsMuGEjK9yGkZIQbUgB6HvOgOWOwJSX6Gc9Ac7GuH11xSU8tHDuTQot6fVtgcm2Y/VUFi65Knz9rLHz7h/Zy29ek+UYav5T7juhBIuk57cDxs= root@cache.ovh.net ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAkyyXySnF051RkltZA5QBa6vCEXquRw0zyY4LSmSRhEUbzcZFWuGJpyn/eAQelxzWWE00N03ekM+5OuErhT6rWONC7rvrYvmwdIsdC4ILjdD4Zdse1OfW2RULZqvZOi9ZAW6vLCYEI6RWjbU9F1MhQJKe1YgFtIc87u6y0aPRd3E= rsa-key-20080318 |
Nous allons maintenant voir comment nous connecter grâce aux clés généréesSur votre poste ouvrez la clé privée que vous avez enregistré |
|
Maintenant vous pouvez ouvrir votre session avec authentification par cléSoit en ouvrant putty, selectionnant votre session et en cliquant sur "open" |
|
|
Soit en faisant un click droit sur l'icone pageant situé dans le panneau en bas à droite de votre écran |
|
Entrez alors votre identifiant ("root" par defaut)
Affiche
Authenticating with public key "rsa-key-20080318" from agent Cela veut dire que l'authentification par clé marche (ce qui est affiché entre guillemets peut varier). |
|
Désactivation de l'authentification par mot de passeNous allons désactiver par mesure de sécurité l'authetification par mot de passe qui est moins sécurisée et ne nous est plus utile ATTENTION : bien garder son fichier de clé privé (faites des sauvegardes !!!) |
Ouvrez une session SSH via putty vers votre serveur
Commande
nano /etc/ssh/sshd_configRemplacer #PasswordAuthentication yesPar PasswordAuthentication noPour prendre en compte les modifications : /etc/init.d/ssh restart |
Exemple
|
Gestion des clésPageant va "gérer" vos clés Avant d'ouvrir une session ssh sous putty ouvrez votre clé.
IMPORTANT : |
Malgrès les mesures déja prises, des "pirates" vont tenter d'acceder à votre serveur en SSH.
Pour accroitre encore la sécurisé et pour épargner un certain travail au serveur nous allons changer le port SSH de notre serveur.
En changeant ce port ces "pirates" ne pourront donc plus contacter notre serveur et donc tenter quoi que ce soit de ce coté la.
De notre coté il faudra bien sur indiquer à notre client SSH sur quel port se connecter
Nous allons dire à SSH d'écouter sur un autre port.
Par défaut j'ai mis le port 6006, mais vous pouvez bien entendu utiliser celui que vous voulez (>1000)
Mais nous allons aussi le laisser écouter sur le port 22 pour que OVH puisse se coonnecter sur le serveur en cas de soucis
Nous allons empecher l'acces à SSH par le port 22 plus tard à l'aide de iptables
nano /etc/ssh/sshd_configAjouter sous "Port 22"
Port 6006Pour prendre en compte les modifications
/etc/init.d/ssh restart
# Package generated configuration file # See the sshd(8) manpage for details # What ports, IPs and protocols we listen for Port 22 Port 6006 # Use these options to restrict which interfaces/protocols sshd will bind to #ListenAddress :: #ListenAddress 0.0.0.0 Protocol 2 # HostKeys for protocol version 2 HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_dsa_key #Privilege Separation is turned on for security UsePrivilegeSeparation yes # Lifetime and size of ephemeral version 1 server key KeyRegenerationInterval 3600 ServerKeyBits 768 # Logging SyslogFacility AUTH LogLevel INFO # Authentication: LoginGraceTime 120 PermitRootLogin yes StrictModes yes RSAAuthentication yes PubkeyAuthentication yes #AuthorizedKeysFile %h/.ssh/authorized_keys # Don't read the user's ~/.rhosts and ~/.shosts files IgnoreRhosts yes # For this to work you will also need host keys in /etc/ssh_known_hosts RhostsRSAAuthentication no # similar for protocol version 2 HostbasedAuthentication no # Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication #IgnoreUserKnownHosts yes # To enable empty passwords, change to yes (NOT RECOMMENDED) PermitEmptyPasswords no # Change to yes to enable challenge-response passwords (beware issues with # some PAM modules and threads) ChallengeResponseAuthentication no # Change to no to disable tunnelled clear text passwords PasswordAuthentication no # Kerberos options #KerberosAuthentication no #KerberosGetAFSToken no #KerberosOrLocalPasswd yes #KerberosTicketCleanup yes # GSSAPI options #GSSAPIAuthentication no #GSSAPICleanupCredentials yes X11Forwarding yes X11DisplayOffset 10 PrintMotd no PrintLastLog yes TCPKeepAlive yes #UseLogin no #MaxStartups 10:30:60 #Banner /etc/issue.net # Allow client to pass locale environment variables AcceptEnv LANG LC_* Subsystem sftp /usr/lib/openssh/sftp-server UsePAM yes
Ce firewall va
- Autoriser la connection Iscsi (vers notre disque sur le SAN pour le RPS)
- Autoriser les connections déja établies (évite de vous couper votre connection SSH
- Autoriser les connections SSH sur le port 22 pour OVH et sur le port 6006 pour l'exterieur (à adapter selon le port que vous aurez choisit)
- Autoriser les connections sortantes des serveurs DNS, FTP, HTTP, NTP, OCO et RTM(monitorings OVH)
- Autoriser les requètes entrantes HTTP, OCO, FTP
- Autoriser les connection sortantes sur le port 587 pour l'envoie de mails locaux vers google apps
- Autoriser le ping pour OVH sans limites et 3 pings par secondes depuis l'exterieur
- Refuser tout le reste.
OVH nous ping depuis plusieurs serveur afin de vérifier qu'il n'y a pas de soucis sur notre machine.
Un de ces serveurs varie selon l'IP de notre serveur, il va donc falloir lui autoriser le ping
L'ip de ce serveur est l'ip réelle (pas fail over) de notre serveur avec 250 pour les derniers chiffres
Sur un serveur dédié normal il s'agit de l'ip indiquée lors de l'installation du serveur
Sur un RPS il va falloir la trouver (l'ip indiquer dans le mail d'installation étant notre ip fail over)
Pour cela :
ifconfigIl s'agit d l'ip indiquée dans inet adr
eth0 Lien encap:Ethernet HWaddr 00:00:00:00:00:00
inet adr:91.121.121.121 Bcast:91.121.121.255 Masque:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1392267 errors:0 dropped:0 overruns:0 frame:0
TX packets:2079783 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:1000
RX bytes:292619120 (279.0 MiB) TX bytes:2694706412 (2.5 GiB)
Interruption:16 Adresse de base:0x2000
eth0:0 Lien encap:Ethernet HWaddr 00:00:00:00:00:00
inet adr:87.98.98.98 Bcast:87.255.255.255 Masque:255.255.255.255
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Interruption:16 Adresse de base:0x2000
lo Lien encap:Boucle locale
inet adr:127.0.0.1 Masque:255.0.0.0
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:10827 errors:0 dropped:0 overruns:0 frame:0
TX packets:10827 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:0
RX bytes:2243076 (2.1 MiB) TX bytes:2243076 (2.1 MiB)
Notre ip réelle est donc 91.121.121.121 l'ip du serveur OVH qui nous ping sera donc 91.121.121.250
Elle sera à adapter dans le script de firewall à l'endroit indiqué (adaptez selon votre ip)
Il devra être lancé au démarrage du serveur
nano /etc/init.d/firewallAjouter au fichier normalement vide le code à droite
chmod +x /etc/init.d/firewallPour rendre notre script exécutable
/etc/init.d/firewall startPour lancer le firewall
update-rc.d firewall defaultsPour lancer notre script au démarrage du serveur
#!/bin/sh
case "$1" in
start)
#Iscsi
/sbin/iptables -A OUTPUT -p tcp --dport 3260 -m state --state NEW,ESTABLISHED -j ACCEPT
echo - Iscsi : [OK]
# Ne pas casser les connexions etablies
/sbin/iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
/sbin/iptables -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
echo - Ne pas casser les connexions établies : [OK]
# Autoriser loopback
iptables -t filter -A INPUT -i lo -j ACCEPT
iptables -t filter -A OUTPUT -o lo -j ACCEPT
echo - Autoriser loopback : [OK]
# Autoriser SSH
/sbin/iptables -A INPUT -i eth0 -p tcp --dport 22 --source cache.ovh.net -j ACCEPT
/sbin/iptables -t filter -A INPUT -p tcp --dport 6006 -j ACCEPT
echo - Autoriser SSH : [OK]
# Autoriser les requetes DNS, FTP, HTTP, NTP, OCO
iptables -t filter -A OUTPUT -p tcp --dport 21 -j ACCEPT
iptables -t filter -A OUTPUT -p tcp --dport 79 -j ACCEPT
iptables -t filter -A OUTPUT -p tcp --dport 80 -j ACCEPT
iptables -t filter -A OUTPUT -p tcp --dport 53 -j ACCEPT
iptables -t filter -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -t filter -A OUTPUT -p udp --dport 123 -j ACCEPT
echo - Autoriser les requetes DNS, FTP, HTTP, NTP, OCO : [OK]
# HTTP
iptables -t filter -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -t filter -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -t filter -A INPUT -p tcp --dport 8443 -j ACCEPT
echo - Autoriser serveur Apache : [OK]
# OCO
iptables -t filter -A INPUT -p tcp --dport 79 -j ACCEPT
echo - Autoriser serveur OCO : [OK]
# DNS
iptables -t filter -A INPUT -p tcp --dport 53 -j ACCEPT
iptables -t filter -A INPUT -p udp --dport 53 -j ACCEPT
echo - Autoriser serveur DNS : [OK]
# FTP
iptables -t filter -A INPUT -p tcp --dport 20 -j ACCEPT
iptables -t filter -A INPUT -p tcp --dport 21 -j ACCEPT
iptables -t filter -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
echo - Autoriser serveur FTP : [OK]
# Mail
iptables -t filter -A OUTPUT -p tcp --dport 587 -j ACCEPT
echo - Autoriser serveur Mail : [OK]
# RTM
/sbin/iptables -t filter -A OUTPUT -p udp --dport 6100:6200 -j ACCEPT
echo - Autoriser monitoring RTM : [OK]
#Ping OVH
/sbin/iptables -A INPUT -i eth0 -p icmp --source proxy.ovh.net -j ACCEPT
/sbin/iptables -A INPUT -i eth0 -p icmp --source proxy.p19.ovh.net -j ACCEPT
/sbin/iptables -A INPUT -i eth0 -p icmp --source proxy.rbx.ovh.net -j ACCEPT
/sbin/iptables -A INPUT -i eth0 -p icmp --source ping.ovh.net -j ACCEPT
/sbin/iptables -A INPUT -i eth0 -p icmp --source 91.121.121.250 -j ACCEPT # IP = aaa.bbb.ccc obtenue selon la règle precedente
/sbin/iptables -A INPUT -i eth0+ -p icmp --icmp-type echo-request -m limit --limit 3/s -j ACCEPT
echo - Ping OVH : [OK]
# on refuse tout le reste
/sbin/iptables -A INPUT -j REJECT
/sbin/iptables -A OUTPUT -j REJECT
/sbin/iptables -A FORWARD -j REJECT
exit 0
;;
stop)
/sbin/iptables -F INPUT
/sbin/iptables -F OUTPUT
/sbin/iptables -F FORWARD
exit 0
;;
*)
echo "Usage: /etc/init.d/firewall {start|stop}"
exit 1
;;
esac
echo "APT::Cache-Limit \"141943904\";" >> /etc/apt/apt.conf.d/00configperso
nano /etc/apt/sources.listAjouter à la fin
deb http://packages.dotdeb.org etch all
deb-src http://packages.dotdeb.org etch all
deb ftp://mir1.ovh.net/debian/ etch main deb-src ftp://mir1.ovh.net/debian/ etch main deb http://security.debian.org/ etch/updates main deb-src http://security.debian.org/ etch/updates main deb http://packages.dotdeb.org etch all deb-src http://packages.dotdeb.org etch all
dpkg-reconfigure locales
cocher fr_FR@euro ISO -8859-15 et fr_FR ISO-8859-1 et fr_FR.UTF-8 UFT-8
Cocher en_US ISO-8859-1 et en_US.ISO-8859-15 et en_US.UTF-8
Actif par défaut : fr_FR
dpkg-reconfigure debconf
choisir dialog
puis medium(intermédiaire)
mv /var/log /home/ ln -s /home/log /var/log
aptitude update aptitude upgrade
aptitude install dpkg-dev
aptitude install g++
aptitude install gcc
wget ftp://ftp.ovh.net/made-in-ovh/rtm/install_rtm.sh -O install_rtm.sh sh install_rtm.sh
Nous allons ici définir les dossiers et fichiers installés automatiquement pour chaque domaine.
mkdir /etc/skel/cgi-bin mkdir /etc/skel/www mkdir /etc/skel/logs mkdir /etc/skel/www/awstats echo " domaine installe
" >> /etc/skel/www/index.html echo "" >> /etc/skel/www/test.php
aptitude install bind9
Un serveur DNS récursif est dit ouvert lorsqu'il répond à des requêtes du monde entier (et pas seulement de son réseau local, comme il devrait le faire).
Il peut alors servir de relais pour l'attaque par déni de service, engageant ainsi potentiellement la responsabilité de son administrateur.
nano /etc/bind/named.conf.optionsajouter après directory "/var/cache/bind";
allow-recursion { localhost; };
ajouter à la fin du fichier
logging {
category lame-servers{ null; };
};
Redémarrer Bind pour prendre en compte la modification :
/etc/init.d/bind9 restart
options {
directory "/var/cache/bind";
allow-recursion { localhost; };
// If there is a firewall between you and nameservers you want
// to talk to, you might need to uncomment the query-source
// directive below. Previous versions of BIND always asked
// questions using port 53, but BIND 8.1 and later use an unprivileged
// port by default.
// query-source address * port 53;
// If your ISP provided one or more IP addresses for stable
// nameservers, you probably want to use them as forwarders.
// Uncomment the following block, and insert the addresses replacing
// the all-0's placeholder.
// forwarders {
// 0.0.0.0;
// };
auth-nxdomain no; # conform to RFC1035
listen-on-v6 { any; };
};
logging {
category lame-servers{ null; };
};
aptitude install apache2 aptitude install apache2-prefork-dev
Suexec est un élément de apache qui en association avec suphp va contribuer à protéger notre système.
Mais Le paquet debian Apache2 est compilé avec un docroot dans /var/www, or nous mettrons nos sites dans /home.
Nous devons donc recompiler suexec afin qu'il tienne compte de ce changement, et ne bloque pas notamment l'exécution des scripts perl.
cd / apt-get update apt-get source apache2 cd apache2-2.2.3/support/
nano suexec.hRemplacer
#define AP_HTTPD_USER "www"par
#define AP_HTTPD_USER "www-data"Remplacer
#define AP_USERDIR_SUFFIX "public_html"par
#define AP_USERDIR_SUFFIX "www"Remplacer
#define AP_LOG_EXEC DEFAULT_EXP_LOGFILEDIR "/suexec_log" /* Need me? */par
#define AP_LOG_EXEC "/var/log/apache2/suexec.log" /* Need me? */Remplacer
#define AP_DOC_ROOT DEFAULT_EXP_HTDOCSDIRpar
#define AP_DOC_ROOT "/home"
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file suexec.h * @brief user-definable variables for the suexec wrapper code. * (See README.configure on how to customize these variables.) */ #ifndef _SUEXEC_H #define _SUEXEC_H /* * Include ap_config_layout so we can work out where the default htdocsdir * and logsdir are. */ #include "ap_config_layout.h" /* * HTTPD_USER -- Define as the username under which Apache normally * runs. This is the only user allowed to execute * this program. */ #ifndef AP_HTTPD_USER #define AP_HTTPD_USER "www-data" #endif /* * UID_MIN -- Define this as the lowest UID allowed to be a target user * for suEXEC. For most systems, 500 or 100 is common. */ #ifndef AP_UID_MIN #define AP_UID_MIN 100 #endif /* * GID_MIN -- Define this as the lowest GID allowed to be a target group * for suEXEC. For most systems, 100 is common. */ #ifndef AP_GID_MIN #define AP_GID_MIN 100 #endif /* * USERDIR_SUFFIX -- Define to be the subdirectory under users' * home directories where suEXEC access should * be allowed. All executables under this directory * will be executable by suEXEC as the user so * they should be "safe" programs. If you are * using a "simple" UserDir directive (ie. one * without a "*" in it) this should be set to * the same value. suEXEC will not work properly * in cases where the UserDir directive points to * a location that is not the same as the user's * home directory as referenced in the passwd file. * * If you have VirtualHosts with a different * UserDir for each, you will need to define them to * all reside in one parent directory; then name that * parent directory here. IF THIS IS NOT DEFINED * PROPERLY, ~USERDIR CGI REQUESTS WILL NOT WORK! * See the suEXEC documentation for more detailed * information. */ #ifndef AP_USERDIR_SUFFIX #define AP_USERDIR_SUFFIX "www" #endif /* * LOG_EXEC -- Define this as a filename if you want all suEXEC * transactions and errors logged for auditing and * debugging purposes. */ #ifndef AP_LOG_EXEC #define AP_LOG_EXEC "/var/log/apache2/suexec.log" /* Need me? */ #endif /* * DOC_ROOT -- Define as the DocumentRoot set for Apache. This * will be the only hierarchy (aside from UserDirs) * that can be used for suEXEC behavior. */ #ifndef AP_DOC_ROOT #define AP_DOC_ROOT "/home" #endif /* * SAFE_PATH -- Define a safe PATH environment to pass to CGI executables. * */ #ifndef AP_SAFE_PATH #define AP_SAFE_PATH "/usr/local/bin:/usr/bin:/bin" #endif #endif /* _SUEXEC_H */
touch /var/log/apache2/suexec.log
cd .. ./configure make suexec
cp /usr/lib/apache2/suexec /usr/lib/apache2/suexec.save cp ./support/suexec /usr/lib/apache2/suexec
cd / rm -rf apache2*.*
nano /etc/apache2/ports.confAjouter
Listen 443
Listen 80 Listen 443
nano /etc/apache2/mods-available/userdir.confRemplacer
UserDir public_htmlpar
UserDir www
nano /etc/apache2/conf.d/charsetRemplacer
#AddDefaultCharset UTF8par
AddDefaultCharset ISO-8859-1
AddDefaultCharset ISO-8859-1
cd /etc/apache2 openssl genrsa -out server.key 1024 openssl req -new -x509 -days 3650 -key server.key -out server.crt
Remplir les renseignements demandés
Ce chapitre va nous permetre d'adapte apache à notre serveur :
- Limiter le nombre de client simultané gérale en fonction de la mémoire
- Limiter l'impacte d'une attaque DOS
- Limiter les infos que donne apache lors de ses réponses
- Sécuriser l'accès à certaines parties du système de fichier
- Monitorer apache via collectd
nano /etc/apache2/apache2.confRemplacer
KeepAliveTimeout 15Par
KeepAliveTimeout 20Modifier
RemplacerStartServers 2 MaxClients 80 MinSpareThreads 25 MaxSpareThreads 80 ThreadsPerChild 5 MaxRequestsPerChild 2000
ServerTokens FullPar
ServerTokens ProdRemplacer
ServerSignature OnPar
ServerSignature OffModifier
Ajouter à la fin du fichierSetHandler server-status Order deny,allow Deny from all Allow from 127.0.0.1 localhost ExtendedStatus On
Pour prendre en compte les modifications :order deny,allow deny from all Options None AllowOverride None order deny,allow allow from all AllowOverride all Options -MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec order deny,allow allow from all AllowOverride Options Indexes Limit AuthConfig Options -MultiViews -Indexes SymLinksIfOwnerMatch IncludesNoExec order deny,allow allow from all AllowOverride Limit AuthConfig Options -MultiViews -Indexes
/etc/init.d/apache2 force-reload
aptitude install exim4
petits fichiers / smarthost(SMTP ou fetchmail) / nom du rps / 127.0.0.1
laisser vide / laisser vide / smtp.gmail.com::587 / non
aptitude install php5-cgi
Taper "Oui" quand demander
aptitude install php5-imap php5-gd php5-mysql php5-pear php5-dev php5-cli php5-curl php5-imagick php5-mcrypt php5-mhash
Taper "Oui" quand demander
OK / oui / oui
aptitude install libapache2-mod-suphp suphp-common
nano /etc/suphp/suphp.confModifier
docroot=/ check_vhost_docroot=false
[global] ;Path to logfile logfile=/var/log/suphp/suphp.log ;Loglevel loglevel=info ;User Apache is running as webserver_user=www-data ;Path all scripts have to be in docroot=/ ;Path to chroot() to before executing script ;chroot=/mychroot ; Security options allow_file_group_writeable=false allow_file_others_writeable=false allow_directory_group_writeable=false allow_directory_others_writeable=false ;Check wheter script is within DOCUMENT_ROOT check_vhost_docroot=false ;Send minor error messages to browser errors_to_browser=false ;PATH environment variable env_path=/bin:/usr/bin ;Umask to set, specify in octal notation umask=0077 ; Minimum UID min_uid=100 ; Minimum GID min_gid=100 [handlers] ;Handler for php-scripts x-httpd-php=php:/usr/bin/php-cgi ;Handler for CGI-scripts x-suphp-cgi=execute:!self
a2enmod suphp a2enmod userdir a2enmod suexec a2enmod ssl a2enmod status a2enmod deflate a2enmod rewriteRedémarrer Apache2 pour prendre en compte la modification
/etc/init.d/apache2 force-reload
Awstats va nous permetre d'afficher des pages de statistiques de visites des sites aux propriétaires de ceux ci
Par mesure de sécurité et de bonne gestion de la charge du serveur, nous allons nous même gérer la génération de ces statistiques
Et n'afficher que le résultat sous forme de pages html aux propriétaires des sites
aptitude install awstatsCopie des fichiers dont nous aurons besoin
cp /usr/share/doc/awstats/examples/awstats_buildstaticpages.pl /usr/lib/cgi-bin/ mkdir /usr/share/apache2/icons/awstats cp -R /usr/share/awstats/icon/* /usr/share/apache2/icons/awstats
Nous allons ici établie la configuration générale de awstats pour tous les domaines
Le reste de la configuration particulière à chaque domaine sera faite lors de l'installation du domaine
nano /etc/awstats/awstats.conf.local
Ajouter ce qui est indiqué à droite
LogType=W LogFormat=1 LogSeparator=" " HostAliases="localhost 127.0.0.1" DNSLookup=1 DirData="/var/lib/awstats" DirCgi="/cgi-bin" DirIcons="/icons/awstats/" AllowToUpdateStatsFromBrowser=0 AllowFullYearView=0 EnableLockForUpdate=0 DNSStaticCacheFile="dnscache.txt" DNSLastUpdateCacheFile="dnscachelastupdate.txt" SkipDNSLookupFor="" CreateDirDataIfNotExists=0 BuildHistoryFormat=text BuildReportFormat=html SaveDatabaseFilesWithPermissionsForEveryone=0 PurgeLogFile=0 KeepBackupOfHistoricFiles=1 DefaultFile="index.html" SkipHosts="" SkipUserAgents="" SkipFiles="" SkipReferrersBlackList="" OnlyHosts="" OnlyUserAgents="" OnlyFiles="" NotPageList="css js class gif jpg jpeg png bmp ico swf" ValidHTTPCodes="200 304" ValidSMTPCodes="1 250" AuthenticatedUsersNotCaseSensitive=0 URLNotCaseSensitive=0 URLWithAnchor=0 URLQuerySeparators="?;" URLWithQuery=0 URLWithQueryWithOnlyFollowingParameters="" URLWithQueryWithoutFollowingParameters="" URLReferrerWithQuery=0 WarningMessages=1 ErrorMessages="" DebugMessages=0 NbOfLinesForCorruptedLog=50 WrapperScript="" DecodeUA=0 MiscTrackerUrl="" LevelForBrowsersDetection=2 LevelForOSDetection=2 LevelForRefererAnalyze=2 LevelForRobotsDetection=2 LevelForSearchEnginesDetection=2 LevelForKeywordsDetection=2 LevelForFileTypesDetection=2 LevelForWormsDetection=0 UseFramesWhenCGI=1 DetailedReportsOnNewWindows=1 Expires=0 Lang="auto" DirLang="/usr/share/awstats/lang" ShowMenu=1 ShowSummary=UVPHB ShowMonthStats=UVPHB ShowDaysOfMonthStats=VPHB ShowDaysOfWeekStats=PHB ShowHoursStats=PHB ShowDomainsStats=PHB ShowHostsStats=PHBL ShowAuthenticatedUsers=0 ShowRobotsStats=HBL ShowWormsStats=0 ShowEMailSenders=0 ShowEMailReceivers=0 ShowSessionsStats=1 ShowPagesStats=PBEX ShowFileTypesStats=HB ShowFileSizesStats=0 ShowOSStats=1 ShowBrowsersStats=1 ShowScreenSizeStats=0 ShowOriginStats=PH ShowKeyphrasesStats=1 ShowKeywordsStats=1 ShowMiscStats=a ShowHTTPErrorsStats=1 ShowSMTPErrorsStats=0 ShowClusterStats=0 AddDataArrayMonthStats=1 AddDataArrayShowDaysOfMonthStats=1 AddDataArrayShowDaysOfWeekStats=1 AddDataArrayShowHoursStats=1 IncludeInternalLinksInOriginSection=0 MaxNbOfDomain = 10 MinHitDomain = 1 MaxNbOfHostsShown = 10 MinHitHost = 1 MaxNbOfLoginShown = 10 MinHitLogin = 1 MaxNbOfRobotShown = 10 MinHitRobot = 1 MaxNbOfPageShown = 10 MinHitFile = 1 MaxNbOfOsShown = 10 MinHitOs = 1 MaxNbOfBrowsersShown = 10 MinHitBrowser = 1 MaxNbOfScreenSizesShown = 5 MinHitScreenSize = 1 MaxNbOfWindowSizesShown = 5 MinHitWindowSize = 1 MaxNbOfRefererShown = 10 MinHitRefer = 1 MaxNbOfKeyphrasesShown = 10 MinHitKeyphrase = 1 MaxNbOfKeywordsShown = 10 MinHitKeyword = 1 MaxNbOfEMailsShown = 20 MinHitEMail = 1 FirstDayOfWeek=1 ShowFlagLinks="" ShowLinksOnUrl=1 UseHTTPSLinkForUrl="" MaxLengthOfShownURL=64 HTMLHeadSection="" HTMLEndSection="" Logo="awstats_logo6.png" LogoLink="http://awstats.sourceforge.net" BarWidth = 260 BarHeight = 90 StyleSheet="" color_Background="FFFFFF" color_TableBGTitle="CCCCDD" color_TableTitle="000000" color_TableBG="CCCCDD" color_TableRowTitle="FFFFFF" color_TableBGRowTitle="ECECEC" color_TableBorder="ECECEC" color_text="000000" color_textpercent="606060" color_titletext="000000" color_weekend="EAEAEA" color_link="0011BB" color_hover="605040" color_u="FFAA66" color_v="F4F090" color_p="4477DD" color_h="66DDEE" color_k="2EA495" color_s="8888DD" color_e="CEC2E8" color_x="C1B2E2" LoadPlugin="hashfiles" ExtraTrackedRowsLimit=500
Un fichier que nous allons creer va lancer la génération des stats pour chaque domaines configuré
Ce fichier sera lancer toutes les heures par une tache cron, et il va générer les stats des sites 1 par 1
plutot que tout en même temp pour ne pas trop surcharger le serveur
echo '#!/bin/sh' >> /etc/awstats/awstats.shPour le rendre exécutable
chmod +x /etc/awstats/awstats.sh
useradd -s /sbin/logolin -g users awstats chown awstats:users -R /var/lib/awstats chown awstats:users -R /etc/awstats/awstats.sh
echo '36 * * * * awstats /etc/awstats/awstats.sh >/dev/null' >> /etc/cron.d/awstatsPour prendre en compte la modification
/etc/init.d/cron restart
aptitude install mysql-server-5.0
Taper "Oui" quand demander
mot de passe root mysql / non
aptitude install phpmyadmin
apache ssl / admin / mot de passe
nano /usr/share/phpmyadmin/.htaccessRemplacer
Options +FollowSymLinks -Indexespar
# Options +FollowSymLinks -Indexes
Celui ci va servir pour l'accès au vhost phpmyadmin.
useradd -s /sbin/logolin -g users phpmyadmin
chown -R phpmyadmin:users /usr/share/phpmyadmin chown -R phpmyadmin:users /etc/phpmyadmin
aptitude install proftpd
indépendamment
Pour suprimer la gestion de l'ipV6 (non encore supportée sur les RPS
Et Chrooter (bloquer) l'utilisateur dans son repertoire
nano /etc/proftpd/proftpd.confRedémarrer proftpd pour prendre en compte ces modifications
/etc/init.d/proftpd restart
UseIPv6 onpar
UseIPv6 offPour chrooter l'utilisateur dans son répertoire
DefaultRoot ~
aptitude install fail2ban
Nous allons configurer fail2ban pour bannir les tentatives de bruteforce durant 10 minutes (bantime en secondes) toutes les 5 (maxretry) tentatives erronées sur ssh,
erreurs authentification apache, scan de fichiers apache, accès FTP.
Nous ne protégeons pas les emails, étant donné que nous avons juste un serveur smtp local non utilisable depuis l'extérieur.
nano /etc/fail2ban/jail.local
[DEFAULT]
# "ignoreip" can be an IP address, a CIDR mask or a DNS host
#ignoreip = 127.0.0.1 192.168.0.99
bantime = 600
maxretry = 3
# "backend" specifies the backend used to get files modification. Available
# options are "gamin", "polling" and "auto".
# yoh: For some reason Debian shipped python-gamin didn't work as expected
# This issue left ToDo, so polling is default backend for now
backend = polling
#
# Destination email address used solely for the interpolations in
# jail.{conf,local} configuration files.
#destemail = root@localhost
# Default action to take: ban only
action = iptables[name=%(__name__)s, port=%(port)s]
[ssh]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
[apache]
enabled = true
port = http
filter = apache-auth
logpath = /home/*/logs/error.log
maxretry = 5
[apache-noscript]
enabled = false
port = http
filter = apache-noscript
logpath = /home/*/logs/error.log
maxretry = 5
[proftpd]
enabled = true
port = ftp
filter = proftpd
logpath = /home/log/proftpd/proftpd.log
maxretry = 5
[proftpd2]
enabled = true
port = ftp
filter = proftpd2
logpath = /home/log/proftpd/proftpd.log
maxretry = 5
Nous allons modifier le filtre par défaut de proftpd car celui proposé est non fonctionnel :
nano /etc/fail2ban/filter.d/proftpd.confModifier
failregex = \(\S+\[\]\)[: -]+ USER \S+: no such user found from \S+ \[\S+\] to \S+:\S+$
# Fail2Ban configuration file # # Author: Yaroslav Halchenko # # $Revision: 331 $ # [Definition] # Option: failregex # Notes.: regex to match the password failures messages in the logfile. The # host must be matched by a group named "host". The tag "" can # be used for standard IP/hostname matching. # Values: TEXT # failregex = \(\S+\[ \]\)[: -]+ USER \S+: no such user found from \S+ \[\S+\] to \S+:\S+$ # Option: ignoreregex # Notes.: regex to ignore. If this regex matches, the line is ignored. # Values: TEXT # ignoreregex =
Nous allons ajouter un autre filtre pour proftpd car le premier ne gère que les utilisateur invalides, nous allons donc ajouter la destion des mot de passe invalides :
nano /etc/fail2ban/filter.d/proftpd2.confAjouter
[Definition] failregex = \(\S+\[Puis nous allons redémarrer fail2ban pour prendre en compte les modifications :\]\)[: -]+ USER \S+ \(Login failed\): Incorrect password\.$
/etc/init.d/fail2ban restart
[Definition] failregex = \(\S+\[\]\)[: -]+ USER \S+ \(Login failed\): Incorrect password\.$
Vous pouvez biensur régler à votre convenant les valeures de bantime (temp de bannisement en secondes) et de maxretry (nombre d'erreures acceptées avant bannisement).
Ou encore ne pas surveiller certaines ip (la votre par exemple si vous avez une ip fixe) afin que même en cas d'erreures multiples vous ne vous retrouviez pas banni de votre serveur (décommenter la ligne #ignoreip et ajouter votre ip).
Logwatch va nous aider à surveiller nos logs.
En effet, rien de plus fastidieux pour ne pas dire impossible de parcourir l'intégralité de nos logs tous les jours à la recherche d'anomalies.
Logwatch va nous y aider : il va parcourir pour nous tous nos logs et va nous envoyer une fois par jour un email récapitulatif des anomalies trouvées.
Mais attention, n'étant pas exhaustif ce programme n'est pas une sécurité absolue à lui seule.
aptitude install logwatch
nano /usr/share/logwatch/default.conf/logwatch.confModifier
MailTo = adresse.email.valide@domaine.tld Detail = Med
######################################################## # This was written and is maintained by: # Kirk Bauer# # Please send all comments, suggestions, bug reports, # etc, to kirk@kaybee.org. # ######################################################## # NOTE: # All these options are the defaults if you run logwatch with no # command-line arguments. You can override all of these on the # command-line. # You can put comments anywhere you want to. They are effective for the # rest of the line. # this is in the format of = . Whitespace at the beginning # and end of the lines is removed. Whitespace before and after the = sign # is removed. Everything is case *insensitive*. # Yes = True = On = 1 # No = False = Off = 0 # Default Log Directory # All log-files are assumed to be given relative to this directory. LogDir = /var/log # You can override the default temp directory (/tmp) here TmpDir = /var/cache/logwatch # Default person to mail reports to. Can be a local account or a # complete email address. MailTo = webmaster@domaine.tld # Default person to mail reports from. Can be a local account or a # complete email address. MailFrom = Logwatch # If set to 'Yes', the report will be sent to stdout instead of being # mailed to above person. Print = No # if set, the results will be saved in instead of mailed # or displayed. #Save = /tmp/logwatch # Use archives? If set to 'Yes', the archives of logfiles # (i.e. /var/log/messages.1 or /var/log/messages.1.gz) will # be searched in addition to the /var/log/messages file. # This usually will not do much if your range is set to just # 'Yesterday' or 'Today'... it is probably best used with # By default this is now set to Yes. To turn off Archives uncomment this. #Archives = No # Range = All # The default time range for the report... # The current choices are All, Today, Yesterday Range = yesterday # The default detail level for the report. # This can either be Low, Med, High or a number. # Low = 0 # Med = 5 # High = 10 Detail = Med # The 'Service' option expects either the name of a filter # (in /usr/share/logwatch/scripts/services/*) or 'All'. # The default service(s) to report on. This should be left as All for # most people. Service = All # You can also disable certain services (when specifying all) Service = "-zz-network" # Prevents execution of zz-network service, which # prints useful network configuration info. Service = "-zz-sys" # Prevents execution of zz-sys service, which # prints useful system configuration info. Service = "-eximstats" # Prevents execution of eximstats service, which # is a wrapper for the eximstats program. # If you only cared about FTP messages, you could use these 2 lines # instead of the above: #Service = ftpd-messages # Processes ftpd messages in /var/log/messages #Service = ftpd-xferlog # Processes ftpd messages in /var/log/xferlog # Maybe you only wanted reports on PAM messages, then you would use: #Service = pam_pwdb # PAM_pwdb messages - usually quite a bit #Service = pam # General PAM messages... usually not many # You can also choose to use the 'LogFile' option. This will cause # logwatch to only analyze that one logfile.. for example: #LogFile = messages # will process /var/log/messages. This will run all the filters that # process that logfile. This option is probably not too useful to # most people. Setting 'Service' to 'All' above analyizes all LogFiles # anyways... # # By default we assume that all Unix systems have sendmail or a sendmail-like system. # The mailer code Prints a header with To: From: and Subject:. # At this point you can change the mailer to any thing else that can handle that output # stream. TODO test variables in the mailer string to see if the To/From/Subject can be set # From here with out breaking anything. This would allow mail/mailx/nail etc..... -mgt mailer = "sendmail -t" # # With this option set to 'Yes', only log entries for this particular host # (as returned by 'hostname' command) will be processed. The hostname # can also be overridden on the commandline (with --hostname option). This # can allow a log host to process only its own logs, or Logwatch can be # run once per host included in the logfiles. # # The default is to report on all log entries, regardless of its source host. # Note that some logfiles do not include host information and will not be # influenced by this setting. # #HostLimit = Yes # vi: shiftwidth=3 tabstop=3 et
nano /usr/share/logwatch/default.conf/logfiles/http.confAjouter dans la premiere section
LogFile = /home/*/logs/access.log LogFile = /home/*/logs/access.log.1Ajouter dans la 2eme section
Archive = /home/*/logs/access.log.*.gz
######################################################## # Define log file group for httpd ######################################################## # What actual file? Defaults to LogPath if not absolute path.... LogFile = httpd/*access_log LogFile = apache/*access.log.1 LogFile = apache/*access.log LogFile = apache2/*access.log.1 LogFile = apache2/*access.log LogFile = apache-ssl/*access.log.1 LogFile = apache-ssl/*access.log LogFile = /home/*/logs/access.log LogFile = /home/*/logs/access.log.1 # If the archives are searched, here is one or more line # (optionally containing wildcards) that tell where they are... #If you use a "-" in naming add that as well -mgt Archive = archiv/httpd/*access_log.* Archive = httpd/*access_log.* Archive = apache/*access.log.*.gz Archive = apache2/*access.log.*.gz Archive = apache-ssl/*access.log.*.gz Archive = /home/*/logs/access.log.*.gz # Expand the repeats (actually just removes them now) *ExpandRepeats # Keep only the lines in the proper date range... *ApplyhttpDate # vi: shiftwidth=3 tabstop=3 et
nano /usr/share/logwatch/default.conf/logfiles/xferlog.confModifier
LogFile = /home/log/proftpd/xferlog Archive = /home/log/proftpd/xferlog.*
########################################################################## # $Id: xferlog.conf,v 1.15 2006/03/21 01:47:28 bjorn Exp $ ########################################################################## ######################################################## # This was written and is maintained by: # Kirk Bauer# # Please send all comments, suggestions, bug reports, # etc, to kirk@kaybee.org. ######################################################## # What actual file? Defaults to LogPath if not absolute path.... LogFile = /home/log/proftpd/xferlog # If the archives are searched, here is one or more line # (optionally containing wildcards) that tell where they are... #If you use a "-" in naming add that as well -mgt Archive = /home/log/proftpd/xferlog.* Archive = /home/log/proftpd/xferlog.* # vi: shiftwidth=3 tabstop=3 et
Logrotate est un programme qui permet de faire "tourner" les logs.
Selon sa configuration il va compresser les anciennes entrées des logs afin d'éviter d'avoir de trop gros fichier prenant de la place et ralentissant les serveurs
Nous allons aussi lui dire de générer les statistiques de visites des sites avant de faire la rotation des logs afin de ne pas fausser les résultats
nano /etc/logrotate.d/apache2Remplacer la première ligne par
/home/*/logs/*.log {
Ajouter sous la ligne "sharedscripts"
prerotate /etc/awstats/awstats.sh endscript Supprimer la lignecreate 640 root adm
/home/*/logs/*.log {
weekly
missingok
rotate 52
compress
delaycompress
notifempty
sharedscripts
prerotate
/etc/awstats/awstats.sh
endscript
postrotate
if [ -f /var/run/apache2.pid ]; then
/etc/init.d/apache2 restart > /dev/null
fi
endscript
}
Vous pouvez appeler cet user autrement que defaut, mais pensez alors à adapter le nom pour tout ce qui suit quand l'user defaut est mentionné
Remplacez "MOT DE PASSE" par le mot de passe que vous aurez choisit
useradd -m -g users -p `mkpasswd MOT DE PASSE` defaut
Collectd est un daemon qui collecte des informations du système toutes les 10 secondes.
Les données sont enregistrées dans un fichier RRD et peuvent ensuite être visualisées sous forme de graphiques.
aptitude install devscripts build-essential fakeroot aptitude install librrd2-dev librrds-perl aptitude install libsensors-dev aptitude install libmysqlclient-dev=> taper "Oui" quand demander
aptitude install collectd
aptitude install collectd-apache
nano /etc/collectd/collectd.confRemplacer
#DataDir /var/lib/collectd #PIDFILE /var/run/collectd.pid #PluginDir /usr/lib/collectdPar :
DataDir /var/lib/collectd PIDFILE /var/run/collectd.pid PluginDir /usr/lib/collectdRemplacer
#LoadPlugin apachePar :
LoadPlugin apacheRemplacer
Par :# # URL http://localhost/status?auto # User www-user # Password secret # CACert /etc/ssl/ca.crt #
Pour prendre en compte les modifications :URL http://localhost/server-status?auto
/etc/init.d/collectd force-reload
cp /usr/share/doc/collectd/examples/collection.cgi.gz /home/defaut/cgi-bin/mrtg.cgi.gz cd /home/defaut/cgi-bin gunzip mrtg.cgi.gz chmod 755 mrtg.cgi
Choisir un mot de passe et le mettre à la place de "MOT DE PASSE"
Choisir un identifiant et le metre à la place de "USER"
Votre utilisateur pourra alors accéder aux graphs par l'adresse http://www.rxxxxx.ovh.net/cgi-bin/mrtg.cgi/
Avec le couple login / mot de passe définit par user / mot de passe que vous aurez choisit
nano /home/defaut/cgi-bin/.htaccessAjouter ce qui est indiqué à droite Configuration du mot de passe
htpasswd -b -c -m /home/defaut/cgi-bin/.htpasswd USER MOT DE PASSEDéfinition du propriétaire du répertoire des fichiers
chown -R defaut:users /home/defaut/cgi-bin
AuthUserFile /home/defaut/cgi-bin/.htpasswd AuthGroupFile /dev/null AuthName "CollectD" AuthType Basic require valid-user
Le vhost par défaut est celui auquel on accèdera par l'adresse du serveur (rxxxxx.ovh.net pour un RPS).
Il permetra aussi de voir les graphiques collectd du serveur via le repertoire cgi-bin.
> /etc/apache2/sites-available/default
nano /etc/apache2/sites-available/defaultOn redémarre apache2 pour prendre en compte les changements
/etc/init.d/apache2 force-reload
NameVirtualHost *:80 NameVirtualHost *:443 ServerAdmin webmaster@localhost DocumentRoot /home/defaut/www SuexecUserGroup defaut users CustomLog /home/defaut/logs/access.log combined ErrorLog /home/defaut/logs/error.log ScriptAlias /cgi-bin/ /home/defaut/cgi-bin/ LogLevel warn AddHandler x-httpd-php .php ServerSignature Off
Pour vérifier que tout va bien on va acceder au serveur via notre navigateur.
L'adresse est à adapter à votre serveur pour l'exemple nous prendrons rxxxxx.ovh.net
http://rxxxxx.ovh.net/ => Doit afficher Domaine installé
http://rxxxxx.ovh.net/test.php => Doit afficher le phpinfo
http://rxxxxx.ovh.net/cgi-bin/mrtg.cgi => Doit afficher les graphs collectd du serveur
Ici je vais vous expliquer comment créer manuellement un domaine
(sachant que je vais vous proposer un script pour automatiser cette création ultérieurement)
Remplacez "MOT DE PASSE" par le mot de passe que vous aurez choisit
useradd -m -g users -p `mkpasswd MOT DE PASSE` domaine
N'oubliez pas de remplacer domaine par votre domaine sans son extension et domaine.tld par votre
domaine avec son extension
nano /etc/bind/named.confAjouter
zone "domaine.tld" {
type master;
file "/etc/bind/db.domaine.tld";
};
// This is the primary configuration file for the BIND DNS server named.
//
// Please read /usr/share/doc/bind9/README.Debian.gz for information on the
// structure of BIND configuration files in Debian, *BEFORE* you customize
// this configuration file.
//
// If you are just adding zones, please do that in /etc/bind/named.conf.local
include "/etc/bind/named.conf.options";
// prime the server with knowledge of the root servers
zone "." {
type hint;
file "/etc/bind/db.root";
};
// be authoritative for the localhost forward and reverse zones, and for
// broadcast zones as per RFC 1912
zone "localhost" {
type master;
file "/etc/bind/db.local";
};
zone "127.in-addr.arpa" {
type master;
file "/etc/bind/db.127";
};
zone "0.in-addr.arpa" {
type master;
file "/etc/bind/db.0";
};
zone "255.in-addr.arpa" {
type master;
file "/etc/bind/db.255";
};
zone "domaine.tld" {
type master;
file "/etc/bind/db.domaine.tld";
};
Sachant que pour le numéro SOA sous forme de AAAAMMJJNUM :
En se basant sur la date de la modification :
- AAAA = Année sur 4 chiffres
- MM = Mois sur 2 chiffres
- JJ = Jour sur 2 chiffres
- Num = numéro de modification sur 2 chiffres minimum
N'oubliez pas de remplacer domaine par votre domaine sans son extension et domaine.tld par votre
domaine avec son extension
nano /etc/bind/db.domaine.tldPuis
/etc/init.d/bind9 restart
Pour prendre en compte les modifications
$ttl 86400 domaine.tld. IN SOA rXXXXX.ovh.net. webmaster.domaine.tld. ( AAAAMMJJNUM 21600 3600 604800 86400 ) IN NS rXXXXX.ovh.net. IN NS sdns1.ovh.net. IN A 123.456.789.012 * IN A 123.456.789.012 domaine.tld. IN MX 1 ASPMX.L.GOOGLE.COM. domaine.tld. IN MX 5 ALT1.ASPMX.L.GOOGLE.COM. domaine.tld. IN MX 5 ALT2.ASPMX.L.GOOGLE.COM. domaine.tld. IN MX 10 ASPMX2.GOOGLEMAIL.COM. domaine.tld. IN MX 10 ASPMX3.GOOGLEMAIL.COM. domaine.tld. IN MX 10 ASPMX4.GOOGLEMAIL.COM. domaine.tld. IN MX 10 ASPMX5.GOOGLEMAIL.COM. mail IN CNAME ghs.google.com.
On va configurer apache pour acceder au site depuis www.domaine.tld et domaine.tld
Et pour acceder au phpmyadmin de la base de donnée en ssl depuis sql.comaine.tld
N'oubliez pas de remplacer domaine par votre domaine sans son extension et domaine.tld par votre
domaine avec son extension
nano /etc/apache2/sites-available/domaine.tldPuis
a2ensite domaine.tld
Pour activer le domaine dans apache.
Et enfin/etc/init.d/apache2 force-reloadPour prendre en compte les modifications.
ServerAdmin webmaster@domaine.tld DocumentRoot /home/domaine/www SuexecUserGroup domaine users ServerName www.domaine.tld ServerAlias domaine.tld CustomLog /home/domaine/logs/access.log combined ErrorLog /home/domaine/logs/error.log ScriptAlias /cgi-bin/ /home/domaine/cgi-bin/ LogLevel warn AddHandler x-httpd-php .php ServerSignature Off ServerName sql.domaine.tld Redirect / https://sql.domaine.tld ServerAdmin webmaster@domaine.tld DocumentRoot /usr/share/phpmyadmin SuexecUserGroup phpmyadmin users ServerName sql.domaine.tld CustomLog /home/domaine/logs/sql-access.log combined ErrorLog /home/domaine/logs/sql-error.log LogLevel warn ServerSignature Off AddHandler x-httpd-php .php SSLEngine on SSLCertificateFile /etc/apache2/server.crt SSLCertificateKeyFile /etc/apache2/server.key
On va créer la base de donnée pour le domaine identifié par son mot de passe.
Et on va attribuer les droits uniquement sur cette base à l'utilisateur du domaine.
Pensez à remplacer domaine par le nom de votre utilisateur et mot de passe par le mot de passe que vous lui choisirez pour mysql.
mysql -pEntrer le mot de passe ROOT que vous avez choisis pour mysql
create database domaine;
Pour creer la base de donnee
GRANT ALL PRIVILEGES ON `domaine`.* TO 'domaine'@'localhost' IDENTIFIED BY 'mot_de_passe';Pour donner les droits à l'utilisateur sur la base de donnée
FLUSH PRIVILEGES;Pour mettre à jour la table des privilèges
exit;Pour sortir de Mysql
create database domaine; GRANT ALL PRIVILEGES ON `domaine`.* TO 'domaine'@'localhost' IDENTIFIED BY 'mot_de_passe'; FLUSH PRIVILEGES; exit;
N'oubliez pas de remplacer domaine par votre domaine sans son extension et domaine.tld par votre
domaine avec son extension
nano /etc/awstats/awstats.domaine.tld.confAjouter ce qui est indiqué à droite
LogFile="/home/domaine/logs/access.log" SiteDomain="domaine.tld" Include "/etc/awstats/awstats.conf.local"
N'oubliez pas de remplacer domaine par votre domaine sans son extension et domaine.tld par votre
domaine avec son extension
echo '/usr/lib/cgi-bin/awstats_buildstaticpages.pl -config=domaine.tld -update -lang=fr -awstatsprog=/usr/lib/cgi-bin/awstats.pl -dir=/home/domaine/www/awstats' >> /etc/awstats/awstats.shMise en place du propriétaire du repertoire de destination des stats
chown awstats:users -R /home/domaine/www/awstats
N'oubliez pas de remplacer domaine par votre domaine sans son extension et domaine.tld par votre
domaine avec son extension
Choisir un mot de passe et le mettre à la place de "MOT DE PASSE"
Votre utilisateur pourra alors accéder aux stats par l'adresse http://www.domaine.tld/awstats/
Avec le couple login / mot de passe définit par domaine / mot de passe que vous aurez choisit
nano /home/domaine/www/awstats/.htaccessAjouter ce qui est indiqué à droite Configuration du mot de passe
htpasswd -b -c -m /home/domaine/www/awstats/.htpasswd domaine MOT DE PASSEDéfinition du propriétaire du répertoire de destination des stats
chown awstats:users -R /home/domaine/www/awstats
AuthUserFile /home/domaine/www/awstats/.htpasswd AuthGroupFile /dev/null AuthName "Statistiques" AuthType Basic require valid-user DirectoryIndex awstats.www.domaine.tld.html
Voici un script pouvant être utilisé pour installé un domaine
je ne propose aucune ganrantie sur ce script, qui fonctionne sur mon install mais manque de test
Malgrès tout les messages d'erreurs sont assez clair pour réussir à corriger les problèmes éventuels
Ce script va creer tout ce qui est nécéssaire au bon fonctionnement du domaine tel que décrit dans la méthode précédente
A l'exclusion (pour le moment) de la partie mails qui reste à faire manuelement tel qu'indiqué ci dessous
nano /root/install_dom.shAjouter ce qui est indiqué à droite
chmod +X /root/install_dom.shLancer le script
/root/install_dom.sh
#!/bin/sh #--------------------------------- Récupère les variables nécéssaires ---------------------------------------------------------------- # Récupère l'ip du serveur : mon_ip=`grep $HOSTNAME /etc/hosts |cut -f1` # Récupère le nom d'hote du serveur hostname=$HOSTNAME # Met le nom d'hote du serveur en serveur DNS1 dns1=$HOSTNAME # Met le DNS secondaire de OVH en serveur DNS2 dns2="sdns1.ovh.net" # Récupère pass root mysql while test -z $root_mysql; do echo "veuillez entrer le mot de passe ROOT MYSQL" read root_mysql done # Récupère le nom de domaine a créer et le tld ## Force une variable domaine non vide while test -z $new_dom do echo "veuillez entrer le nom de domaine SANS le tld (ex: gandalf76fr)" read new_dom done ## Force une variable tld non vide while test -z $tld do echo "veuillez entrer le tld (ex: fr)" read tld done # Récupère le nom de domaine nom_domaine=$new_dom.$tld # Récupère le nom d'user a créer ## Force une variable user de plus de 8 caractères if test -z $new_user then echo "Veuillez entrer un nom d'utilisateur de plus de 8 caractères" read new_user while [ "${#new_user}" -lt "8" ]; do echo "votre nom d'utilisateur fais ${#new_user} caractères" echo "veuillez choisir un nom d'utilisateur de plus de 8 caractères" read new_user done fi # Récupère le nom de BDD a créer ## Force une variable bdd de plus de 8 caractères if test -z $new_bdd then echo "Veuillez entrer un nom de base de données de plus de 8 caractères" read new_bdd while [ "${#new_bdd}" -lt "8" ]; do echo "votre nom de base de données fais ${#new_user} caractères" echo "veuillez choisir un nom de base de données de plus de 8 caractères" read new_bdd done fi # Génère le mot de passe de 8 caractères M="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" while [ "${n:=1}" -le "20" ]; do pass="$pass${M:$(($RANDOM%${#M})):1}" let n+=1 done password=${pass:0:8} # Récupère la date de création pour générer le fichier Bind (et on y ajoute 01 pour première modification) date_creation=`date +%Y%m%d`01 echo "ce qui nous donne : IP : $mon_ip Hote : $hostname DNS1 : $dns1 DNS2 : $dns2 Pass Root Mysql : $root_mysql User : $new_user TLD : $tld Domaine : $nom_domaine Nom BDD = $new_bdd Password : $password Date : $date_creation" #------------------------------------------ Test si les variables renseignées sont OK --------------------------------------------------- # Défini le répertoire de base du user rep=/home/$new_user # Test si le répertoire existe, et donc le user if [ -d $rep ]; then echo "l'utilisateur est déja gérer par ce serveur" exit fi # Test si le vhost existe, et donc le domaine if [ -e /etc/apache2/sites-enabled/$nom_domaine ]; then echo "Le nom de domaine est déja gérer par ce serveur (apache)" exit fi # Test si la zone bind, et donc le domaine if [ -e /etc/bind/db.$nom_domaine ]; then echo "Le nom de domaine est déja gérer par ce serveur (bind)" exit fi # Test si la base de donnée existe if [ -e /var/lib/mysql/$new_bdd ]; then echo "La base de donnée est déja crée sur ce serveur" exit fi # Test si la connection root à Mysql est possible mysql -u root -e "" -p$root_mysql if test $? != "0"; then echo "Erreur connection mysql" exit fi #--------------------------------------- Crée l'utilisateur et son environnement par défaut (squelette) --------------------------------- useradd -m -g users -p `mkpasswd $password` $new_user if test $? != "0"; then echo "Erreur création utilisateur" exit fi #---------------------------------------- Configuration de bind -------------------------------------------------- ## Crée le fichier de déclaration de zone BIND echo " \$ttl 86400 $nom_domaine. IN SOA $hostname. webmaster.$nom_domaine. ( $date_creation 21600 3600 604800 86400 ) IN NS $hostname. IN NS $dns2. IN A $mon_ip * IN A $mon_ip $nom_domaine. IN MX 1 ASPMX.L.GOOGLE.COM. $nom_domaine. IN MX 5 ALT1.ASPMX.L.GOOGLE.COM. $nom_domaine. IN MX 5 ALT2.ASPMX.L.GOOGLE.COM. $nom_domaine. IN MX 10 ASPMX2.GOOGLEMAIL.COM. $nom_domaine. IN MX 10 ASPMX3.GOOGLEMAIL.COM. $nom_domaine. IN MX 10 ASPMX4.GOOGLEMAIL.COM. $nom_domaine. IN MX 10 ASPMX5.GOOGLEMAIL.COM. mail IN CNAME ghs.google.com. " > /etc/bind/db.$nom_domaine if test $? != "0"; then echo "Erreur création fichier de déclaration de zone BIND" exit fi ## Crée la zone BIND echo " zone \"$nom_domaine\" { type master; file \"/etc/bind/db.$nom_domaine\"; }; " >> /etc/bind/named.conf.local if test $? != "0"; then echo "Erreur création de la zone BIND" exit fi ## Redémarrage de bind pour prendre en compte les modifications /etc/init.d/bind9 restart if test $? != "0"; then echo "Erreur lors du redémarrage de BIND" exit fi #--------------------------------- Configuration de apache2 -------------------------------------------- ## Crée la zone virtuelle apache2 echo " ServerAdmin webmaster@$nom_domaine DocumentRoot /home/$new_user/www SuexecUserGroup $new_user users ServerName www.$nom_domaine ServerAlias $nom_domaine CustomLog /home/$new_user/logs/access.log combined ErrorLog /home/$new_user/logs/error.log ScriptAlias /cgi-bin/ /home/$new_user/cgi-bin/ LogLevel warn AddHandler x-httpd-php .php ServerSignature Off ServerName sql.$nom_domaine Redirect / https://sql.$nom_domaine ServerAdmin webmaster@$nom_domaine DocumentRoot /usr/share/phpmyadmin SuexecUserGroup phpmyadmin users ServerName sql.$nom_domaine CustomLog /home/$new_user/logs/sql-access.log combined ErrorLog /home/$new_user/logs/sql-error.log LogLevel warn ServerSignature Off AddHandler x-httpd-php .php SSLEngine on SSLCertificateFile /etc/apache2/server.crt SSLCertificateKeyFile /etc/apache2/server.key " > /etc/apache2/sites-available/$nom_domaine if test $? != "0"; then echo "Erreur création fichier de zone virtuelle apache2" exit fi ## Activation du site dans apahce2 a2ensite $nom_domaine if test $? != "0"; then echo "Erreur activation du site dans apache2" exit fi ## Redémarrage de apache2 pour prendre en compte les modifications /etc/init.d/apache2 force-reload if test $? != "0"; then echo "Erreur redémarrage de apache2" exit fi #---------------------------------- Ajout d'une base de donnée Mysql pour le domaine ------------------ ## Création BDD mysql -u root -e "create database $new_bdd;" -p$root_mysql if test $? != "0"; then echo "Erreur création BDD" exit fi ## Ajout des privilèges au user pour la bdd crée mysql -u root -e "GRANT ALL PRIVILEGES ON $new_bdd.* TO '$new_user'@'localhost' IDENTIFIED BY '$password';" -p$root_mysql if test $? != "0"; then echo "Erreur ajout des privilèges utilisateur dans mysql" exit fi #---------------------------------- Configuration de Awstats ---------------------------------------- ## Création du fichier de configuration du domaine echo " LogFile=\"/home/$new_user/logs/access.log\" SiteDomain=\"$nom_domaine\" Include \"/etc/awstats/awstats.conf.local\" " > /etc/awstats/awstats.$nom_domaine.conf if test $? != "0"; then echo "Erreur création fichier de configuration awstats" exit fi ## Ajout de la tache de génération des stats au fichier de lancement des stats echo "/usr/lib/cgi-bin/awstats_buildstaticpages.pl -config=$nom_domaine -update -lang=fr -awstatsprog=/usr/lib/cgi-bin/awstats.pl -dir=/home/$new_user/www/awstats " >> /etc/awstats/awstats.sh if test $? != "0"; then echo "Erreur ajout tache de génération des stats au fichier de lancement" exit fi ## Mise en place de la protection par mot de passe des stats ### Creation du fichier .htaccess echo " AuthUserFile /home/$new_user/www/awstats/.htpasswd AuthGroupFile /dev/null AuthName \"Statistiques\" AuthType Basicrequire valid-user DirectoryIndex awstats.$nom_domaine.html " > /home/$new_user/www/awstats/.htaccess if test $? != "0"; then echo "Erreur mise en place du .htaccess du repertoire de destination des stats" exit fi ### Creation du fichier .htpasswd htpasswd -b -c -m /home/$new_user/www/awstats/.htpasswd $new_user $password if test $? != "0"; then echo "Erreur mise en place du .htpasswd du repertoire de destination des stats" exit fi ## Mise en place du propriétaire du repertoire de destination des stats chown awstats:users -R /home/$new_user/www/awstats if test $? != "0"; then echo "Erreur mise en place du propriétaire du repertoire de destination des stats" exit fi
Nous allons donc enfin paramétrer votre domaine pour gérer vos mails via google apps.
|
Allez à l'adresse : https://www.google.com/a/help/intl/fr/admins/editions_spe.html Sur l'édition qui vous convient (standard gratuite ou premier payant) cliquez sur inscription |
|
|
--- Exemple edition gratuite : --- Dans la rubrique "je dispose déja d'un nom de domaine" |
|
|
Dans la page suivante : |
|
|
Dans cette nouvelle page, |
|
|
Selectionner alors :
Commande
nano /etc/bind/db.domaine.tldAjouter à la fin "chaine unique donnée" IN CNAME google.com.modifier le SOA au format aaaammjjnumdemodif /etc/init.d/bind9 restartPour prendre en compte les modifications. Puis dans la page de google apps, cliquez sur vérifier. |
|
Configuration du compte smtp sur le serveurEn SSH :
Commande
nano /etc/exim4/passwd.clientAjouter gmail-smtp.l.google.com:webmaster@domaine.tld:motdepasse *.google.com:webmaster@domaine.tld:motdepasse smtp.gmail.com:webmaster@domaine.tld:motdepassePuis exécutez : update-exim4.confPour valider les modifications. |
Exemple
gmail-smtp.l.google.com:webmaster@domaine.tld:motdepasse *.google.com:webmaster@domaine.tld:motdepasse smtp.gmail.com:webmaster@domaine.tld:motdepasse |
Changement de serveurs DNS du domaineAllez sur votre manager ovh |
|
|
cliquez sur votre domaine, |
|
|
Cliquez sur "serveurs DNS", |
|
|
Entrez le nom de votre RPS dans la première case Entrez le dns secondaire de ovh dans la 2eme : |
|
|
Puis cliquez sur "valider" |
|
Ajout du domaine dans les DNS secondaire liés au serveurCliquez sur "accueil" |
|
|
Selectionnez votre RPS, |
|
|
Cliquez sur "dns secondaire", |
|
|
Entrez votre domaine.tld, |
|
|
Une fois le changement de DNS et sa propagation OK |
|
|
Cliquez sur "j'ai éffectuer la procédure". |
|
|
Une fois la messagerie via google activée |
|
|
Cliquez sur "modifier l'url" |
|
|
Cochez la case du bas |
|