- Что вам понадобится
- Введение
- Получение необходимого программного обеспечения
- 1: создайте каталог для сертификата
- 1: создание виртуального хоста
- Создание собственного сертификата
- 2: создайте ключ и запрос на подпись сертификата
- 2: установка зависимостей
- 3: загрузка клиента let’s encrypt
- 3: создание самоподписанного сертификата
- 3: удалите пароль
- 4: создание ssl-сертификата
- 5: автоматическое обновление
- 5: перезапуск apache
- 5: установите сертификат
- 6: обновление клиента let’s encrypt (опционально)
- Adjusting the virtualhost directives
- Not using centos 7? choose a different version or distribution.
- Introduction
- Prerequisites
- Step one: install mod ssl
- Step two: create a new certificate
- Step three: set up the certificate
- Adjusting the virtualhost directives
- Setting up secure ssl parameters
- (recommended) modify the unencrypted virtual host file to redirect to https
- Step four: activate the certificate
- Conclusion
- Prerequisites
- Setting up secure ssl parameters
- Step four: activate the certificate
- Step one: install mod ssl
- Step three: set up the certificate
- Step two: create a new certificate
- Включение виртуального хоста
- Загрузка необходимых файлов на веб-сервер
- О самоподписанных сертификатах
- Перенос сертификатов с компьютера linux/mac os:
- Состояние сертификата
- Требования
- Установка ssl-сертификата на centos и ngnix — первый vps
- Заключение
Что вам понадобится
Перед тем, как вы начнете это руководство, вам понадобится следующее:
Введение
В этом руководстве вы узнаете, как установить SSL/TLS сертификат на сервер Apache. После завершения данной процедуры, весь трафик между сервером и клиентом будет зашифрован. Это стандартная практика защиты сайтов электронной коммерции или других финансовых онлайн сервисов.
Получение необходимого программного обеспечения
Для обеспечения SSL шифрования на вашем веб-сервере вам потребуется несколько вещей. В соответствии с предустановленным набором программного обеспечения вы можете иметь или не иметь в своей системе OpenSSL и mod_ssl, интерфейс apache для OpenSSL. Воспользуемся YUM чтобы установить их в нашу систему, если это необходимо.
yum install mod_ssl openssl
Соответственно YUM выдаст предупреждение о том, что данные пакеты уже установлены или установит их.
1: создайте каталог для сертификата
SSL-сертификат состоит из двух частей: самого сертификата и открытого ключа. Для простоты работы нужно создать отдельный каталог для хранения этих файлов:
sudo mkdir /etc/nginx/ssl
Теперь перейдите в новый каталог, поскольку следующие действия нужно выполнить в нем:
cd /etc/nginx/ssl
1: создание виртуального хоста
Плагин Apache для Let’s Encrypt позволяет упростить процесс генерирования и установки SSL-сертификата. Для корректной работы плагина необходимо создать виртуальный хост. При этом каждому отдельному домену, на который нужно установить сертификат, нужен индивидуальный виртуальный хост.
Примечание: Если вы настроили виртуальные хосты ранее, пропустите этот раздел.
Создание собственного сертификата
Используя OpenSSL мы будем генерировать собственный сертификат. Если вы используете это на рабочем сервере (продакшн), вы, вероятно захотите ключ от доверенного центра сертификации, но если вы используете это на личном сайте или в целях тестирования – собственного сертификата вполне достаточно.
# Генерация приватного ключа openssl genrsa -out ca.key 1024 # Генерация запроса на сертификат CSR openssl req -new -key ca.key -out ca.csr # Генерация самоподписанного ключа openssl x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt # Перемещение полученных файлов в правильные места mv ca.crt /etc/pki/tls/certs mv ca.key /etc/pki/tls/private/ca.key mv ca.csr /etc/pki/tls/private/ca.csr
Затем нам нужно обновить конфигурационный файл Apache SSL.
2: создайте ключ и запрос на подпись сертификата
Сначала создайте закрытый ключ. В ходе этого процесса будет предложено ввести определенный пароль. Обязательно запишите или запомните этот пароль – если он будет утерян, получить доступ к сертификату будет невозможно.
sudo openssl genrsa -des3 -out server.key 1024
Затем создайте запрос на подпись сертификата:
sudo openssl req -new -key server.key -out server.csr
Данная команда выведет на экран список полей, которые необходимо заполнить.
Самым важным полем является Common Name. Внесите в него официальный домен или IP-адрес (если домена нет). Поля Challenge password и Optional company name заполнять не нужно.
2: установка зависимостей
Прежде чем приступить к установке клиента Let’s Encrypt и созданию сертификата SSL, нужно установить несколько зависимостей.
Для начала добавьте репозиторий EPEL:
sudo yum install epel-release
Для загрузки клиента Let’s Encrypt понадобится git:
sudo yum install git
Для работы скрипта обновления сертификата необходим инструмент bc (он рассчитывает дату истечения срока действия сертификата). Чтобы установить его, выполните:
sudo yum install bc
3: загрузка клиента let’s encrypt
Теперь можно загрузить клиент Let’s Encrypt из официального репозитория.
Поскольку клиент Let’s Encrypt еще находится в бета-версии, его, вероятно, придётся часто обновлять, чтобы исправить баги и получить доступ к новой функциональности.
Клонируйте репозиторий Let’s Encrypt в каталог /opt, предназначенный для хранения дополнительных пакетов системы.
3: создание самоподписанного сертификата
Создавая сертификат, необходимо указать срок его действия; для этого измените значение 365 нужным количеством дней. Без изменений следующая строка создаст сертификат со сроком действия в 365 дней.
3: удалите пароль
Сертификат почти готов. На данном этапе нужно удалить установленный ранее пароль. Конечно, наличие пароля повышает уровень безопасности. Тем не менее, его нужно вводить всякий раз, когда nginx терпит сбои или требует перезагрузки,.
Для удаления пароля используйте команду:
sudo cp server.key server.key.orgsudo openssl rsa -in server.key.org -out server.key
4: создание ssl-сертификата
Процесс генерирования SSL-сертификата для Apache с помощью клиента Let’s Encrypt довольно прост. Клиент автоматически получит и установит сертификат, валидный для всех доменов, указанных в качестве аргументов.
Откройте каталог letsencrypt:
cd /opt/letsencrypt
Чтобы запустить интерактивную установку и получить сертификат для одного домена, выполните команду:
5: автоматическое обновление
Сертификаты Let’s Encrypt действительны в течение 90 дней, но во избежание ошибок их рекомендуется обновлять каждые 60 дней. На момент написания статьи клиент не оборудован функцией автоматического обновления сертификатов. Этот процесс можно выполнить вручную, просто запустив клиент Let’s Encrypt с использованными ранее параметрами.
Чтобы вручную обновить сертификат Let’s Encrypt для Apache, отключив интерактивный режим, введите:
5: перезапуск apache
На данном этапе сертификат полностью готов к работе. Осталось только перезапустить Apache, чтобы активировать внесенные изменения.
5: установите сертификат
Откройте конфигурационный файл SSL:
vi /etc/nginx/conf.d/ssl.conf
6: обновление клиента let’s encrypt (опционально)
После выхода обновлений для клиента Let’s Encrypt можно обновить локальную копию при помощи команды:
cd /opt/letsencryptsudo git pull
Эта команда загрузит все обновления клиента.
Adjusting the virtualhost directives
First, uncomment the DocumentRoot line and edit the address in quotes to the location of your site’s document root. By default, this will be in /var/www/html, and you don’t need to change this line if you have not changed the document root for your site.
Not using centos 7?
choose a different version or distribution.
Introduction
TLS, or “transport layer security”, and its predecessor SSL, which stands for “secure sockets layer”, are web protocols used to wrap normal traffic in a protected, encrypted wrapper. Using this technology, servers can send traffic safely between the server and the client without the concern that the messages will be intercepted and read by an outside party. The certificate system also assists users in verifying the identity of the sites that they are connecting with.
In this guide, we will show you how to set up a self-signed SSL certificate for use with an Apache web server on a CentOS 7 machine.
Note: A self-signed certificate will encrypt communication between your server and any clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers, users cannot use the certificate to validate the identity of your server automatically.
A self-signed certificate may be appropriate if you do not have a domain name associated with your server and for instances where the encrypted web interface is not user-facing. If you do have a domain name, in many cases it is better to use a CA-signed certificate. You can find out how to set up a free trusted certificate with the Let’s Encrypt project here.
Prerequisites
Before you begin with this guide, there are a few steps that need to be completed first.
You will need access to a CentOS 7 server with a non-root user that has sudo privileges. If you haven’t configured this yet, you can run through the CentOS 7 initial server setup guide to create this account.
You will also need to have Apache installed in order to configure virtual hosts for it. If you haven’t already done so, you can use yum to install Apache through CentOS’s default software repositories:
Next, enable Apache as a CentOS service so that it will automatically start after a reboot:
After these steps are complete, you can log in as your non-root user account through SSH and continue with the tutorial.
Step one: install mod ssl
In order to set up the self-signed certificate, we first have to be sure that mod_ssl, an Apache module that provides support for SSL encryption, is installed the server. We can install mod_ssl with the yum command:
The module will automatically be enabled during installation, and Apache will be able to start using an SSL certificate after it is restarted. You don’t need to take any additional steps for mod_ssl to be ready for use.
Step two: create a new certificate
Now that Apache is ready to use encryption, we can move on to generating a new SSL certificate. The certificate will store some basic information about your site, and will be accompanied by a key file that allows the server to securely handle encrypted data.
First, we need to create a new directory to store our private key (the /etc/ssl/certs directory is already available to hold our certificate file):
Since files kept within this directory must be kept strictly private, we will modify the permissions to make sure only the root user has access:
Now that we have a location to place our files, we can create the SSL key and certificate files with openssl:
After you enter the request, you will be taken to a prompt where you can enter information about your website. Before we go over that, let’s take a look at what is happening in the command we are issuing:
Fill out the prompts appropriately. The most important line is the one that requests the Common Name. You need to enter the domain name that you want to be associated with your server. You can enter the public IP address instead if you do not have a domain name.
The full list of prompts will look something like this:
Country Name (2 letter code) [XX]:US
State or Province Name (full name) []:Example
Locality Name (eg, city) [Default City]:Example
Organization Name (eg, company) [Default Company Ltd]:Example Inc
Organizational Unit Name (eg, section) []:Example Dept
Common Name (eg, your name or your server's hostname) []:example.com
Email Address []:webmaster@example.comBoth of the files you created will be placed in the appropriate subdirectories of the /etc/ssl directory.
While we are using OpenSSL, we should also create a strong Diffie-Hellman group, which is used in negotiating Perfect Forward Secrecy with clients.
We can do this by typing:
This may take a few minutes, but when it’s done you will have a strong DH group at /etc/ssl/certs/dhparam.pem that we can use in our configuration.
Since the version of Apache that ships with CentOS 7 does not include the SSLOpenSSLConfCmd directive, we will have to manually append the generated file to the end of our self-signed certificate. To do this, type:
The apache-selfsigned.crt file should now have both the certificate and the generated Diffie-Hellman group.
Step three: set up the certificate
We now have all of the required components of the finished interface. The next thing to do is to set up the virtual hosts to display the new certificate.
Open Apache’s SSL configuration file in your text editor with root privileges:
Find the section that begins with <VirtualHost _default_:443>. We need to make a few changes here to ensure that our SSL certificate is correctly applied to our site.
Adjusting the virtualhost directives
First, uncomment the DocumentRoot line and edit the address in quotes to the location of your site’s document root. By default, this will be in /var/www/html, and you don’t need to change this line if you have not changed the document root for your site. However, if you followed a guide like our Apache virtual hosts setup guide, your site’s document root may be different.
Next, uncomment the ServerName line and replace www.example.com with your domain name or server IP address (whichever one you put as the common name in your certificate):
/etc/httpd/conf.d/ssl.conf
<VirtualHost _default_:443>
. . .
DocumentRoot "/var/www/example.com/public_html"
ServerName www.example.com:443
Next, find the SSLProtocol and SSLCipherSuite lines and either delete them or comment them out. The configuration we be pasting in a moment will offer more secure settings than the default included with CentOS’s Apache:
/etc/httpd/conf.d/ssl.conf
. . .
# SSLProtocol all -SSLv2
. . .
# SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5:!SEED:!IDEA
Find the SSLCertificateFile and SSLCertificateKeyFile lines and change them to the directory we made at /etc/httpd/ssl:
/etc/httpd/conf.d/ssl.conf
SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
We’re now done with the changes within the actual VirtualHost block. The next changes will take place after the ending </VirtualHost> tag within this same file.
Setting up secure ssl parameters
Next, to set up Apache SSL more securely, we will be using the recommendations by Remy van Elst on the Cipherli.st site. This site is designed to provide easy-to-consume encryption settings for popular software. You can read more about his decisions regarding the Apache choices here.
Note: The suggested settings on the site linked to above offer strong security. Sometimes, this comes at the cost of greater client compatibility. If you need to support older clients, there is an alternative list that can be accessed by clicking the link on the page labelled “Yes, give me a ciphersuite that works with legacy / old software.” That list can be substituted for the items copied below.
The choice of which config you use will depend largely on what you need to support. They both will provide great security.
For our purposes, we can copy the provided settings in their entirety. We will just make two small changes.
Take a moment to read up on HTTP Strict Transport Security, or HSTS, and specifically about the “preload” functionality. Preloading HSTS provides increased security, but can have far reaching consequences if accidentally enabled or enabled incorrectly. In this guide, we will not preload the settings, but you can modify that if you are sure you understand the implications.
The other change we will make is to comment out the SSLSessionTickets directive, since this isn’t available in the version of Apache shipped with CentOS 7.
Paste in the settings from the site AFTER the end of the VirtualHost block:
/etc/httpd/conf.d/ssl.conf
. . .
</VirtualHost>
. . .
# Begin copied text
# from https://cipherli.st/
# and https://raymii.org/s/tutorials/Strong_SSL_Security_On_Apache2.html
SSLCipherSuite EECDH AESGCM:EDH AESGCM:AES256 EECDH:AES256 EDH
SSLProtocol All -SSLv2 -SSLv3
SSLHonorCipherOrder On
# Disable preloading HSTS for now. You can use the commented out header line that includes# the "preload" directive if you understand the implications.#Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains"
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
# Requires Apache >= 2.4
SSLCompression off
SSLUseStapling on
SSLStaplingCache "shmcb:logs/stapling-cache(150000)"
# Requires Apache >= 2.4.11
# SSLSessionTickets Off
When you are finished making these changes, you can save and close the file.
(recommended) modify the unencrypted virtual host file to redirect to https
As it stands now, the server will provide both unencrypted HTTP and encrypted HTTPS traffic. For better security, it is recommended in most cases to redirect HTTP to HTTPS automatically. If you do not want or need this functionality, you can safely skip this section.
To redirect all traffic to be SSL encrypted, create and open a file ending in .conf in the /etc/httpd/conf.d directory:
Inside, create a VirtualHost block to match requests on port 80. Inside, use the ServerName directive to again match your domain name or IP address. Then, use Redirect to match any requests and send them to the SSL VirtualHost. Make sure to include the trailing slash:
/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerName www.example.com
Redirect "/" "https://www.example.com/"
</VirtualHost>
Save and close this file when you are finished.
Step four: activate the certificate
By now, you have created an SSL certificate and configured your web server to apply it to your site. To apply all of these changes and start using your SSL encryption, you can restart the Apache server to reload its configurations and modules.
First, check your configuration file for syntax errors by typing:
As long as the output ends with Syntax OK, you are safe to continue. If this is not part of your output, check the syntax of your files and try again:
Output
. . .
Syntax OK
Restart the Apache server to apply your changes by typing:
Next, make sure port 80 and 443 are open in your firewall. If you are not running a firewall, you can skip ahead.
If you have a firewalld firewall running, you can open these ports by typing:
If have an iptables firewall running, the commands you need to run are highly dependent on your current rule set. For a basic rule set, you can add HTTP and HTTPS access by typing:
In your web browser, try visiting your domain name or IP with https:// to see your new certificate in action.
https://example.com/
Your web browser will likely warn you that the site’s security certificate is not trusted. Since your certificate isn’t signed by a certificate authority that the browser trusts, the browser is unable to verify the identity of the server that you are trying to connect to. We created a self-signed certificate instead of a trusted CA-signed certificate, so this makes perfect sense.
Once you add an exception to the browser’s identity verification, you will be allowed to proceed to your newly secured site.
Conclusion
You have configured your Apache server to handle both HTTP and HTTPS requests. This will help you communicate with clients securely and avoid outside parties from being able to read your traffic.
If you are planning on using SSL for a public website, you should probably purchase an SSL certificate from a trusted certificate authority to prevent the scary warnings from being shown to each of your visitors.
Prerequisites
Before you begin with this guide, there are a few steps that need to be completed first.
Setting up secure ssl parameters
Next, to set up Apache SSL more securely, we will be using the recommendations by Remy van Elst on the Cipherli.st site. This site is designed to provide easy-to-consume encryption settings for popular software. You can read more about his decisions regarding the Apache choices here.
Step four: activate the certificate
By now, you have created an SSL certificate and configured your web server to apply it to your site. To apply all of these changes and start using your SSL encryption, you can restart the Apache server to reload its configurations and modules.
First, check your configuration file for syntax errors by typing:
As long as the output ends with Syntax OK, you are safe to continue. If this is not part of your output, check the syntax of your files and try again:
Output
. . .
Syntax OK
Restart the Apache server to apply your changes by typing:
Next, make sure port 80 and 443 are open in your firewall. If you are not running a firewall, you can skip ahead.
If you have a firewalld firewall running, you can open these ports by typing:
Step one: install mod ssl
In order to set up the self-signed certificate, we first have to be sure that mod_ssl, an Apache module that provides support for SSL encryption, is installed the server. We can install mod_ssl with the yum command:
The module will automatically be enabled during installation, and Apache will be able to start using an SSL certificate after it is restarted. You don’t need to take any additional steps for mod_ssl to be ready for use.
Step three: set up the certificate
We now have all of the required components of the finished interface. The next thing to do is to set up the virtual hosts to display the new certificate.
Open Apache’s SSL configuration file in your text editor with root privileges:
Find the section that begins with <VirtualHost _default_:443>. We need to make a few changes here to ensure that our SSL certificate is correctly applied to our site.
Step two: create a new certificate
Now that Apache is ready to use encryption, we can move on to generating a new SSL certificate. The certificate will store some basic information about your site, and will be accompanied by a key file that allows the server to securely handle encrypted data.
First, we need to create a new directory to store our private key (the /etc/ssl/certs directory is already available to hold our certificate file):
Включение виртуального хоста
Виртуальный хост готов к работе, но не включен, потому пока что Apache не поддерживает его. Чтобы включит виртуальный хост, нужно создать символьную ссылку в каталоге sites-enabled, указывающую на новый виртуальный хост. Запустите команду:
Загрузка необходимых файлов на веб-сервер
Прежде всего, необходимо загрузить представленные в панели 1cloud файлы .ca и .crt на веб-сервер. Если ваш сервер не имеет графического окружения рабочего стола, вы можете загрузить эти файлы на другой компьютер, а затем перенести их одним из приведенных ниже способов.
Примечание: подразумевается, что необходимая для работы пара закрытый/открытый ключ была сгенерирована на том же веб-сервере, на который вы будете переносить приобретенный сертификат. Если вы создавали ключи на другой машине, вам необходимо также перенести файл закрытого ключа .key на ваш веб-сервер по аналогии с описанной ниже процедурой копирования файлов сертификатов.
О самоподписанных сертификатах
SSL-сертификат – это способ шифрования информации сайта с целью создать более защищенное соединение. Кроме того, такой сертификат может предоставить посетителям сайта идентификационную информацию виртуального сервера.
Перенос сертификатов с компьютера linux/mac os:
Самый простой способ загрузки сертификатов на сервер – опция SCP, встроенная в возможность терминала вашего компьютера:
Состояние сертификата
Проверить состояние сертификата можно по следующей ссылке (вместо условного домена укажите своё базовое доменное имя):
Требования
Для выполнения данного руководства на VPS должен быть установлен nginx.
Чтобы установить nginx:
- установите репозиторий EPEL:
Установка ssl-сертификата на centos и ngnix — первый vps
SSL сертификаты можно приобрести у нас.
После приобретения сертификата у вас должны быть следующие файлы:
- файл ключа, который был создан Вами при генерации CSR-запроса для получения сертификата (к примеру private.key),
- файл сертификата, например sert1.crt,
- файл промежуточного сертификата (промежуточных сертификатов может быть несколько), например sert2.crt, sert3.crt,
- файл корневого сертификата sert4.crt.
Вышеперечисленные сертификаты могут быть в виде текста (в таком случае можно данный текст можно сохранить через текстовый редактор с расширением .crt):
-----BEGIN CERTIFICATE-----
много строк с текстом
много строк с текстом
много строк с текстом
-----END CERTIFICATE-----Все эти файлы (private.key, sert1.crt, sert2.crt, sert3.crt, sert4.crt) необходимо скопировать под root по ssh на вашу ВМ Битрикс в папку /etc/nginx/ssl/domen – папку надо предварительно создать.
После чего нам необходимо объединить все сертификаты в один файл pem. Здесь важно соблюсти обратную последовательность: сначала должен быть сертификат для вашего домена sert1.crt, затем промежуточные сертификаты sert3.crt, sert2.crt и затем корневой сертификат sert4.crt. Сделать это можно через любой текстовый редактор или через командную строку сервера:
cd /etc/nginx/ssl/domen/
cat sert1.crt sert3.crt sert2.crt sert4.crt > sert.pemПолученный файл сертификата sert.pem скопировать в папку /etc/nginx/ssl/domen/ и прописать в конфигурационном файле nginx путь к публичному ключу – /etc/nginx/bx/conf/ssl.conf:
ssl_certificate /etc/nginx/ssl/domen/cert.pem;
ssl_certificate_key /etc/nginx/ssl/domen/private.key;Перезагружаем nginx:
[root@1 conf]# service nginx restart
Stopping nginx:
[ OK ]
Starting nginx:
[ OK ]и проверяем результат, набрав ваш домен по протоколу https – https://www.sslshopper.com/ssl-checker.html
Заключение
Теперь веб-сервер Apache защищён при помощи SSL-сертификата Let’s Encrypt. Не забывайте о том, что клиент Let’s Encrypt до сих пор находится в бета-версии, потому очень важно следить за выходом обновлений и своевременно устанавливать их.
Tags:
