- linux-notes.org
- Создание нового приватного ключа (Private Key) и Certificate Signing Request (CSR).
- Создание самоподписанного сертификата (Self-Signed Certificate).
- Проверка CSR файла.
- Создать приватный RSA ключ (Private Key).
- Удалить ключевую фразу (Passphrase) с ключа.
- Проверка сертификата (Certificate).
- Проверка подписанного сертификата (Certificate Signer Authority).
- Создать тестовый SSL сервер.
- Проверить хеш вашего сертификата.
- Конвертирование сертификатов с DER в PEM формат.
- Конвертирование сертификатов с PEM в DER формат.
- Конвертирование CSR c DER в PEM формат.
- Конвертирование сертификата и приватного ключа в PKCS#12 фотмат.
- Создание CSR используя приватный ключ (private key).
- Проверьте содержимое сертификата в PKCS12 формате.
- Конвертирование PKCS12 формата в PEM сертификат.
- Получить SHA-1 отпечаток сертификата или CSR
- Получить MD5 отпечаток сертификата или CSR
- Тестирование SSL сертификата по URL.
- Поверка PEM сертификата на завершение (Expiration Date).
- Проверка завершения SSL сертификата (Expiration Date) по URL.
- Проверить поддержку SSL версии V2/V3 по URL.
- Проверка поддержки cipher для сайта по URL.
- Какой алгоритм используется в сертификате (проверка).
- Получить сертификат по URL
- Добавить комментарий Отменить ответ
- OpenSSL create certificate chain with Root & Intermediate CA
- Root vs Intermediate Certificate
- Step 1: Install OpenSSL
- Step 2: OpenSSL encrypted data with salted password
- Step 3: Create OpenSSL Root CA directory structure
- Step 4: Configure openssl.cnf for Root CA Certificate
- Step 5: Generate Root CA Private Key
- OpenSSL verify Root CA key
- Step 6: Create your own Root CA Certificate
- OpenSSL verify Certificate
- Step 7: Create OpenSSL Intermediate CA directory structure
- Step 8: Configure openssl.cnf for Intermediate CA Certificate
- Step 9: Generate Intermediate CA key
- Step 10: Create immediate CA Certificate Signing Request (CSR)
- Step 11: Sign and generate immediate CA certificate
- OpenSSL verify Certificate
- Step 12: OpenSSL Create Certificate Chain (Certificate Bundle)
- OpenSSL verify Certificate Chain
- Conclusion
- References
- Related Posts
linux-notes.org
При работе с SSL, нужно уметь работать с утилитой OpenSSL чтобы создавать, конвертировать, управляют SSL-сертификатами. В этой статье «Примеры использования OpenSSL в Unix/Linux» я буду говорить о примерах использования OpenSSL.
Некоторые из сокращений, связанных с сертификатами:
- SSL – Secure Socket Layer (Безопасный уровень сокета).
- CSR – Certificate Signing Request (Запрос на подпись сертификата).
- TLS – Transport Layer Security (Транспортный уровень безопастности).
- PEM – Privacy Enhanced Mail
- DER – Distinguished Encoding Rules
- SHA – Secure Hash Algorithm (Безопасный hash алгорит).
- PKCS – Public-Key Cryptography Standards (Стандарты шифрования публичных ключей).
Создание нового приватного ключа (Private Key) и Certificate Signing Request (CSR).
Команда выше будет генерировать CSR и 2048-битный RSA ключ. Если вы собираетесь использовать этот сертификат в Apache или Nginx, то вам необходимо отправить этот CSR файл в службу сертификации и они дадут вам подписанный сертификат в «der» или «pem» формате. После чего вы настроите его на веб-сервере Apache или Nginx.
Так же, можно использовать такой вариант:
Создание самоподписанного сертификата (Self-Signed Certificate).
Команда выше будет генерировать самоподписанный сертификат (self-signed) и 2048-битный RSA ключ. Я также использую алгорит шифрования — SHA256. Так как он считается наиболее безопасным в данный момент.
Замечание: По умолчанию, будет сгенерирован ключ толкьо на 1 месяц, если нужно создать на более длительное время — используйте опцию «–days», пример использования ниже.
Пример: Чтобы создать self-signed сертификат на 2 год, используйте:
Проверка CSR файла.
и вы получите информацию.
Проверка подписи (signature):
Кем(кому) был выдан сертификат:
Показать открытый ключ (public key):
Создать приватный RSA ключ (Private Key).
Чтобы это сделать, выполните:
Если вам просто нужно генерировать RSA закрытый ключ, вы можете использовать команду что выше. Я включил 2048 шифрование, для безопастности.
Удалить ключевую фразу (Passphrase) с ключа.
Если вы установили ключевую фразу для ключа, то при каждом старте веб-сервера (Apache/Nginx) вы должны будите вводить пароль. Если это вас злит, вы можете с легкостью удалить passphrase с RSA ключа.
Проверка приватного ключа (Private Key)
Если вы сомневаетесь в ключевом файле, вы можете использовать команду что выше для проверки.
Проверка сертификата (Certificate).
Если вы хотите проверить данные сертификата( CN, OU, и т.д.), то вы можете использовать команду, которая даст вам сведения о сертификате:
Команда довольна простая в использовании.
Проверка подписанного сертификата (Certificate Signer Authority).
Можно узнать много полезного.
Создать тестовый SSL сервер.
Команда OpenSSL s_server реализует общий SSL/TLS-сервер. Она должна использоваться только для целей тестирования. В приведенном ниже примере данный сервер прослушивает соединения на порту 8080 и возвращает отформатированную HTML страницу статуса, который включает много информации о ciphers:
Проверить хеш вашего сертификата.
Конвертирование сертификатов с DER в PEM формат.
Как правило, при покупке SSL сертификатов, его отдают вам в формате .der и если вам нужно использовать его в веб-сервере или .pem формате, вы можете использовать команду выше, чтобы преобразовать такие сертификаты.
Конвертирование сертификатов с PEM в DER формат.
В случае, если вам необходимо изменить .pem формат в .der:
Конвертирование CSR c DER в PEM формат.
Конвертирование сертификата и приватного ключа в PKCS#12 фотмат.
Если вам необходимо использовать сертификат с приложением Java или с любым другим, кто принимает формат PKCS# 12.
Совет: Вы можете включить «chain certificate» используя «-chain» опцию:
Создание CSR используя приватный ключ (private key).
Если вы не хотите создать новый секретный ключ, а хотите используя вместо существующего, вы можете с предыдущей командой.
Проверьте содержимое сертификата в PKCS12 формате.
PKCS12 — это двоичный формат, так что вы не сможете просматривать содержимое в блокноте или другом редакторе. Таким образом, вы должны использовать команду что выше, для просмотра содержимого файла формата PKCS12.
Конвертирование PKCS12 формата в PEM сертификат.
Получить SHA-1 отпечаток сертификата или CSR
Чтобы получить отпечаток SHA1 сертификата с использованием OpenSSL, используйте команду, приведенную ниже:
Чтобы получить SHA1 отпечаток пальца CSR с использованием OpenSSL, используйте команду, приведенную ниже:
Получить MD5 отпечаток сертификата или CSR
Чтобы получить отпечаток MD5 сертификата с использованием OpenSSL, используйте команду, приведенную ниже:
Чтобы получить MD5 отпечаток пальца CSR с использованием OpenSSL, используйте команду, приведенную ниже:
Тестирование SSL сертификата по URL.
Я использую это довольно часто для проверки SSL-сертификатов по URL с сервера. Это очень удобно для проверки некоторых деталей протокола, шифров и CERT.
Узнать версию OpenSSL
Поверка PEM сертификата на завершение (Expiration Date).
Проверка завершения SSL сертификата (Expiration Date) по URL.
Проверить поддержку SSL версии V2/V3 по URL.
Проверка SSL версии V2:
Проверка SSL версии V3:
Проверка TLS 1.0:
Проверка TLS 1.1:
Проверка TLS 1.2:
Проверка поддержки cipher для сайта по URL.
Какой алгоритм используется в сертификате (проверка).
Или, используя URL:
Получить сертификат по URL
Команда что ниже, сохранит сертификат в файл прямо по URL сайта:
Если веб-сервер имеет несколько сертификатов на один IP-адрес, то вам нужно будет сообщить OpenSSL, какой сертификат будет использоваться, пример ниже:
Вот и все, много полезностей и все в одной статье «Примеры использования OpenSSL в Unix/Linux».
Добавить комментарий Отменить ответ
Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.
Источник
OpenSSL create certificate chain with Root & Intermediate CA
Table of Contents
Openssl create certificate chain requires Root CA and Intermediate certificate, In this article I will share Step-by-Step Guide to create root and intermediate certificates and then use these certificates to create certificate CA bundle in Linux. I hope you have an overview of all the terminologies used with OpenSSL.
Root vs Intermediate Certificate
- A certificate chain or certificate CA bundle is a sequence of certificates, where each certificate in the chain is signed by the subsequent certificate.
- The Root CA is the top level of certificate chain while intermediate CAs or Sub CAs are Certificate Authorities that issue off an intermediate root.
- Typically, the root CA does not sign server or client certificates directly.
- The root CA is only ever used to create one or more intermediate CAs, which are trusted by the root CA to sign certificates on their behalf. This is best practice.
- It allows the root key to be kept offline and unused as much as possible, as any compromise of the root key is disastrous.
- An intermediate certificate authority (CA) is an entity that can sign certificates on behalf of the root CA.
- The root CA signs the intermediate certificate, forming a chain of trust.
- The purpose of using an intermediate CA is primarily for security.
- The root key can be kept offline and used as infrequently as possible.
- If the intermediate key is compromised, the root CA can revoke the intermediate certificate and create a new intermediate cryptographic pair.
I have already written multiple articles on OpenSSL, I would recommend you to also check them for more overview on openssl examples:
- Beginners guide to understand all Certificate related terminologies used with openssl
- Generate openssl self-signed certificate with example
- Create your own Certificate Authority and generate a certificate signed by your CA
- Create certificate chain (CA bundle) using your own Root CA and Intermediate Certificates with openssl
- Create server and client certificates using openssl for end to end encryption with Apache over SSL
- Create SAN Certificate to protect multiple DNS, CN and IP Addresses of the server in a single certificate
Step 1: Install OpenSSL
On RHEL/CentOS 7/8 you can use yum or dnf respectively while on Ubuntu use apt-get to install openssl rpm
Step 2: OpenSSL encrypted data with salted password
When we create private key for Root CA certificate, we have an option to either use encryption for private key or create key without any encryption. As if we choose to create private key with encryption such as 3DES, AES then you will have to provide a passphrase every time you try to access the private key.
I have already written another article with the steps for openssl encd data with salted password to encrypt the password file. So I will not repeat the steps here again.
We will use the same encrypted password file for all our examples in this article to demonstrate openssl create certificate chain examples.
Step 3: Create OpenSSL Root CA directory structure
We can also create CA bundle with all the certificates without creating any directory structure and using some manual tweaks but let us follow the long procedure to better understanding. In RHEL/CentOS 7/8 the default location for all the certificates are under /etc/pki/tls . But for this article we will create a new directory structure /root/tls/ to store our certificates.
Create a parent directory to store the certificates
Within the CA’s root directory, we need to create two sub directories:
certs: This will be used to keep copies of all of the certificates that we issue with our CA.
private: This will be used to keep a copy of the CA certificate’s private key.
Besides key generation, we will create three files that our CA infrastructure will need.
A serial file is used to keep track of the last serial number that was used to issue a certificate. It’s important that no two certificates ever be issued with the same serial number from the same CA. OpenSSL is somewhat quirky about how it handles this file. It expects the value to be in hex, and it must contain at least two digits, so we must pad the value by prepending a zero to it.
Next we will create index.txt file which is a database of sorts that keeps track of the certificates that have been issued by the CA. Since no certificates have been issued at this point and OpenSSL requires that the file exist, we’ll simply create an empty file.
Check the list of contents under /root/tls
Step 4: Configure openssl.cnf for Root CA Certificate
We will have a default configuration file openssl.cnf in RHEL/CentOS 7/8 under /etc/pki/tls/openssl.cnf which is added by the openssl rpm. We will copy this file to your custom certificate location i.e. /root/tls and will modify the content of this file to create Root CA Certificate
The OpenSSL command for the CA functions is aptly named ca , and so the first section that we’re interested in is named ca . For our purposes, this section is quite simple, containing only a single key: default_ca . The value is the name of a section containing the configuration for the default CA. The [ CA_default ] section contains a range of defaults. Make sure you declare the directory you chose earlier /root/tls .
The x509_extensions key specifies the name of a section that will contain the extensions to be added to each certificate issued by our CA.
The policy key specifies the name of a section that will be used for the default policy.
A policy definition is a set of keys with the same name as the fields in a certificate’s distinguished name. For each key or field, there are three legal values: match, supplied, or optional.
- match: means that the field by that name in a certificate request must match the same field in the CA’s certificate.
- supplied: means that the certificate request must contain the field.
- optional: means that the field is not required in the certificate request.
We will apply policy_match for creating root CA certificates so we have added this as a default value for policy under CA_default .
And policy_anything for creating Intermediate CA certificates
The values under [ req ] section are applied when creating Certificate Signing Requests (CSR) or Certificates. The x509_extensions key specifies the name of a section that contains the extensions that we want included in the certificate.
The eq_distinguished_name key determine how OpenSSL gets the information it needs to fill in the certificate’s distinguished name. I have given few default values while the Common Name must be supplied as we have defined under policy key.
These are the extensions we will use with openssl create certificate chain. We will use v3_ca extension to create root CA certificate and v3_intermediate extension for intermediate CA certificate.
Step 5: Generate Root CA Private Key
- We will create root CA key using 4096 bits and 3DES encryption
- I am using my encrypted password file to provide the passphrase for the private key
- We will store this private key under /root/tls/private
OpenSSL verify Root CA key
We will use openssl command to view the content of private key:
Step 6: Create your own Root CA Certificate
- OpenSSL create certificate chain requires Root and Intermediate Certificate. In this step you’ll take the place of VeriSign, Thawte, etc.
- Use the Root CA key cakey.pem to create a Root CA certificate cacert.pem
- Give the root certificate a long expiry date. Once the root certificate expires, all certificates signed by the CA become invalid.
- Whenever you use the openssl req tool, you must specify a configuration file to use with the -config option, otherwise OpenSSL will default to /etc/pki/tls/openssl.cnf
- We will use v3_ca extensions to create CA certificate
Use below command to create Root Certificate Authority Certificate cacert.pem
To change the format of the certificate to PEM format
OpenSSL verify Certificate
Execute the below command for openssl verify root CA certificate
The output shows:
- the Signature Algorithm used
- the dates of certificate Validity
- the Public-Key bit length
- the Issuer , which is the entity that signed the certificate
- the Subject , which refers to the certificate itself
The output also shows the X509v3 extensions. We applied the v3_ca extension, so the options from [ v3_ca ] should be reflected in the output.
Step 7: Create OpenSSL Intermediate CA directory structure
Now to complete setup of openssl create certificate chain, we will also need intermediate certificate for the CA bundle. We will create new directory structure /root/tls/intermediate under our parent folder /root/tls to keep both the certificate files separate.
We will also create sub directories under /root/tls/intermediate to store our keys and certificate files. We will also need a serial and index.txt file as we created for our Root CA Certificate.
Add a crlnumber file to the intermediate CA directory tree. crlnumber is used to keep track of certificate revocation lists.
Step 8: Configure openssl.cnf for Intermediate CA Certificate
Copy the openssl.cnf used for our Root CA Certificate from /root/tls/openssl.cnf to /root/tls/intermediate/openssl.cnf . Below are the options we have been changed compared to the root CA certificate configuration file:
Step 9: Generate Intermediate CA key
Generate intermediate CA key ca-intermediate.key .using openssl genrsa with 3DES encryption and our encrypted passphrase file to avoid any password prompt.
Step 10: Create immediate CA Certificate Signing Request (CSR)
- Use the intermediate CA key to create a certificate signing request (CSR).
- The details should generally match the root CA.
- The Common Name, however, must be different.
Next we will create intermediate CA certificate signing request (CSR) under /root/tls/intermediate/csr with expiry value lesser than the root CA certificate
Step 11: Sign and generate immediate CA certificate
Now the last step before we conclude openssl create certificate chain, we need to create immediate CA certificate using our Certificate Signing request which we created in above step. We will use v3_intermediate_ca extension from /root/tls/openssl.cnf to create the intermediate CA certificate under /root/tls/intermediate/certs/intermediate.cacert.pem
The index.txt file is where the OpenSSL ca tool stores the certificate database. Do not delete or edit this file by hand. It should now contain a line that refers to the intermediate certificate.
OpenSSL verify Certificate
Verify the Intermediate CA Certificate content
Next openssl verify intermediate certificate against the root certificate. An OK indicates that the chain of trust is intact.
To convert the format of the Certificate to PEM format
Step 12: OpenSSL Create Certificate Chain (Certificate Bundle)
To openssl create certificate chain (certificate bundle), concatenate the intermediate and root certificates together.
In the below example I have combined my Root and Intermediate CA certificates to openssl create certificate chain in Linux. We will use this file later to verify certificates signed by the intermediate CA.
OpenSSL verify Certificate Chain
After openssl create certificate chain, to verify certificate chain use below command:
To verify certificate chain for online pages such as Google:
To show certificates from the certificate chain for Google:
Conclusion
In this tutorial we learned how to create certificate chain using openssl with root and intermediate certificate. You can add upto «n» number of intermediate certificates in the certificate chain depending upon your requirement.
Lastly I hope the steps from the article for openssl create certificate chain with Root and Intermediate Certificate on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
References
Related Searches: Openssl create certificate chain, root ca certificate, intermediate ca certificate, verify certificate chain, create ca bundle, verify ca certificate, openssl verify certificate, openssl view certificate, openssl get certificate info
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Источник