X.509 certificate spurs

    The monster shook, mischievously, enormously, harshly and barking .

    The set of technologies, which we habitually call SSL certificates, is a hefty iceberg, on top of which there is a green lock to the left of the domain name in the address bar of your browser. The correct name X.509 сертификат, which goes back to X.500the ITU-T standard DAP (Directory Access Protocol). DAP did not take off, at the IETF it was considered inconvenient for use with all these OSI piles, and instead it came up with LDAP, Lightweight DAP where the first letter means "lightweight". Those who had to tune, or worse to debug it, can fully appreciate the irony. Never before has the first letter of the abbreviation so lied, apart from SNMP.


    Spurs


    By the way, what do LDAP, SNMP and X.509 have in common, well, besides the fact that they will not have to assemble fan stadiums soon? They are united by ASN.1 - a meta-language for describing objects of antiquity. If these technologies were created now, XML, DTD or some other ML would be used. But at that time, standards were created by titans, for which even SNMP was a simple affair.


    Vocabulary


    Definition of X.509 certificates is in the ITU-T archive


    Certificate  ::=  SEQUENCE  {
         tbsCertificate       TBSCertificate,
         signatureAlgorithm   AlgorithmIdentifier,
         signatureValue       BIT STRING  }
    TBSCertificate  ::=  SEQUENCE  {
         version         [0]  EXPLICIT Version DEFAULT v1,
         serialNumber         CertificateSerialNumber,
         signature            AlgorithmIdentifier,
         issuer               Name,
         validity             Validity,
         subject              Name,
         subjectPublicKeyInfo SubjectPublicKeyInfo,
         issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
                              -- If present, version MUST be v2 or v3

    In order to thoroughly understand the notation and syntax, you will have to read the X.680 specs of the 2008 edition , where there is a full description of ASN.1 . In terms of ASN.1SEQUENCE means roughly the same as structin C. This can be confusing, because by semantics it should have corresponded more likely to an array. And yet.


    The X.690 standard defines the following encoding rules for data structures created in accordance with ASN.1 : BER(Basic Encoding Rules), CER(Canonical Encoding Rules), DER(Distinguished Encoding Rules). There is even XER(XML Encoding Rules), which in practice I have never met.


    Yes, but why do you need X.509 certificates that deliver so much headache? The first and main function of X.509 certificates is to serve as a repository of a public or public key PKI (public key infrastructure). There are no complaints about this function, but not everything is so clear with the second one.


    The second function of X.509 certificates is for the bearer to be accepted by a person or a program as the true owner of a digital asset: a domain name, a website, etc. This is done differently, not all certificates have high liquidity if use financial terminology. Six months ago, Google threatened Simantec companies that it would cease to trust their certificates due to the fact that they issued as many as 30,000 failed certificates.


    Certificate Nomenclature


    Let's look at what X.509 certificates are found in nature, if we consider them by location in food chain of trust.


    • Root certificates - are made in the root CA (certification authority) and have the following characteristics: attributes issueand subjectidentical, and in the extension basicConstraintsattribute cAis set to TRUE.
    • Intermediate certificates - a vague term for certificates that are not signed by the root CA, which can form a chain of arbitrary length, starting from the root certificate and ending with the certificate of the final subject .
    • End-entity certificates are end -level certificates in a chain that cannot sign other intermediate certificates with their private key.

    By degree steepnesshigh cost and reliability certificates are divided into 3 types: DV , OV and EV .


    • DV - domain name certificate certificates are easy to obtain. They are issued automatically and instantly after the certification authority verifies that the applicant has the right to a domain name. Most often, just open the message and follow the link. Naturally, the message will be sent to the mailbox with the domain name, which should be certified.
    • OV - the certificate will already indicate not the domain name, but the name of the applicant organization itself. There is no longer any automatic speech output, it will take several business days. The subject of verification is the presence in the whoisdomain database of the name of the applicant organization. They can check the state registration and validity of the phone number.
    • EV - it is difficult to obtain these certificates and they are not cheap. They can be identified by the name of the organization on a green lock in the address bar panel.

      EV certificate

    It’s rare who is willing to fork out for it. Offhand, Yandex, StackOverflow.com and Habr can live without it. But those who are willing to make sacrifices for this must fulfill the following requirements:


    1. Audit of legal, physical and operational activities of the organization.
    2. Make sure that the organization has the exclusive right to use the domain name.
    3. Make sure that the organization is authorized to issue this type of certificate.

    More details can be found in TutHost's Habraposp . Also attribute subjectX.509 EV certificate contains values jurisdictionOfIncorporationCountryName, businessCategoryand serialNumber.


    By their properties, certificates are of the following types.


    • Multi-domain certificates - A certificate can span multiple domain names using the SAN- attribute subjectAltName.
    • Multi-host certificates - in cases where the attribute subjectcontains an entry CN=example.net, while the DNS server can have several records of the A / AAAAtype where one host name can correspond to several IP addresses. In this case, an X.509 certificate with the same certificate hostnamecan be successfully restored on all such nodes.
    • Wildcard certificates, wildcard certificates - this is when an attribute subjectcontains an entry CN=*.example.net. It acts the same as in the usual regular expressions, that is, it can be used on all sub-domains *.example.net.
    • Qualified Certificates - RFC 3739 defines this term as referring to personal certificates, referring to the European Union Electronic Signature Directive . In particular, the RFC allows the attribute to subjectcontain values:
      • commonName (CN =),
      • givenName (GN =),
      • pseudonym =.

        Also subjectDirectoryAttributesincludes values:
      • dateOfBirth =,
      • placeOfBirth =,
      • gender =,
      • countryOfCitizenship =,
      • countryOfResidence =.

    In Russia, the concept of a COP of a qualified certificate is defined by law in connection with access to State Services. According to the link with the epic Habrapost about the extraction of personal data from the COP.


    Where do the certificates come from?


    More recently, there were only 2 ways to get an X.509 certificate, but times are changing and recently there is a third way.


    1. Create your own certificate and sign it yourself. Pros - it's free, cons - the certificate will be accepted only by you and, at best, your organization.

      not trusted
    2. Purchase a certificate from a CA It will cost money depending on its various characteristics and capabilities indicated above.
    3. Get a free LetsEncrypt certificate , only the simplest DV certificates are available.

    For the first scenario, a couple of commands are enough and in order not to get up 2 times, we will create a certificate with an elliptic curve algorithm . The first step is to create a private key. It is believed that encryption with the elliptic curve algorithm gives a greater exhaust , if measured in CPU cycles, or bytes of key length. ECC support is not uniquely defined in TLS <1.2.


    openssl ecparam -name secp521r1 -genkey -param_enc explicit -out private-key.pem

    Next, it creates a CSR - certificate signing request.


    openssl req -new -sha256 -key private.key -out server.csr -days 730

    And we sign.


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

    The result can be viewed with the command:


    openssl x509 -text -noout -in public.crt

    Opensslhas a huge number of options and commands. The Man page is not very useful, the manual is more convenient to use like this:


    openssl -help
    openssl x509 -help
    openssl s_client -help

    Exactly the same thing can be done using the javautility keytool.


    keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048

    A series of questions follows so that there is something to remember the fields ownerandissuer


    What is your first and last name?
    What is the name of your organizational unit?
    What is the name of your organization?
    What is the name of your City or Locality?
    What is the name of your State or Province?
    What is the two-letter country code for this unit?
    Is CN=Johnnie Walker, OU=Unknown, O=Unknown, L=Moscow, ST=Moscow, C=RU correct?

    Convert the keychain from the proprietary format to PKCS12.


    keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.jks -deststoretype pkcs12

    We look at the result:


    keytool -list -v -alias selfsigned -storepass password -keystore keystore.jks
    Alias name: selfsigned
    Creation date: 20.01.2018
    Entry type: PrivateKeyEntry
    Certificate chain length: 1
    Certificate[1]:
    Owner: CN=Johnnie Walker, OU=Unknown, O=Unknown, L=Moscow, ST=Moscow, C=RU
    Issuer: CN=Johnnie Walker, OU=Unknown, O=Unknown, L=Moscow, ST=Moscow, C=RU
    Serial number: 1f170cb9
    Valid from: Sat Jan 20 18:33:42 MSK 2018 until: Tue Jan 15 18:33:42 MSK 2019
    Certificate fingerprints:
         MD5:  B3:E9:92:87:13:71:2D:36:60:AD:B5:1F:24:16:51:05
         SHA1: 26:08:39:19:31:53:C5:43:1E:ED:2E:78:36:43:54:9B:EA:D4:EF:9A
         SHA256: FD:42:C9:6D:F6:2A:F1:A3:BC:24:EA:34:DC:12:02:69:86:39:F1:FC:1B:64:07:FD:E1:02:57:64:D1:55:02:3D
    Signature algorithm name: SHA256withRSA
    Subject Public Key Algorithm: 2048-bit RSA key
    Version: 3
    Extensions:
    #1: ObjectId: 2.5.29.14 Criticality=false
    SubjectKeyIdentifier [
    KeyIdentifier [
    0000: 30 95 58 E3 9E 76 1D FB   92 44 9D 95 47 94 E4 97  0.X..v...D..G...
    0010: C8 1E F1 92                                        ....
    ]
    ]

    The value ObjectId: 2.5.29.14corresponds to the definition of ASN.1, according to RFC 3280 it is always non-critical. In the same way, you can find out the meaning and possible meanings of others ObjectIdthat are present in the X.509 certificate.


    subjectKeyIdentifier EXTENSION ::= {
        SYNTAX SubjectKeyIdentifier
        IDENTIFIED BY id-ce-subjectKeyIdentifier
    }
    SubjectKeyIdentifier ::= KeyIdentifier

    Letsencrypt


    You can get the X.509 LetsEncrypt certificate for free and you don’t even need to go to the website, just install it certbot.


    sudo emerge -av certbot #для Gentoo
    sudo apt-get install certbot -t stretch-backports #Debian
    sudo dnf install certbot #Fedora
    sudo certbot certonly --standalone -d example.com -d www.example.com

    Scenario # 1 - find the next one in a bunch


    Certificate Bundle - Combine multiple X.509 certificates into a single file, most often in a format PEM. The bundle is transmitted over the network at the time of the SSL / TLS handshake protocol.


    Trust chain


    Самый сок начинается, когда имеете дело со связкой сертификатов, a. k. a certificate chain. Часто просматривая лапшу в связке ключей jks непросто понять как найти родительский сертификат, когда там россыпь новых и старых сертификатов на несколько доменных имен.


    Рассмотрим связку сертификатов *.novell.com. Расширение Authority Key Identifier (AKI) должно совпадать с Subject Key Identifier (SKI) старшего в связке.


    Certificate Authority Key Identifier
    Size: 20 Bytes / 160 Bits
    51 68 ff 90 af 02 07 75 3c cc d9 65 64 62 a2 12 b8 59 72 3b

    Так и есть, SKI сертификат DigiCert имеет то же значение.


    Certificate Subject Key ID
    Size: 20 Bytes / 160 Bits
    51 68 ff 90 af 02 07 75 3c cc d9 65 64 62 a2 12 b8 59 72 3b

    Novell cert chain


    Для корневого сертификата AKI = SKI, а также isCa=true


    Certificate Basic Constraints
    Critical
    Is a Certificate Authority

    Сценарий №2 — используй subjectAltnName, Люк


    Вот представьте у вас приложение, использующее веб сервер: вики, WordPress или Cacti. Вы настроили доступ по https, приобрели или сами сгенерировали и подписали сертификат. Все должно быть в порядке, но зеленого замочка все равно нет. Браузер подозревает, что сертификат готовили неправильные пчелы, из-за того, что FQDN сервера и hostname, который указан в адресной строке не совпадают. Так иногда бывает, что DNS сервера указывает на mars.domain.com, а веб-сервер настроен на venus.domain.com.


    Если администратору в силу перфекционизма нужны помимо езды нужны еще и шашечки — вожделенный зеленый замочек, то нужно переделать сертификат X.509, определив в нем subjectAltName.


    Откройте файл openssl.cnf и в секции req добавьте следующие линии.


    [ alternate_names ]
    DNS.1        = example.com
    DNS.2        = www.example.com
    DNS.3        = mail.example.com
    DNS.4        = ftp.example.com

    Далее, в секции [ v3_ca ] укажите.


    subjectAltName      = @alternate_names

    And then everything is as usual, create a private key and sign a certificate.


    openssl genrsa -out private.key 3072
    openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730

    Used materials



    Also popular now: