Outils pour utilisateurs

Outils du site


issue100:site_web_from_scratch

Ceci est une ancienne révision du document !


Titre : Website with Infrastructure from Scratch The goal of this series, mainly targeted to beginners, is to guide you step-by-step in building a website, with the entire Linux infrastructure – from scratch. Basically, deploy a Linux distribution (Ubuntu) in the cloud, secure the OS, install the Apache web server and secure Apache. You may wonder why should we go through all the trouble when it is very easy and possible to get a cheap and full featured hosting solution such as Wordpress? I strongly believe there is no “One size fits all solution” – building from scratch will totally fulfill your needs, while a ready-to-use solution probably won't. On the other hand, a “ready-to-use solution”, especially open-source, may provide right away (complex) functionality out of the box, therefore saving on development time, and usually for free. But my main reason for building from scratch is learning! When I built my wife's website from scratch, I learned a lot – mainly around security, OS setup and Apache – in other words, I gathered invaluable Linux experience.

Titre : Site Web avec infrastructure à partir de 0

Le but de cette série, surtout destinée aux débutants, est de vous guider pas-à-pas en construisant un sit Web, avec toute l'infrastructure Linux - à partir de zéro. En bref, déployer une distribution Linux (Ubuntu) dans le nuage, sécuriser l'OS, installer le serveur Web Apache et sécuriser Apache.

Vous pourriez vous demander pourquoi nous ferons tout ça alors qu'il est si facile et possible de prendre une solution hôte peu chère et complète comme Wordpress ?

Je crois fortement qu'il n'y a pas de « solution universelle » - la construction à partir de zéro remplira totalement vos besoins, alors que la solution toute faite ne le fera probablement pas. A l'inverse, une solution « prête à l'emploi », particulièrement en open source, peut fournir un fonctionnement (complexe) directement à l'installation, épargnant du temps de développement, et en général gratuite.

Mais la raison principale d'une construction intégrale est d'apprendre ! Quand j'ai construit le site Web de ma femme à partir de rien, j'ai beaucoup appris -principalement autour de la sécurité, du paramétrage de l'OS et d'Apache - en d'autres mots, j'ai acquis un expérience inestimable de Linux.

Enough talking – let's start! Here, at a high level, is what we will achieve: • First, deploy a Linux VM (Virtual Machine) in the cloud • Then, we'll secure this Linux VM • We'll then install and secure Apache (web server) • Finally, I'll show how to register a domain and link this domain to the Apache hosted on the Linux VM Deploy Linux in the Cloud There are many available solutions to deploy a VM in the cloud. Just as an example, Amazon Web Services is probably known Worldwide. In my document, I will use Digital Ocean. I am not trying to make any commercial argument for Digital Ocean. I personally chose this provider because it is cheap, (charged by the hour of usage, equivalent of $5 / month for the smallest configuration with limited network usage), very easy to deploy a Linux VM, and somehow local (several data centers available – I chose New York). Let's spin a new VM, and we'll choose Ubuntu 14.04: • Go to https://www.digitalocean.com and log in. • Choose “Create a new droplet” (“droplet” is just a VM).

Assez parlé - Commençons !

Voici, au niveau global, ce que nous allons réaliser : • Premièrement, déployer Linux VM (Virtual Machine) dans le Nuage, • ensuite, nous allons sécuriser cette VM Linux, • suivi de l'installation det la sécurisation d'Apache (serveur Web), • enfin, je vous montrerai comment enregistrer un domaine et relier ce domaine à Apache, hébergé dans la VM Linux.

Déployer Linux dans le Nuage

Il y a beaucoup de solutions disponibles pour déployer une VM dans le Nuage. Juste un exemple : Amazon Web Services (service Web d'Amazon), probablement connu dans le monde entier.

Dans mon document, je vais utiliser Digital Ocean. Je n'essaie pas de faire de la publicité pour Digital Ocean. Personnellement, j'ai choisi ce fournisseur parce qu'il est bon marché (il facture à l'heure de connexion, soit environ 5€/mois pour la plus petite configuration avec un usage réseau limité), très pratique pour déployer une VM Linux et d'une certaine façon, de proximité (j'ai choisi New-York).

Faisons tourner une nouvelle VM et nous choisirons Ubuntu 14.04 : • Allez sur https://www.digitalocean.com et connectez-vous, • choisissez « Create a new droplet » (créer une nouvelle droplet - droplet égale VM).

Key in a VM name and choose the VM size. The smallest size runs really well. Yes, it doesn't have a lot of memory – but remember, we'll be running Linux, so it's more than enough to run a couple of websites. Then choose the Linux flavor – we'll go for Ubuntu 14.04 64-bit - and finally use the “Create Droplet” button at the bottom of the page. A few seconds later, the VM will be created and root password with IP address will be sent to you by email. We'll need this to connect to the VM. Note that I will not hide the IP address – after all it's temporary, and since I am supposed to secure this VM, I should not be worried about being hacked. IMPORTANT Digital Ocean charges by the hour even if the VM is powered off. Please go and read the Digital Ocean billing documentation for all the details. If you'd like to stop any charges, take a snapshot (so the VM can be restored later) and then destroy the VM. Please note that we'll continue setting up the server using only the command-line. • First, the bandwidth is limited (only 1Tb is included in our monthly allowance) and graphical interface uses a lot of that. • Second, command-line is faster. As convention, all commands starting with # should run as root while all starting with $ will start as regular user.

