Бруй В.В., Карлов С.В. - Linux-сервер - пошаговые инструкции - инсталляции и настройки (1077321), страница 49
Текст из файла (страница 49)
There are several options.# default: PrintableString, T61String, BMPString.# pkix: PrintableString, BMPString.# utf8only: only UTF8Strings.# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).# MASK:XXXX a literal mask value.# WARNING: current versions of Netscape crash on BMPStrings orUTF8Strings# so use this option with caution!string_mask = nombstr# req_extensions = v3_req # The extensions to add to a certificate request[ req_distinguished_name ]countryNamecountryName_defaultcountryName_mincountryName_max====stateOrProvinceNamestateOrProvinceName_default= State or Province Name (full name)= Moscow regionlocalityNamelocalityName_default= Locality Name (eg, city)= Ybileynyi0.organizationName0.organizationName_default= Organization Name (eg, company)= SIP RIACountry Name (2 letter code)RU22Глава 12.
OpenSSL – программное обеспечение для безопасной передачи данных187# we can do this but it is not needed normally :-)#1.organizationName= Second Organization Name (eg, company)#1.organizationName_default= World Wide Web Pty LtdorganizationalUnitName= Organizational Unit Name (eg, section)commonNamecommonName_defaultcommonName_max= Common Name (eg, YOUR name)= www.dymatel.und= 64emailAddressemailAddress_defaultemailAddress_max= Email Address= root@dymatel.und= 40# SET-ex3= SET extension number 3[ req_attributes ]challengePasswordchallengePassword_minchallengePassword_max= A challenge password= 8= 20unstructuredName= An optional company name[ usr_cert ]# These extensions are added when 'ca' signs a request.# This goes against PKIX guidelines but some CAs do it and some software# requires this to avoid interpreting an end user certificate as a CA.basicConstraints=CA:FALSE# Here are some examples of the usage of nsCertType.
If it is omitted# the certificate can be used for anything *except* object signing.# This is OK for an SSL server.# nsCertType= server# For an object signing certificate this would be used.# nsCertType = objsign# For normal client use this is typical# nsCertType = client, email# and for everything including object signing:# nsCertType = client, email, objsign# This is typical in keyUsage for a client certificate.# keyUsage = nonRepudiation, digitalSignature, keyEncipherment# This will be displayed in Netscape's comment listbox.nsComment= "OpenSSL Generated Certificate"# PKIX recommendations harmless if included in all certificates.subjectKeyIdentifier=hashauthorityKeyIdentifier=keyid,issuer:always# This stuff is for subjectAltName and issuerAltname.# Import the email address.# subjectAltName=email:copy# Copy subject details# issuerAltName=issuer:copy188Часть 3.
Криптографическое программное обеспечение...#nsCaRevocationUrl#nsBaseUrl#nsRevocationUrl#nsRenewalUrl#nsCaPolicyUrl#nsSslServerName= http://www.domain.dom/ca-crl.pem[ v3_req ]# Extensions to add to a certificate requestbasicConstraints = CA:FALSEkeyUsage = nonRepudiation, digitalSignature, keyEncipherment[ v3_ca ]# Extensions for a typical CA# PKIX recommendation.subjectKeyIdentifier=hashauthorityKeyIdentifier=keyid:always,issuer:always# This is what PKIX recommends but some broken software chokes on critical# extensions.#basicConstraints = critical,CA:true# So we do this instead.basicConstraints = CA:true####Key usage: this is typical for a CA certificate. However since it willprevent it being used as an test self-signed certificate it is bestleft out by default.keyUsage = cRLSign, keyCertSign# Some might want this also# nsCertType = sslCA, emailCA####Include email address in subject alt name: another PKIX recommendationsubjectAltName=email:copyCopy issuer detailsissuerAltName=issuer:copy#####DER hex encoding of an extension: beware experts only!obj=DER:02:03Where 'obj' is a standard or added objectYou can even override a supported extension:basicConstraints= critical, DER:30:03:01:01:FF[ crl_ext ]# CRL extensions.# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.# issuerAltName=issuer:copyauthorityKeyIdentifier=keyid:always,issuer:alwaysШаг 2Группа разработчиков OpenSSL предъявляет некоторые требования, затрудняющие использованиефайлов CA.pl или CA.sh для самостоятельной подписи ключей.
Для подписи ключей авторы рекомендуютГлава 12. OpenSSL – программное обеспечение для безопасной передачи данных189самостоятельно воспользоваться скриптом, разработанным Ральфом С. Энгелчолом (Ralf S. Engelschall).Создайте файл /usr/share/ssl/misc/sign следующего содержания:#!/bin/sh#### sign.sh -- Sign a SSL Certificate Request (CSR)## Copyright (c) 1998-1999 Ralf S. Engelschall, All Rights Reserved.###argument line handlingCSR=$1if [ $# -ne 1 ]; thenecho "Usage: sign.sign <whatever>.csr"; exit 1fiif [ ! -f $CSR ]; thenecho "CSR not found: $CSR"; exit 1ficase $CSR in*.csr ) CERT="`echo $CSR | sed -e 's/\.csr/.crt/'`" ;;* ) CERT="$CSR.crt" ;;esac#make sure environment existsif [ ! -d ca.db.certs ]; thenmkdir ca.db.certsfiif [ ! -f ca.db.serial ]; thenecho '01' >ca.db.serialfiif [ ! -f ca.db.index ]; thencp /dev/null ca.db.indexfi#create an own SSLeay configcat >ca.config <<EOT[ ca ]default_ca = CA_own[ CA_own ]dir = /usr/share/sslcerts = /usr/share/ssl/certsnew_certs_dir = /usr/share/ssl/ca.db.certsdatabase = /usr/share/ssl/ca.db.indexserial = /usr/share/ssl/ca.db.serialRANDFILE = /usr/share/ssl/ca.db.randcertificate = /usr/share/ssl/certs/ca.crtprivate_key = /usr/share/ssl/private/ca.keydefault_days = 365default_crl_days = 30default_md = md5preserve = nopolicy = policy_anything[ policy_anything ]countryName = optionalstateOrProvinceName = optionallocalityName = optionalorganizationName = optionalorganizationalUnitName = optionalcommonName = suppliedemailAddress = optionalEOT# sign the certificateecho "CA signing: $CSR -> $CERT:"openssl ca -config ca.config -out $CERT -infiles $CSRecho "CA verifying: $CERT <-> CA cert"190Часть 3.
Криптографическое программное обеспечение...openssl verify -CAfile /usr/share/ssl/certs/ca.crt $CERT#rmrmrmcleanup after SSLeay-f ca.config-f ca.db.serial.old-f ca.db.index.old# die gracefullyexit 0Шаг 3Измените права доступа к файлу и назначьте владельцем файла суперпользователя root:[root@dymatel /]# chmod 700 /usr/share/ssl/misc/sign[root@dymatel /]# chown 0.0 /usr/share/ssl/misc/signТестирование OpenSSLДля проверки работоспособности OpenSSL создайте на вашей системе SSL-сертификат Web-сервераApache.
Для создания ключей RSA и запросов на подтверждение подлинности сертификатов (CertificateSigning Requests, CSR) используется утилита /usr/bin/openssl.Шаг 1Выберите пять любых больших файлов со случайным (уникальным) содержанием, скопируйте их вкаталог /usr/share/ssl и переименуйте в random1, random2, random3, random4, random5.Для выбора пяти случайных файлов и размещения их в /usr/share/ssl используйте команды:[root@dymatel /]# cp /var/log/messages /usr/share/ssl/random1[root@dymatel /]# cp /var/log/messages.1 /usr/share/ssl/random2[root@dymatel /]# cp /var/log/messages.2 /usr/share/ssl/random3[root@dymatel /]# cp /var/log/messages.3 /usr/share/ssl/random4[root@dymatel /]# cp /var/log/messages.4 /usr/share/ssl/random5Шаг 2Создайте закрытый ключ RSA для Web-сервера, защищенный паролем:[root@dymatel /]# cd /usr/share/ssl/[root@dymatel ssl]# openssl genrsa -des3 -rand random1:random2:random3:random4:random5 -out www.dymatel.und.key 10241540748 semi-random bytes loadedGenerating RSA private key, 1024 bit long modulus........++++++.................................................++++++e is 65537 (0x10001)Введите пароль для защиты вашего RSA-ключа:Enter pass phrase for www.dymatel.und.key: $ecretn0e_Sl0voПодтвердите пароль:Verifying - Enter pass phrase for www.dymatel.und.key: $ecretn0e_Sl0voЗАМЕЧАНИЕ Обратите внимание, что в качестве имени системы нужно ввести www.dymatel.und, ане dymatel.und.
В противном случае вы не сможете подписать сертификат.Шаг 3Сохраните ключ, содержащийся в файле www.dymatel.und.key, и защищающий его пароль в надежном месте, например, на дискете.Шаг 4Создайте запрос на подтверждение подлинности сертификата:[root@dymatel ssl]# openssl req -new -keywww.dymatel.und.csrwww.dymatel.und.keyВведите пароль, защищающий ключ www.dymatel.und.key:Enter pass phrase for www.dymatel.und.key: $ecretn0e_Sl0vo-outГлава 12.
OpenSSL – программное обеспечение для безопасной передачи данных191You are about to be asked to enter information that will be incorporatedinto your certificate request.What you are about to enter is what is called a Distinguished Name or aDN.There are quite a few fields but you can leave some blankFor some fields there will be a default value,If you enter '.', the field will be left blank.Подтвердите заданные ранее в файле /usr/shared/ssl/openssl.cnf название страны, области,города, организации, Web-сервера, почтового адреса администратора сервера:Country Name (2 letter code) [RU]: <Enter>State or Province Name (full name) [Moscow Region]: <Enter>Locality Name (eg, sity) [Ybileynyi]: <Enter>Organization Name (eg, company) [SIP RIA]: <Enter>Organizational Unit Name (eg, section) []:<Enter>Common Name (eg, YOUR name) [www.dymatel.und]: <Enter>Email Address [root@dymatel.und]: <Enter>Please enter the following 'extra' attributesto be sent with your certificate requestA challenge password []:<Enter>An optional company name []:<Enter>Файл www.dymatel.und.csr, содержащий запрос на подтверждение подлинности сертификата,отправьте в коммерческий сертификационный центр, оплатите его услуги, и через некоторое время вы получите файл www.dymatel.und.crt, который вы сможете использовать для подтверждения подлинностисертификата.Если вы не желаете прибегать к услугам коммерческих сертификационных центров и желаете подписать его самостоятельно, то выполните операции, описанные в шагах 5, 6,7,8 и 9.Шаг 5Создайте закрытый RSA-ключ для своего собственного центра сертификации:[root@dymatel ssl]# openssl genrsa -des3 -out ca.key 1024Generating RSA private key, 1024 bit long modulus............++++++...............++++++e is 65537 (0x10001)Введите пароль, защищающий ключ:Enter pass phrase for ca.key: $ecretnoe_Slov0Подтвердите пароль:Verifying - Enter pass phrase for ca.key: $ecretnoe_Slov0Шаг 6Сохраните ключ и защищающий его пароль в надежном месте, например на дискете.Шаг 7Создайте и подпишите для ключа ca.key сертификат:[root@dymatel ssl]# openssl req -new -x509 -days 365 -key ca.key -outca.crtEnter pass phrase for ca.key:You are about to be asked to enter information that will be incorporatedinto your certificate request.What you are about to enter is what is called a Distinguished Name or aDN.There are quite a few fields but you can leave some blankFor some fields there will be a default value,If you enter '.', the field will be left blank.Введите название страны, области, города, организации, Web-сервера, почтового адреса администратора сервера:Country Name (2 letter code) [RU]:<Enter>State or Province Name (full name) [Moscow Region]: <Enter>192Часть 3.