Это старая версия документа.


Сертификаты

Одной из наиболее распространенных форм криптографии сегодня является криптография на открытых ключах. Криптография на открытых ключах использует открытый (public) и закрытый (secret) ключи. Система выполняет шифрование с использованием открытого ключа. Расшифрована такая информация может быть только с использованием закрытого ключа.

Обычное использование криптографии на открытых ключах - шифрование трафика приложений с использованием соединений по протоколам SSL и TLS. Например, настройка Apache для предоставления HTTPS, протокола HTTP поверх SSL. Это позволяет применить шифрование трафика с протоколом, который сам по себе шифрование не поддерживает.

Сертификат - это метод, используемый для распространения открытого ключа и другой информации о сервере и организации, ответственной за него. Сертификаты могут иметь цифровую подпись, сделанную Центром сертификации или CA. CA - это третья сторона, которая подтверждает, что информация, содержащаяся в сертификате, верна.

Типы сертификатов

Для установки безопасного сервера с использованием криптографии на открытых ключах в большинстве случаев вы посылаете свой запрос на сертификат (включающий ваш открытый ключ), подтверждение идентичности вашей компании и оплату центру сертификации. Центр проверяет запрос на сертификат и вашу идентичность, и затем отсылает в ответ сертификат для вашего сервера. В качестве альтернативы вы можете использовать самоподписанный сертификат.

Обратите внимание, что самоподписанный сертификат не может быть использованным в большинстве производственных сред.

Продолжая пример с HTTPS, сертификат, подписанный CA, предоставляет два важных свойства в отличие от самоподписанного сертификата:

  1. Браузеры (обычно) автоматически распознают такой сертификат и позволяют устанавливать защищенные соединения без предупреждения пользователя.

  2. Когда CA выпускает подписанный сертификат, он гарантирует идентичность организации, которая предоставляет интернет страницы браузеру.

Большинство интернет браузеров и компьютеров, которые поддерживают SSL имеют список центров сертификации, чьи сертификаты они автоматически принимают. Если браузер встречает сертификат, чей заверяющий центр не попал в этот список, он запрашивает пользователя на подтверждение или запрет соединения. При этом другие приложения могут выдавать сообщения об ошибке, когда используется самоподписанный сертификат.

Процесс получения сертификата из CA довольно прост. Короткий обзор его приведен ниже:

  1. Создайте пару из открытого и закрытого ключей.

  2. Создайте запрос на сертификат на основе открытого ключа. Запрос на сертификат содержит информацию о вашем сервере и управляющей им компании.

  3. Пошлите запрос на сертификат вместе с документами, подтверждающими вашу идентичность, в CA. Мы не можем сказать вам какой центр сертификации выбрать. Ваше решение может основываться на вашем прошлом опыте, опыте ваших друзей и коллег или исключительно на факторе цены. Как только вы определитесь с CA, вам надо следовать их инструкциям по тому, как получить у них сертификат.

  4. Когда центр убедится, что вы действительно тот, за кого себя выдаете, они отправят вам цифровой сертификат.

  5. Установите это сертификат на ваш защищенный сервер и настройте соответствующие приложения на его использование.

Создание запроса на подпись сертификата (CSR)

Вне зависимости от того получаете и вы сертификат от CA или создаете самоподписаный, первым шагом будет создание ключа.

If the certificate will be used by service daemons, such as Apache, Postfix, Dovecot, etc, a key without a passphrase is often appropriate. Not having a passphrase allows the services to start without manual intervention, usually the preferred way to start a daemon.

This section will cover generating a key with a passphrase, and one without. The non-passphrase key will then be used to generate a certificate that can be used with various service daemons.

Running your secure service without a passphrase is convenient because you will not need to enter the passphrase every time you start your secure service. But it is insecure and a compromise of the key means a compromise of the server as well.

To generate the keys for the Certificate Signing Request (CSR) run the following command from a terminal prompt:

openssl genrsa -des3 -out server.key 2048

Generating RSA private key, 2048 bit long modulus ……………………..++++++ …….++++++ e is 65537 (0x10001) Enter pass phrase for server.key:

You can now enter your passphrase. For best security, it should at least contain eight characters. The minimum length when specifying -des3 is four characters. It should include numbers and/or punctuation and not be a word in a dictionary. Also remember that your passphrase is case-sensitive.

Re-type the passphrase to verify. Once you have re-typed it correctly, the server key is generated and stored in the server.key file.