Saisissez un nom de VM et choisissez sa taille. Le plus petit format fonctionne vraiment bien. Oui, il n'y a pas beaucoup de mémoire - mais, souvenez-vous, nous allons faire tourner Linux, aussi, c'est largement suffisant pour une paire de sites.

Ensuite, choisissez la saveur de Linux - pour nous, Ubuntu 14.04 64-bits - et, enfin, utilisez le bouton « Create Droplet » (Créer la droplet) en bas de la page.

Quelques secondes après, la VM sera créée et un mot de passe administrateur avec l'adresse IP vous sera envoyé par mail. Nous en aurons besoin pour nous connecter à la VM. Notez que je ne vais pas cacher l'adresse IP (après tout, c'est temporaire) et, bien que je sois supposé sécuriser cette VM, je n'ai pas peur d'être attaqué.

IMPORTANT

Digital Ocean facture à l'heure même si la VM est éteinte. Merci de lire la documentation de Digital Ocean sur la facturation pour tous les détails.

Si vous voulez arrêter tout coût supplémentaire, faites un instantané de votre VM (vous pourrez la restaurer plus tard) et détruisez la VM.

Prenez note, s'il vous plaît, que nous allons continue la préparation du serveur en utilisant uniquement la ligne de commande. • Premièrement, la bande passante est limitée (1 To seulement est compris dans notre abonnement mensuel) et l'interface graphique en utilise une bonne partie, • deuxièmement, la ligne de commande est plus rapide.

Par convention, toutes les commandes commençant par # devront être lancées comme administrateur alors que celles avec $ le seront par un utilisateur normal.

Basic Security Now that the VM is up & running, it is available via SSH from anywhere – no security is provided by default except the root password – we need to address this rapidly. Let me make a parallel with Real Estate - when purchasing a house, the motto is “location, location, location”. Likewise, to secure a Linux server with SSH, the motto should be “no root access”, “RSA key”, “no password”. Step 0 – Create a new user The first time, login to your brand new Linux VM as root and create a new user called tux. Then we'll assign the password linux to our user (obviously, choose a better password). Login to the VM – we must log in as root this 1st time. Open a terminal: ssh root@104.236.124.121 Then add the new user: useradd -m -s /bin/bash tux passwd tux Follow the prompt and key in linux The -m flag for useradd is to create the home folder, and -s means we want bash as shell.

Sécurité minimum

Maintenant que la VM est configurée et en fonctionnement, elle est accessible depuis n'importe où par SSH - aucune sécurité n'est fournie par défaut, sauf le mot de passe administrateur - et nous devons régler ça rapidement.

Laissez-moi faire un parallèle avec l'immobilier - quand vous achetez une maison, l’adage est « localisation, emplacement, environnement ». De même, pour sécuriser un serveur Linux avec SSH, la maxime devrait être « pas d'accès administrateur », « Clé RSA », « pas de mot de passe ».

Etape 0 - Créer un utilisateur

La première fois que vous vous connectez à VM Linux toute neuve, créez un nouvel utilisateur nommé « tux ». Ensuite, nous attribuons le mot de passe « linux » à ce nouvel utilisateur (choisissez un meilleur mot de passe).

Connectez-vous à la VM - nous nous connectons comme administrateur dans un premier temps. Ouvrez un terminal :

ssh root@104.236.124.121

Puis ajoutez un nouvel utilisateur:

useradd -m -s /bin/bash tux

passwd tux

Attendez l'invite et saisissez linux.

le commutateur -m pour useradd crée un répertoire home et le -s que nous voulons bash comme shell.

Now we must ensure that we can log in with the new user created. Open a new terminal session and let's try it out: ssh tux@104.236.124.121 and key in your password you should now be connected. Please make sure this step works before moving forward. 1 - “no root access” Never allow root access to SSH if for whatever reason an attacker can get root access to your system, you are doomed. vi /etc/ssh/sshd_config And add these 2 lines in the beginning of the file: AllowUsers tux DenyUsers root I am using vi as text editor but you could use another editor (I hear nano is probably better suited for beginners). In order to take effect, we must restart the ssh daemon: service ssh restart Now the user root cannot connect anymore to iceberg. Try it out – ssh root@104.236.124.121 - error message should be “Permission Denied”. Level 1 of security completed!

2 – RSA key An RSA key is a pretty secure way to login to an SSH server. Generating an RSA key will create 2 components – a private key and a public key. In plain English, a private key is a small file. A public key is also a small file. In order to access the system with the RSA keys (so we'll do what is called “RSA authentication”), SSH will ensure that both files go together – if they do, you'll be able to log in. Let me make a parallel with a dollar bill – let's imagine we randomly tear the bill in 2 pieces. Only these 2 pieces will go together. Same for RSA keys. The public key will be stored on the SSH server (iceberg in our example), while tux will hold the private key. When tux tries to connect to iceberg, tux must show the private key matching with the public key. And we'll make the size of the key so large that the probability somebody can reproduce the match is virtually not possible. In summary, without the right private key, there will be no access to the server. IMPORTANT – we'll generate the keys for tux and not root (remember – no root access!!!). Generate the pair public/private key. We'll hit it hard and ask for a 10Kb key (I believe default is 4Kb). This process can take some time – up to 1 min at most (large key). ssh-keygen -t rsa -b 10240 You can accept the default selection or change the name. Let's change the name on purpose to id_rsa_iceberg (but keep the same folder). You can choose a password or leave it blank.

Some explanation here – the password is used to protect the private key itself. In the unlikely scenario somebody steals the private key, that attacker could then be able to connect to your server. But if he doesn't know the private key password, he will not be able to use the key. I know that a few of you will not agree, but think about it – what is really the chance somebody will steal your key? Virtually none, right? This is my point – it may therefore not need a password for our purposes. But let's make it the way we should – let choose a password: 12345 (again – if you plan to go it right - do not use a weak password, this is just a tutorial). We should now have 2 files in the folder /home/tux/.ssh • id_rsa_iceberg is the private key • id_rsa_iceberg.pub is the public key Now make a copy of the public key as follows – the name is important since ssh will be looking specifically for authorized_keys (you can change this default feature by tweaking /etc/ssh/sshd_config): cp id_rsa_iceberg.pub authorized_keys Special private key password security Now, before we continue, let's talk a little bit about the private key password security. As a general rule, modern encryption systems are pretty robust. However corners are sometimes cut and the entire system will be easier to defeat.

If you are familiar with the Enigma encryption system used by Germans during World War 2 – that was a really robust encryption system. For whatever (good?) reason, the creators decided that a character could not be encrypted as itself. Well, this feature inserted a weakness because it reduced the number of combinations the cypher could produce. It's obviously not the only reason why the code was broken – my point is that a small decision (by sloppiness or not) lowered the encryption strength of a well thought system. Same with SSH - private keys can be encrypted with a password (remember – 12345 in our example), however the encryption used is not as strong as you may think. Thanks to Open Source, somebody noticed this weakness and it is easily possible to seriously beef up the private key encryption. If you have any interest in doing this – just for fun actually - I recommend reading this excellent blog: http://martin.kleppmann.com/2013/05/24/improving-security-of-ssh-private-keys.html To summarize: • make a copy of the private key. • create 2 files - file1.txt with the original password and file2.txt with a new password. Both files can have the same password (12345 for us) but you must have both files created. • change the encryption. As tux (su – tux if you are root): cd /home/tux/.ssh mv id_rsa_iceberg id_rsa_iceberg.bak cat » file1.txt Key in 12345 and hit control+d cat » file2.txt Key in 12345 and hit control+d openssl pkcs8 -topk8 -v2 des3 -in /home/tux/.ssh/id_rsa_iceberg.bak -out /home/tux/.ssh/id_rsa_iceberg -passin file:file1.txt -passout file:file2.txt [NOTE: the above is all one line]

Now the private key will be protected with the password included in file2.txt, and properly encrypted! In order to connect to iceberg, we need to copy the private key id_rsa_iceberg to our computer. There are a few ways of doing this (scp for example – or secure copy), however what about a simple copy / paste? Let's do this: cat id_rsa_iceberg • select everything starting with —–BEGIN RSA PRIVATE KEY—– up to —–END RSA PRIVATE KEY—– and copy into the clipboard. Back to your desktop: cd (this will go back to your home folder). cd .ssh vi id_rsa_iceberg Now paste, save and close. • Change the file persmission: chmod 400 id_rsa_iceberg (this is read-only and expected by ssh).

We should now try to connect to iceberg using our ssh key. From your desktop: ssh -i ~/.ssh/id_rsa_iceberg tux@104.236.124.121 You should be prompted for the password of the private key (that is 12345) and then should be connected to iceberg! Final security setup – we'll now forbid any password connection to iceberg. Back to the file /etc/ssh/sshd_config and make some changes: vi /etc/ssh/sshd_config • Change PermitRootLogin yes to PermitRootLogin no • Change #PasswordAuthentication yes to PasswordAuthentication no • Change LoginGraceTime from 120 to 20 (this will allow 20s to login – it's more than enough). Save & exit and restart the ssh service (service ssh restart). Try ssh tux@104.236.124.121 You should get Permission denied (publickey). It means that password authentication is not allowed. Now we are fully secure!

To summarize: • root cannot connect. • only RSA keys are allowed for authentication. Next time we will secure the server using firewall rules (the server is wide open, however safe enough for right now). We will then install apache (web server) and secure apache. Last important note If you are using Digital Ocean, just shutting down the VM will not stop the billing cycle! Take a snapshot of the VM, and when this is completed, destroy the VM. With the snapshot, the VM can be re-created to the same state as when the snapshot was taken. If you are using any other Cloud provider, make sure to check their documentation so you do not pay while the VM is not up & running.

issue100/site_web_from_scratch.1442127350.txt.gz · Dernière modification : 2015/09/13 08:55 de d52fr