Now create the insecure key, the one without a passphrase, and shuffle the key names:

openssl rsa -in server.key -out server.key.insecure mv server.key server.key.secure mv server.key.insecure server.key

The insecure key is now named server.key, and you can use this file to generate the CSR without passphrase.

To create the CSR, run the following command at a terminal prompt:

openssl req -new -key server.key -out server.csr

It will prompt you enter the passphrase. If you enter the correct passphrase, it will prompt you to enter Company Name, Site Name, Email Id, etc. Once you enter all these details, your CSR will be created and it will be stored in the server.csr file.

You can now submit this CSR file to a CA for processing. The CA will use this CSR file and issue the certificate. On the other hand, you can create self-signed certificate using this CSR.

Создание самоподписанного сертификата

To create the self-signed certificate, run the following command at a terminal prompt:

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

The above command will prompt you to enter the passphrase. Once you enter the correct passphrase, your certificate will be created and it will be stored in the server.crt file.

If your secure server is to be used in a production environment, you probably need a CA-signed certificate. It is not recommended to use self-signed certificate.

Установка сертификата

You can install the key file server.key and certificate file server.crt, or the certificate file issued by your CA, by running following commands at a terminal prompt:

sudo cp server.crt /etc/ssl/certs sudo cp server.key /etc/ssl/private

Now simply configure any applications, with the ability to use public-key cryptography, to use the certificate and key files. For example, Apache can provide HTTPS, Dovecot can provide IMAPS and POP3S, etc.

Центр сертификатов

If the services on your network require more than a few self-signed certificates it may be worth the additional effort to setup your own internal Certification Authority (CA). Using certificates signed by your own CA, allows the various services using the certificates to easily trust other services using certificates issued from the same CA.

  First, create the directories to hold the CA certificate and related files:
  sudo mkdir /etc/ssl/CA
  sudo mkdir /etc/ssl/newcerts
  The CA needs a few additional files to operate, one to keep track of the last serial number used by the CA, each certificate must have a unique serial number, and another file to record which certificates have been issued:
  sudo sh -c "echo '01' > /etc/ssl/CA/serial"
  sudo touch /etc/ssl/CA/index.txt
  The third file is a CA configuration file. Though not strictly necessary, it is very convenient when issuing multiple certificates. Edit /etc/ssl/openssl.cnf, and in the [ CA_default ] change:
  dir             = /etc/ssl/             # Where everything is kept
  database        = $dir/CA/index.txt     # database index file.
  certificate     = $dir/certs/cacert.pem # The CA certificate
  serial          = $dir/CA/serial        # The current serial number
  private_key     = $dir/private/cakey.pem# The private key
  Next, create the self-singed root certificate:
  openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650
  You will then be asked to enter the details about the certificate.
  Now install the root certificate and key:
  sudo mv cakey.pem /etc/ssl/private/
  sudo mv cacert.pem /etc/ssl/certs/
  You are now ready to start signing certificates. The first item needed is a Certificate Signing Request (CSR), see Generating a Certificate Signing Request (CSR) for details. Once you have a CSR, enter the following to generate a certificate signed by the CA:
  sudo openssl ca -in server.csr -config /etc/ssl/openssl.cnf
  After entering the password for the CA key, you will be prompted to sign the certificate, and again to commit the new certificate. You should then see a somewhat large amount of output related to the certificate creation.
  There should now be a new file, /etc/ssl/newcerts/01.pem, containing the same output. Copy and paste everything beginning with the line: -----BEGIN CERTIFICATE----- and continuing through the line: ----END CERTIFICATE----- lines to a file named after the hostname of the server where the certificate will be installed. For example mail.example.com.crt, is a nice descriptive name.
  Subsequent certificates will be named 02.pem, 03.pem, etc.
  Replace mail.example.com.crt with your own descriptive name.
  Finally, copy the new certificate to the host that needs it, and configure the appropriate applications to use it. The default location to install certificates is /etc/ssl/certs. This enables multiple services to use the same certificate without overly complicated file permissions.
  For applications that can be configured to use a CA certificate, you should also copy the /etc/ssl/certs/cacert.pem file to the /etc/ssl/certs/ directory on each server.

Ссылки

  For more detailed instructions on using cryptography see the SSL Certificates HOWTO by tlpd.org
  The Wikipedia HTTPS page has more information regarding HTTPS.
  For more information on OpenSSL see the OpenSSL Home Page.
  Also, O'Reilly's Network Security with OpenSSL is a good in depth reference.