博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
X509 证书详解
阅读量:2342 次
发布时间:2019-05-10

本文共 69177 字,大约阅读时间需要 230 分钟。

X.509 Certificates

1) Certificates

In the X.509 system, an organization that want to a signed certificate requests one via a certificate signing request

To do this , it first generates a key pair, keeping the private key secret adn using it to sign the CSR. This contains information indentifying the application and the applicant’s public key that is used to verfiy the signature of the CSR - and the Distiguished Name (DN) that the certificate is for. The CSR may be accompanied by other credentials or proofs of identity required by the certificate authority.

The certificate authority issues a certificate binding a public key to particular distinguished name.

An organization’s trusted root certificates can be distributed to all employees so that they can use the company PKI system. Browsers such as internet Explorer, FireFox, Safari and Chrome come with a predetermined set of root certificates pre-installed, so SSL certificates from major certificate autorities will work instantly; in effort the browsers’ developers detemine which CAs are trusted third parties for the browsers’ users. For example, FireFox provides a CSV and/or HTML file containing a list of include CAs.

X.509 also includes standards for certificate revocation list (CRL) implementations, an often neglected aspect of PKI system. The IETF-approved way of checking a certificates’s validity is the Online Certficate Status Protocol (OCSP). Firefox 3 enables OCSP checking by default, as do versions of Windows from at least Vista and later

1-1) Structure of a Certificate

The structure foreseen by the standards is expressed in a formal language Abstract Syntax Notation One.

The structure of an X.509 v3 digital certificate is as follows:

  • Certificate
    • Version Number
    • Serial Number
    • Signature Algorithm ID
    • Issuer Name
    • Validity period
      • Not before
      • Not after
    • Subject Name
    • Subject pbulic Key Info
      • Public Key Algorithm
      • Subject Public Key
    • Issuer Unique Identifier (optional)
    • Subject Unique Identifier (optional)
    • Extensions (optional)
  • Certificate Sigature Algorithm
  • Certificate Signature

1-2) Extensions informing a specific usage of a certficate

RFC 5280 (and its predecessors) defines a number certificates extensions which indicate how the certificate should be used. Most of them arcs from the joint-iso-ccitt(2) ds(5) id-ce(29) OID. Some of the most common, defined in section 4.2.1 are:

  • Basic Constraints, {id-ce 19}, are used to indicate whether the certificate belongs to a CA.
  • Key Usage, {id-ce 15}, provides a specifying the cryptograhic operations which may be performed using the public key contained in the certificate; for example, it could indicate that the key should be used for signatures but not for encipherment.
  • Extended Key Usage, {id-ce 37}, is used, typically on a leaf certificate, to indicate the purpose of the public key contained in the certificate. It contains a list of OIDs, each of which indicates an allowed use. For example, {id-pkix 31} indicates that the key may be used on the server end of a TLS or SSL connection; {id-pkix 34} indicates that the key may be used to secure email.

In general, if a certificate has several extensions restricting its use, all restrictions must be statified for a given use to be appropriate.

1-3) Certificate filename extensions

There are several commonly used filename extensions for X.509 certificates. Unfortunately, some of these extensions are also used for other data such as private keys.

  • .pem - (Privacy-enhanced Electronic Mail) Base64 encoded DER certificate, enclosed between “—–BEGIN CERTIFICATE—–” and “—–END CERTIFICATE—–”
  • .cer, .crt, .der - usually in binary DER form, but Base64-enclosed certificates are common too
  • .p7b, .p7c - PKC#7 SignedData structure without data, just certificate(s) or CRL(s)
  • .p12 - PKCS#12, may contain certificate(s)(public) and private keys (password protected)
  • .pfx -PFX, predecessor of PKCS#12 (usually contains data in PKCS#12 format, e.g, with PFX fiels generated in IIS)

PKCS#7 is a standard for signing or encripting (officially called “envoloping”)data. Since the certificate is needed to verify signed data, it is possible to include them in the SignedData struture. A .p7c file is a degenerated SignedData struture, without any data to sign.

PKCS#12 evolved from the personal information exchange (PFX) standard and is used to exchange public and private objects in a single file.

2) Certificate chains and cross-certification

A cetificate chain (see the equivalent concept of “certification path” defined by RFC 5280) is a list of certificates (usually starting with an end-entity certificate) followed by one or more CA certificates (usually the last one being a self-signed certificate), with the following properties:

  1. The Issuer of each certificate (except the last one) matches the Subject of the next certificate in the list.
  2. Each certificate (except the last one) is supposed to be signed by the secret key corresponding to the next certificate in the chain (i.e the signature of one certificate can be verifed using the public key contained in the following certificate).
  3. The last certificate in the list is a trust anchor: a certificate that you trust because it was delivered to you by some trustworthy procedure.

Certificate chains are used in order to check that the public key (PK) contained in a target certificate (the first certificate in the chain) and other data contained in it effectively belongs to its subject. In order to ascertain this, the signature on the target certificate is verified by using the PK contained in the following certificate, whose signature is verified using the next certificate, and so on until the last certificate in the chain is reached. As the last certificate is a trust anchor, successfully reaching it will prove that the target certificate can be trusted.

The description in the preceding paragraph is a simplified view on the certification path validation process as defined by RFC 5280,[10] which involves additional checks, such as verifying validity dates on certificates, looking up CRLs, etc.

Example 1: Cross-certification between two PKIs

Example 2: CA certificate renewal

Examining how certificate chains are built and validated, it is important to note that a concrete certificate can be part of very different certificate chains (all of them valid). This is because several CA certificates can be generated for the same subject and public key signing them with different private keys (from different CAs or different private keys from the same CA). So, although a single X.509 certificate can have only one issuer and one CA signature, it can be validly linked to more than one certificate building completely different certificate chains. This is crucial for cross-certification between PKIs and other applications. [11] See the following examples.

In these diagrams:

Each box represents a certificate, with its Subject in bold.

A → B means “A is signed by B” (or, more precisely, “A is signed by the secret key corresponding to the public key contained in B”).
Certificates with the same color (that are not white/transparent) contain the same public key.

2-1) Example 1: Cross-certification at root Certification Authority (CA) level between two PKIs

Example 1: Cross-certification at root Certification Authority (CA) level between two PKIs[edit source]

In order to manage that user certificates existing in PKI 2 (like “User 2”) are trusted by PKI 1, CA1 generates a certificate (cert2.1) containing the public key of CA2. [12] Now both “cert2 and cert2.1 (in green) have the same subject and public key, so there are two valid chains for cert2.2 (User 2): “cert2.2 → cert2” and “cert2.2 → cert2.1 → cert1”.

Similarly, CA2 can generate a certificate (cert1.1) containing the public key of CA1 so that user certificates existing in PKI 1 (like “User 1”) are trusted by PKI 2.

Example 1: Cross-certification between two PKIs

2-2) Example 2: CA certificate renewal

Understanding Certification Path Construction (PDF). PKI Forum. September 2002. To allow for graceful transition from the old signing key pair to the new signing key pair, the CA should issue a certificate that contains the old public key signed by the new private signing key and a certificate that contains the new public key signed by the old private signing key. Both of these certificates are self-issued, but neither is self-signed. Note that these are in addition to the two self-signed certificates (one old, one new).

Since both cert1 and cert3 contain the same public key (the old one), there are two valid certificate chains for cert5: “cert5 → cert1” and “cert5 → cert3 → cert2”, and analogously for cert6. This allows that old user certificates (such as cert5) and new certificates (such as cert6) can be trusted indifferently by a party having either the new root CA certificate or the old one as trust anchor during the transition to the new CA keys.[13]

Example 2: CA certificate renewal

3) Sample X.509 certificates

This is an example of a decoded X.509 certificate for wikipedia.org and several other Wikipedia websites. It was issued by GlobalSign, as stated in the Issuer field. Its Subject field describes Wikipedia as an organization, and its Subject Alternative Name field describes the hostnames for which it can be used. The Subject Public Key Info field contains an ECDSA public key, while the signature at the bottom is generated by GlobalSign’s RSA private key.

3-1) End-entity certificate

Certificate:    Data:        Version: 3 (0x2)        Serial Number:            10:e6:fc:62:b7:41:8a:d5:00:5e:45:b6    Signature Algorithm: sha256WithRSAEncryption        Issuer: C=BE, O=GlobalSign nv-sa, CN=GlobalSign Organization Validation CA - SHA256 - G2        Validity            Not Before: Nov 21 08:00:00 2016 GMT            Not After : Nov 22 07:59:59 2017 GMT        Subject: C=US, ST=California, L=San Francisco, O=Wikimedia Foundation, Inc., CN=*.wikipedia.org        Subject Public Key Info:            Public Key Algorithm: id-ecPublicKey                Public-Key: (256 bit)                pub:                     04:c9:22:69:31:8a:d6:6c:ea:da:c3:7f:2c:ac:a5:                    af:c0:02:ea:81:cb:65:b9:fd:0c:6d:46:5b:c9:1e:                    ed:b2:ac:2a:1b:4a:ec:80:7b:e7:1a:51:e0:df:f7:                    c7:4a:20:7b:91:4b:20:07:21:ce:cf:68:65:8c:c6:                    9d:3b:ef:d5:c1                ASN1 OID: prime256v1                NIST CURVE: P-256        X509v3 extensions:            X509v3 Key Usage: critical                Digital Signature, Key Agreement            Authority Information Access:                 CA Issuers - URI:http://secure.globalsign.com/cacert/gsorganizationvalsha2g2r1.crt                OCSP - URI:http://ocsp2.globalsign.com/gsorganizationvalsha2g2            X509v3 Certificate Policies:                 Policy: 1.3.6.1.4.1.4146.1.20                  CPS: https://www.globalsign.com/repository/                Policy: 2.23.140.1.2.2            X509v3 Basic Constraints:                 CA:FALSE            X509v3 CRL Distribution Points:                 Full Name:                  URI:http://crl.globalsign.com/gs/gsorganizationvalsha2g2.crl            X509v3 Subject Alternative Name:                 DNS:*.wikipedia.org, DNS:*.m.mediawiki.org, DNS:*.m.wikibooks.org, DNS:*.m.wikidata.org, DNS:*.m.wikimedia.org, DNS:*.m.wikimediafoundation.org, DNS:*.m.wikinews.org, DNS:*.m.wikipedia.org, DNS:*.m.wikiquote.org, DNS:*.m.wikisource.org, DNS:*.m.wikiversity.org, DNS:*.m.wikivoyage.org, DNS:*.m.wiktionary.org, DNS:*.mediawiki.org, DNS:*.planet.wikimedia.org, DNS:*.wikibooks.org, DNS:*.wikidata.org, DNS:*.wikimedia.org, DNS:*.wikimediafoundation.org, DNS:*.wikinews.org, DNS:*.wikiquote.org, DNS:*.wikisource.org, DNS:*.wikiversity.org, DNS:*.wikivoyage.org, DNS:*.wiktionary.org, DNS:*.wmfusercontent.org, DNS:*.zero.wikipedia.org, DNS:mediawiki.org, DNS:w.wiki, DNS:wikibooks.org, DNS:wikidata.org, DNS:wikimedia.org, DNS:wikimediafoundation.org, DNS:wikinews.org, DNS:wikiquote.org, DNS:wikisource.org, DNS:wikiversity.org, DNS:wikivoyage.org, DNS:wiktionary.org, DNS:wmfusercontent.org, DNS:wikipedia.org            X509v3 Extended Key Usage:                 TLS Web Server Authentication, TLS Web Client Authentication            X509v3 Subject Key Identifier:                 28:2A:26:2A:57:8B:3B:CE:B4:D6:AB:54:EF:D7:38:21:2C:49:5C:36            X509v3 Authority Key Identifier:                 keyid:96:DE:61:F1:BD:1C:16:29:53:1C:C0:CC:7D:3B:83:00:40:E6:1A:7C    Signature Algorithm: sha256WithRSAEncryption         8b:c3:ed:d1:9d:39:6f:af:40:72:bd:1e:18:5e:30:54:23:35:         ...

To validate this end-entity certificate, one needs an intermediate certificate that matches its Issuer and Authority Key Identifier:

  • Issuer C=BE, O=GlobalSign nv-sa, CN=GlobalSign Organization Validation CA - SHA256 - G2
  • Authority Key Identifier 96:DE:61:F1:BD:1C:16:29:53:1C:C0:CC:7D:3B:83:00:40:E6:1A:7C

In a TLS connection, a properly-configured server would provide the intermediate as part of the handshake. However, it’s also possible to retrieve the intermediate certificate by fetching the “CA Issuers” URL from the end-entity certificate.

3-2) Intermediate certificate

his is an example of an intermediate certificate belonging to a certificate authority. This certificate signed the end-entity certificate above, and was signed by the root certificate below. Note that the subject field of this intermediate certificate matches the issuer field of the end-entity certificate that it signed. Also, the “subject key identifier” field in the intermediate matches the “authority key identifier” field in the subject.

Certificate:    Data:        Version: 3 (0x2)        Serial Number:            04:00:00:00:00:01:44:4e:f0:42:47    Signature Algorithm: sha256WithRSAEncryption        Issuer: C=BE, O=GlobalSign nv-sa, OU=Root CA, CN=GlobalSign Root CA        Validity            Not Before: Feb 20 10:00:00 2014 GMT            Not After : Feb 20 10:00:00 2024 GMT        Subject: C=BE, O=GlobalSign nv-sa, CN=GlobalSign Organization Validation CA - SHA256 - G2        Subject Public Key Info:            Public Key Algorithm: rsaEncryption                Public-Key: (2048 bit)                Modulus:                    00:c7:0e:6c:3f:23:93:7f:cc:70:a5:9d:20:c3:0e:                    ...                Exponent: 65537 (0x10001)        X509v3 extensions:            X509v3 Key Usage: critical                Certificate Sign, CRL Sign            X509v3 Basic Constraints: critical                CA:TRUE, pathlen:0            X509v3 Subject Key Identifier:                96:DE:61:F1:BD:1C:16:29:53:1C:C0:CC:7D:3B:83:00:40:E6:1A:7C            X509v3 Certificate Policies:                Policy: X509v3 Any Policy                  CPS: https://www.globalsign.com/repository/            X509v3 CRL Distribution Points:                Full Name:                  URI:http://crl.globalsign.net/root.crl            Authority Information Access:                OCSP - URI:http://ocsp.globalsign.com/rootr1            X509v3 Authority Key Identifier:                keyid:60:7B:66:1A:45:0D:97:CA:89:50:2F:7D:04:CD:34:A8:FF:FC:FD:4B    Signature Algorithm: sha256WithRSAEncryption         46:2a:ee:5e:bd:ae:01:60:37:31:11:86:71:74:b6:46:49:c8:         ...

3-3) Root certificate

This is an example of a self-signed root certificate representing a certificate authority. Its issuer and subject fields are the same, and its signature can be validated with its own public key. Validation of the trust chain has to end here. If the validating program has this root certificate in its trust store, the end-entity certificate can be considered trusted for use in a TLS connection. Otherwise, the end-entity certificate is considered untrusted.

Certificate:    Data:        Version: 3 (0x2)        Serial Number:            04:00:00:00:00:01:15:4b:5a:c3:94    Signature Algorithm: sha1WithRSAEncryption        Issuer: C=BE, O=GlobalSign nv-sa, OU=Root CA, CN=GlobalSign Root CA        Validity            Not Before: Sep  1 12:00:00 1998 GMT            Not After : Jan 28 12:00:00 2028 GMT        Subject: C=BE, O=GlobalSign nv-sa, OU=Root CA, CN=GlobalSign Root CA        Subject Public Key Info:            Public Key Algorithm: rsaEncryption                Public-Key: (2048 bit)                Modulus:                    00:da:0e:e6:99:8d:ce:a3:e3:4f:8a:7e:fb:f1:8b:                    ...                Exponent: 65537 (0x10001)        X509v3 extensions:            X509v3 Key Usage: critical                Certificate Sign, CRL Sign            X509v3 Basic Constraints: critical                CA:TRUE            X509v3 Subject Key Identifier:                 60:7B:66:1A:45:0D:97:CA:89:50:2F:7D:04:CD:34:A8:FF:FC:FD:4B    Signature Algorithm: sha1WithRSAEncryption         d6:73:e7:7c:4f:76:d0:8d:bf:ec:ba:a2:be:34:c5:28:32:b5:         ...

4) Security

There are a number of publications about PKI problems by Bruce Schneier, Peter Gutmann and other security experts.

4-1) Architectural weaknesses

  • Use of blacklisting invalid certificates (using CRLs and OCSP),
    • If the client only trusts certificates when CRLs are available, then they lose the offline capability that makes PKI attractive. So most clients do trust certificates when CRLs are not available, but in that case an attacker that controls the communication channel can disable the CRLs. Adam Langley of Google has said soft-fail CRL checks are like a safety belt that works except when you are having an accident.[17]
  • CRLs are notably a poor choice because of large sizes and convoluted distribution patterns,
  • Ambiguous OCSP semantics and lack of historical revocation status,
  • Revocation of root certificates is not addressed,
  • Aggregation problem: Identity claims (authenticate with an identifier), attribute claims (submit a bag of vetted attributes), and policy claims are combined in a single container. This raises privacy, policy mapping, and maintenance issues,
  • Delegation problem: CAs cannot technically restrict subordinate CAs from issuing certificates outside a limited namespaces or attribute set; this feature of X.509 is not in use. Therefore, a large number of CAs exist on the Internet, and classifying them and their policies is an insurmountable task. Delegation of authority within an organization cannot be handled at all, as in common business practice.
  • Federation problem: Certificate chains that are the result of subordinate CAs, bridge CAs, and cross-signing make validation complex and expensive in terms of processing time. Path validation semantics may be ambiguous. The hierarchy with a third-party trusted party is the only model. This is inconvenient when a bilateral trust relationship is already in place.
  • Issuance of an Extended Validation (EV) certificate for a hostname doesn’t prevent issuance of a lower-validation certificate valid for the same hostname, which means that the higher validation level of EV doesn’t protect against man-in-the-middle attacks.[18]

4-2) Problems with certificate authorities

  • The subject, not the relying party, purchases certificates. The subject will often utilize the cheapest issuer, so quality is not being paid for in the competing market. This is partly addressed by Extended Validation certificates.
  • Certification authorities deny almost all warranties to the user (including subject or even relying parties).
  • The expiration date should be used to limit the time the key strength is deemed sufficient. This parameter is abused by certification authorities to charge the client an extension fee. This places an unnecessary burden on the user with key roll-over.
  • “Users use an undefined certification request protocol to obtain a certificate which is published in an unclear location in a nonexistent directory with no real means to revoke it.” [16]
  • Like all businesses, CAs are subject to the legal jurisdiction(s) of their site(s) of operation, and may be legally compelled to compromise the interests of their customers and their users. Intelligence agencies have also made use of false certificates issued through extralegal compromise of CAs, such as DigiNotar, to carry out man-in-the-middle attacks.[citation needed] Another example is a revocation request of the CA of the Dutch government, because of a new Dutch law becoming active starting January 1, 2018, giving new powers for the Dutch intelligence and security services.[19]

4-3) Implementation issues

Implementations suffer from design flaws, bugs, different interpretations of standards and lack of interoperability of different standards. Some problems are:[citation needed]

  • Many implementations turn off revocation check:
    • Seen as obstacle, policies are not enforced
    • If it was turned on in all browsers by default, including code signing, it would probably crash the infrastructure[citation needed].
  • DNs are complex and little understood (lack of canonicalization, internationalization problems, ..)
  • rfc822Name has two notations
  • Name and policy constraints hardly supported
  • Key usage ignored, first certificate in a list being used
  • Enforcement of custom OIDs is difficult
  • Attributes should not be made critical because it makes clients crash.
  • Unspecified length of attributes lead to product-specific limits
  • There are implementation errors with X.509 that allow e.g. falsified subject names using null-terminated strings[20] or code injection attacks in certificates.
  • By using illegal[21] 0x80 padded subidentifiers of object identifiers, wrong implementations or by using integer overflows of the client’s browsers, an attacker can include an unknown attribute in the CSR, which the CA will sign, which the client wrongly interprets as “CN” (OID=2.5.4.3). Dan Kaminsky at the 26th Chaos Communication Congress “Black OPs of PKI”[22]

4-4) Cryptographic weaknesses

Digital signature systems depend on secure cryptographic hash functions to work. When a public key infrastructure allows the use of a hash function that is no longer secure, an attacker can exploit weaknesses in the hash function to forge certificates. Specifically, if an attacker is able to produce a hash collision, they can convince a CA to sign a certificate with innocuous contents, where the hash of those contents is identical to the hash of another, malicious set of certificate contents, created by the attacker with values of their choosing. The attacker can then append the CA-provided signature to their malicious certificate contents, resulting in a malicious certificate that appears to be signed by the CA. Because the malicious certificate contents are chosen solely by the attacker, they can have different validity dates or hostnames than the innocuous certificate. The malicious certificate can even contain a “CA: true” field making it able to issue further trusted certificates.

  • MD2-based certificates were used for a long time and were vulnerable to preimage attacks. Since the root certificate already had a self-signature, attackers could use this signature and use it for an intermediate certificate.
  • In 2005, Arjen Lenstra and Benne de Weger demonstrated “how to use hash collisions to construct two X.509 certificates that contain identical signatures and that differ only in the public keys”, achieved using a collision attack on the MD5 hash function.[23]
  • In 2008, Alexander Sotirov and Marc Stevens presented at the Chaos Communication Congress a practical attack that allowed them to create a rogue Certificate Authority, accepted by all common browsers, by exploiting the fact that RapidSSL was still issuing X.509 certificates based on MD5.[24]
  • In April 2009 at the Eurocrypt Conference,[25] Australian Researchers of Macquarie University presented “Automatic Differential Path Searching for SHA-1”.[26] The researchers were able to deduce a method which increases the likelihood of a collision by several orders of magnitude.[27]
  • In February 2017, a group of researchers produced a SHA-1 collision, demonstrating SHA-1’s weakness.

4-4-1) Mitigations for cryptographic weaknesses

Exploiting a hash collision to forge X.509 signatures requires that the attacker be able to predict the data that the certificate authority will sign. This can be somewhat mitigated by the CA generating a random component in the certificates it signs, typically the serial number. The CA/Browser Forum has required serial number entropy in its Baseline Requirements Section 7.1 since 2011.[29]

As of January 1, 2016, the Baseline Requirements forbid issuance of certificates using SHA-1. As of early 2017, Chrome[30] and Firefox[31] reject certificates that use SHA-1. As of May 2017 both Edge[32] and Safari [33] are also rejecting SHA-1 certificate. Non-browser X.509 validators do not yet reject SHA-1 certificates.[34]

5) PKCS Standards Summary

In cryptography, PKCS stands for “Public Key Cryptography Standards”. These are a group of public-key cryptography standards devised and published by RSA Security Inc, starting in the early 1990s. The company published the standards to promote the use of the cryptography techniques to which they had patents, such as the RSA algorithm, the Schnorr signature algorithm and several others. Though not industry standards (because the company retained control over them), some of the standards in recent years[when?] have begun to move into the “standards-track” processes of relevant standards organizations such as the IETF and the PKIX working-group.

  • PKCS #1 2.2 RSA Cryptography Standard[1] See RFC 8017. Defines the mathematical properties and format of RSA public and private keys (ASN.1-encoded in clear-text), and the basic algorithms and encoding/padding schemes for performing RSA encryption, decryption, and producing and verifying signatures.

  • PKCS #2 - Withdrawn No longer active as of 2010. Covered RSA encryption of message digests; subsequently merged into PKCS #1.

  • PKCS #3 1.4 Diffie–Hellman Key Agreement Standard[2] A cryptographic protocol that allows two parties that have no prior knowledge of each other to jointly establish a shared secret key over an insecure communications channel.

  • PKCS #4 - Withdrawn No longer active as of 2010. Covered RSA key syntax; subsequently merged into PKCS #1.

  • PKCS #5 2.1 Password-based Encryption Standard[3] See RFC 8018 and PBKDF2.

  • PKCS #6 1.5 Extended-Certificate Syntax Standard[4] Defines extensions to the old v1 X.509 certificate specification. Obsoleted by v3 of the same.

  • PKCS #7 1.5 Cryptographic Message Syntax Standard[5] See RFC 2315. Used to sign and/or encrypt messages under a PKI. Used also for certificate dissemination (for instance as a response to a PKCS #10 message). Formed the basis for S/MIME, which is as of 2010 based on RFC 5652, an updated Cryptographic Message Syntax Standard (CMS). Often used for single sign-on.

  • PKCS #8 1.2 Private-Key Information Syntax Standard[6] See RFC 5958. Used to carry private certificate keypairs (encrypted or unencrypted).

  • PKCS #9 2.0 Selected Attribute Types[7] See RFC 2985. Defines selected attribute types for use in PKCS #6 extended certificates, PKCS #7 digitally signed messages, PKCS #8 private-key information, and PKCS #10 certificate-signing requests.

  • PKCS #10 1.7 Certification Request Standard[8] See RFC 2986. Format of messages sent to a certification authority to request certification of a public key. See certificate signing request.

  • PKCS #11 2.40 Cryptographic Token Interface[9] Also known as “Cryptoki”. An API defining a generic interface to cryptographic tokens (see also hardware security module). Often used in single sign-on, public-key cryptography and disk encryption[10] systems. RSA Security has turned over further development of the PKCS #11 standard to the OASIS PKCS 11 Technical Committee.

  • PKCS #12 1.1 Personal Information Exchange Syntax Standard[11] See RFC 7292. Defines a file format commonly used to store private keys with accompanying public key certificates, protected with a password-based symmetric key. PFX is a predecessor to PKCS #12.

    This container format can contain multiple embedded objects, such as multiple certificates. Usually protected/encrypted with a password. Usable as a format for the Java key store and to establish client authentication certificates in Mozilla Firefox. Usable by Apache Tomcat.

  • PKCS #13 – Elliptic Curve Cryptography Standard (Apparently abandoned, only reference is a proposal from 1998.)[12]

  • PKCS #14 – Pseudo-random Number Generation (Apparently abandoned, no documents exist.)

  • PKCS #15 1.1 Cryptographic Token Information Format Standard[13] Defines a standard allowing users of cryptographic tokens to identify themselves to applications, independent of the application’s Cryptoki implementation (PKCS #11) or other API. RSA has relinquished IC-card-related parts of this standard to ISO/IEC 7816-15.[14]

6) OpenSSL Certificate Authority

This guide demonstrates how to act as your own certificate authority (CA) using the OpenSSL command-line tools. This is useful in a number of situations, such as issuing server certificates to secure an intranet website, or for issuing certificates to clients to allow them to authenticate to a sever.

6-1) Introduction

OpenSSL is a free and open-source cryptographic library that provides several command-line tools for handling digital certificates. Some of these tools can be act as a Certificate Authority

A certificate authority is an entity that sgins digital certificates. Many websites need to let their customers know that the connection is secure

, so they pay an international Certificate Authority (CA) to sign a certificate for their domain.

In some cases it may make more sense to act as your own CA, rather than paying a CA like DigiCert. Common cases include securing an intranet website, or for issuing certificate to clients to allow them to authenticate to a server.

6-2) Create the root pair

Acting as a certificate authority means dealing with cryptograhic pair of private keys and public certificates. The very first cryptographic pair we’ll create is the root pair. This consists of the root key (ca.key.pem) and root certificate (ca.cert.pem). This pair forms the identity of your CA.

Typically, the root CA does not sign server or client certificate directly. The root CA is only ever used to create one or more intermediate CAs, which are trusted by the root CA to sign certificate 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 is disastrous.

Note:

It’s best practice to create the root pair in a secure environment. Ideally,

this should be on a fully encrypted, air gapped computer that is permanently isolated from the Internet. Remove the wireless card and fill the ethernet with glue.

6-2-1)Prepare the directory

Choose a directoy to store all keys and certificates.

mkdir /root/ca

Create the directory structure. The index.txt and serial files act as a flat file database to keep track of signed certificates.

cd /root/camkdir certs crl newcerts privatechmod 700 privatetouch index.txtecho 1000 > serial

6-2-2) Prepare the configuration file

You must create a configuration file for OpenSSL to use. Copy the root CA configuration file from the Appendix to /root/ca/openssl.cnf.

The [ca] section is mandatory. Here we tell OpenSSL to use the options from the [CA_default] section.

[ca]# `man ca`default_ca = CA_default

The [CA_default] section contains a range of defaults. Make sure you declare the directory you chose earlier(/root/ca).

[CA_defalut]# Directory and file lcations.dir                 = /root/cacerts               = $dir/certscrl_dir         = $dir/crlnew_certs_dir       = $dir/newcertsdatabase            = $dir/index.txtserial              = $dir/serialRANDFILE            = $dir/private/.rand# The root key and root certificate.private_key         = $dir/private/ca.key.pemcertificate     = $dir/certs/ca.cert.pem# For certificate revocation listscrlnumber           = $dir/crlnumbercrl                 = $dir/crl/ca.crl.pemcrl_extension       = crl_extdefault_crl_days    = 30# SHA-1 is deprecated, so use SHA-2 instead.defualt_md      = sha256name_opt            = ca_defaultcert_opt            = ca_defaultdefault_days        = 375preserve            = nopolicy              = plicy_strict

We’ll apply policy_strict for all root CA signatures, as the root CA is only being used to create intermediate CAs.

[ policy_strict]# The root CA should only sign intermediate certificates that match.# See the POLICY FORMAT section of `man ca`.countryName             = matchstateOrProvinceName     = matchorganizationName            = matchorganizationalUnitName  = optionalcommonName              = suppliedemailAddress                = optional

We’ll apply policy_loose for all intermediate CA signatures, as the intermediate CA is signing server and client certifcate that may come from a variety of third-parties.

[ policy_loose ]# Allow the intermediate CA to sign a more diverse range of certificates.# See the POLICY FORMAT section of the `ca` man page.countryName             = optionalstateOrProvinceName     = optionallocalityName            = optionalorganizationName        = optionalorganizationalUnitName  = optionalcommonName              = suppliedemailAddress            = optional

Options from te [req] section are applied when creating certificates or certificate signing requests.

[ req ]# options for the `req` tool (`man req`).default_bits                = 2048distinguished_name      = req_distinguished_namestring_mask             = utf8only# SHA-1 is deprecated, so use SHA-2 instead.default_md          = sha256# Extension to add when the -x509 option is used.x509_extensions     = v3_ca

The [ req_distinguished_name ] section declares the information normally required in a certificate signing request. You can optionally specify some defaults.

[ req_distinguished_name ]# See 
.countryName = Country Name (2 letter code)stateOrProvinceName = State or Province NamelocalityName = Locality Name0.organizationName = Organization NameorganizationalUnitName = Organizational Unit NamecommonName = Common NameemailAddress = Email Address# Optionally, specify some defaults.countryName_default = GBstateOrProvinceName_default = EnglandlocalityName_default =0.organizationName_default = Alice Ltd#organizationalUnitName_default =#emailAddress_default =

The next few sections are extensions that can be applied when signing certificates. For example, passing the -extensions v3_ca command-line argument will apply the options set in [ v3_ca ].

We’ll apply the [ v3_ca ] extension when we create the root certificate.

[ v3_ca ]# Extensions for a typical CA (`man x509v3_config`).subjectKeyIdentifier            = hashautorityKeyIdentifier           = keyid:always,issuerbasicConstraints                    = critical, CA:truekeyUsage                            = critical, digitalSignature, cRLsign, keyCertSign

We’ll apply the v3_ca_intermediate extension when we create the intermediate certificate. pathlen:0 ensuers that there can be no further certificate authorities below the intermediate CA.

[ v3_intermediate_ca ]# Extensions for a typical intermediate CA (`man x509v3_config`).subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid:always,issuerbasicConstraints = critical, CA:true, pathlen:0keyUsage = critical, digitalSignature, cRLSign, keyCertSign

We’ll apply the server_cert extension when signing server certificates, such as those used for web servers.

[ server_cert ]# Extensions for server certificates (`man x509v3_config`).basicConstraints = CA:FALSEnsCertType = servernsComment = "OpenSSL Generated Server Certificate"subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid,issuer:alwayskeyUsage = critical, digitalSignature, keyEnciphermentextendedKeyUsage = serverAuth

The crl_ext extension is automatically applied when creating certificate revocation lists.

[ crl_ext ]# Extension for CRLs (`man x509v3_config`).authorityKeyIdentifier=keyid:always

We’ll apply the ocsp extension when signing the Online Certificate Status Protocol (OCSP) certificate.

[ ocsp ]# Extension for OCSP signing certificates (`man ocsp`).basicConstraints = CA:FALSEsubjectKeyIdentifier = hashauthorityKeyIdentifier = keyid,issuerkeyUsage = critical, digitalSignatureextendedKeyUsage = critical, OCSPSigning

6-2-3) Create the root key

Create the root key (ca.key.pem) and keep it absolutely secure. Anyone in possession of the root key can issue trusted certificates. Encrypt the root key with AES 256-bit encryption and a strong password.

Note:

Use 4096 bits for all root and intermediate certificate authority keys. You’ll still be able to sign server and client certificates of a shorter length.

cd /root/caopenssl genrsa -aes256 -out private/ca.key.pem 4096Enter pass phrase for ca.key.pem: secretpasswordVerifying - Enter pass phrase for ca.key.pem: secretpasswordchmod 400 private/ca.key.pem

6-2-4) Create the root certificate

Use the root key (ca.key.pem) to create a root certificate (ca.cert.pem). Give the root certificate a long expire date, such as twenty years. Once the root certificate expires, all certificates signed by the CA become invalid.

Warning

Whenever you use the req tool, you must specifiy a configuration file to use with the -config option, otherwise OpenSSL will default to /etc/pki/tls/openssl.cnf

cd /root/caopenssl req -config openssl.cnf \    -key private/ca.key.pem \    -new -x509 -days 7300 -sha256 -extensions v3_ca \    -out certs/ca.cert.pemEnter pass phrase for ca.key.pem: secretpasswordYou are about to be asked to enter information that will be incorporatedinto your certificate request.-----Country Name (2 letter code) [XX]:GBState or Province Name []:EnglandLocality Name []:Organization Name []:Alice LtdOrganizational Unit Name []:Alice Ltd Certificate AuthorityCommon Name []:Alice Ltd Root CAEmail Address []:

6-2-5) Verify the root certificate

openssl x509 -noout -text -in certs/ca.cert.pem

The output shows:

  • the signature algorithm used
  • the dates of certificate validit
  • the public-key bit length
  • the issuer, which is the entity that signed the certificate
  • the subject, which refers to the certificate itself

The Issuer and Subject are identical as the certificate is self-signed. Note that all root certificates are self-signed.

Signature Algorithm: sha256WithRSAEncryption    Issuer: C=GB, ST=England,            O=Alice Ltd, OU=Alice Ltd Certificate Authority,            CN=Alice Ltd Root CA    Validity        Not Before: Apr 11 12:22:58 2015 GMT        Not After : Apr  6 12:22:58 2035 GMT    Subject: C=GB, ST=England,             O=Alice Ltd, OU=Alice Ltd Certificate Authority,             CN=Alice Ltd Root CA    Subject Public Key Info:        Public Key Algorithm: rsaEncryption            Public-Key: (4096 bit)

The Output also shows the X509v3 extensions. We applied the v3_ca extension, so the options from [ v3_ca ] should be reflectted in the output.

X509v3 extensions:    X509v3 Subject Key Identifier:        38:58:29:2F:6B:57:79:4F:39:FD:32:35:60:74:92:60:6E:E8:2A:31    X509v3 Authority Key Identifier:        keyid:38:58:29:2F:6B:57:79:4F:39:FD:32:35:60:74:92:60:6E:E8:2A:31    X509v3 Basic Constraints: critical        CA:TRUE    X509v3 Key Usage: critical        Digital Signature, Certificate Sign, CRL Sign

6-3) Create the intermediate pair

An intermediate certificate autority (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 certificate primarily of 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.

6-3-1) Prepare the directory

The root CA files are kept in /root/ca. Choose a different directory (/root/ca/intermediate) to store the intermediate CA files.

mkdir /root/ca/intermediate

Create the smae directory structure used for the root files. It’s convenient to also create a csr directory to hold certificate siging requests.

cd /root/ca/intermediatemkdir certs crl csr newcerts privatechmod 700 privatetouch index.txtecho 1000 > serial

Add a crlnumber file to the intermediate CA directory tree. crlnumber is used to keep track of certificate revocation lists.

# echo 1000 > /root/ca/intermediate/crlnumber

Copy the intermediate CA configuration file from the Appendix to /root/ca/intermediate/openssl.cnf. Five options have been changed compared to the root CA configuration file:

[ CA_default ]dir             = /root/ca/intermediateprivate_key     = $dir/private/intermediate.key.pemcertificate     = $dir/certs/intermediate.cert.pemcrl             = $dir/crl/intermediate.crl.pempolicy          = policy_loose

6-3-2) Create the intermediate key

Create the intermediate key (intermediate.key.pem). Encrypt the intermediate key with AES 256-bit encryption and a strong password.

# cd /root/ca# openssl genrsa -aes256 \      -out intermediate/private/intermediate.key.pem 4096Enter pass phrase for intermediate.key.pem: secretpasswordVerifying - Enter pass phrase for intermediate.key.pem: secretpassword# chmod 400 intermediate/private/intermediate.key.pem

6-3-3) Create the intermediate certificate

Use the intermediate key to create a certificate signing request (CSR). The details should generally match the root CA. The Common Name, however, must be different.

Warning

Make sure you specify the intermediate CA configuration file (intermediate/openssl.cnf).

# cd /root/ca# openssl req -config intermediate/openssl.cnf -new -sha256 \      -key intermediate/private/intermediate.key.pem \      -out intermediate/csr/intermediate.csr.pemEnter pass phrase for intermediate.key.pem: secretpasswordYou are about to be asked to enter information that will be incorporatedinto your certificate request.-----Country Name (2 letter code) [XX]:GBState or Province Name []:EnglandLocality Name []:Organization Name []:Alice LtdOrganizational Unit Name []:Alice Ltd Certificate AuthorityCommon Name []:Alice Ltd Intermediate CAEmail Address []:

To create an intermediate certificate, use the root CA with the v3_intermediate_ca extension to sign the intermediate CSR. The intermediate certificate should be valid for a shorter period than the root certificate. Ten years would be reasonable.

Warning

This time, specify the root CA configuration file (/root/ca/openssl.cnf).

# cd /root/ca# openssl ca -config openssl.cnf -extensions v3_intermediate_ca \      -days 3650 -notext -md sha256 \      -in intermediate/csr/intermediate.csr.pem \      -out intermediate/certs/intermediate.cert.pemEnter pass phrase for ca.key.pem: secretpasswordSign the certificate? [y/n]: y# chmod 444 intermediate/certs/intermediate.cert.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.

V 250408122707Z 1000 unknown ... /CN=Alice Ltd Intermediate CA

6-3-4) Verify the intermediate certificate

As we did for the root certificate, check that the details of the intermediate certificate are correct.

# openssl x509 -noout -text \      -in intermediate/certs/intermediate.cert.pem

Verify the intermediate certificate against the root certificate. An OK indicates that the chain of trust is intact.

# openssl verify -CAfile certs/ca.cert.pem \      intermediate/certs/intermediate.cert.pemintermediate.cert.pem: OK

6-3-5) Create the certificate chain file

When an application (eg, a web browser) tries to verify a certificate signed by the intermediate CA, it must also verify the intermediate certificate against the root certificate. To complete the chain of trust, create a CA certificate chain to present to the application.

To create the CA certificate chain, concatenate the intermediate and root certificates together. We will use this file later to verify certificates signed by the intermediate CA.

# cat intermediate/certs/intermediate.cert.pem \      certs/ca.cert.pem > intermediate/certs/ca-chain.cert.pem# chmod 444 intermediate/certs/ca-chain.cert.pem

Note

Our certificate chain file must include the root certificate because no client application knows about it yet. A better option, particularly if you’re administrating an intranet, is to install your root certificate on every client that needs to connect. In that case, the chain file need only contain your intermediate certificate.

6-4) Sign server and client certificates

We will be signing certificates using our intermediate CA. You can use these signed certificates in a variety of situations, such as to secure connections to a web server or to authenticate clients connecting to a server.

Note

The steps below are from your perspective as the certificate authority. A third-party, however, can instead create their own private key and certificate signing request (CSR) without revealing their private key to you. They give you their CSR, and you give back a signed certificate. In that scenario, skip the genrsa and req commands.

6-4-1) Create a key

Our root and intermediate pairs are 4096 bits. Server and client certificates normally expire after one year, so we can safely use 2048 bits instead.

Note

Although 4096 bits is slightly more secure than 2048 bits, it slows down TLS handshakes and significantly increase processor load during handshakes. For this reason, most websites use 2048 bits pairs.

If you’re creating a cryptograhic pair for use with a web server, you’ll need to enter this password every time you restart that web server. You may want to omit the -aes256 option to create a key without a password.

# cd /root/ca# openssl genrsa -aes256 \      -out intermediate/private/www.example.com.key.pem 2048# chmod 400 intermediate/private/www.example.com.key.pem

6-4-2) Create a certificate

Use the private key to create a certificate signing request (CSR). The CSR details don’t need to match the intermediate CA. For server certificates, the Common Name must be a fully quallfied domain name (eg, www.example.com) whereas for client certificates it can be any unique identifier (eg, an e-mail address). Note that the common name connot be the same as either your root or intermediate certifcate.

# cd /root/ca# openssl req -config intermediate/openssl.cnf \      -key intermediate/private/www.example.com.key.pem \      -new -sha256 -out intermediate/csr/www.example.com.csr.pemEnter pass phrase for www.example.com.key.pem: secretpasswordYou are about to be asked to enter information that will be incorporatedinto your certificate request.-----Country Name (2 letter code) [XX]:USState or Province Name []:CaliforniaLocality Name []:Mountain ViewOrganization Name []:Alice LtdOrganizational Unit Name []:Alice Ltd Web ServicesCommon Name []:www.example.comEmail Address []:

To create a certificate, use the intermediate CA to sign the CSR. If the certificate is going to be used on a server, use the server_cert extension. If the certificate is going to be used for user authentication, use the usr_cert extension. Certificates are usually given a validity of one year, though a CA will typically give a few days extra for convenience.

# cd /root/ca# openssl ca -config intermediate/openssl.cnf \      -extensions server_cert -days 375 -notext -md sha256 \      -in intermediate/csr/www.example.com.csr.pem \      -out intermediate/certs/www.example.com.cert.pem# chmod 444 intermediate/certs/www.example.com.cert.pem

The intermediate/index.txt file should contain a line referring to this new certificate.

V 160420124233Z 1000 unknown ... /CN=www.example.com

6-4-3) Verify the certificate

# openssl x509 -noout -text \      -in intermediate/certs/www.example.com.cert.pem

The Issuer is the intermediate CA. The Subject refers to the certificate itself.

Signature Algorithm: sha256WithRSAEncryption    Issuer: C=GB, ST=England,            O=Alice Ltd, OU=Alice Ltd Certificate Authority,            CN=Alice Ltd Intermediate CA    Validity        Not Before: Apr 11 12:42:33 2015 GMT        Not After : Apr 20 12:42:33 2016 GMT    Subject: C=US, ST=California, L=Mountain View,             O=Alice Ltd, OU=Alice Ltd Web Services,             CN=www.example.com    Subject Public Key Info:        Public Key Algorithm: rsaEncryption            Public-Key: (2048 bit)

The output will also show the X509v3 extensions. When creating the certificate, you used either the server_cert or usr_cert extension. The options from the corresponding configuration section will be reflected in the output.

X509v3 extensions:    X509v3 Basic Constraints:        CA:FALSE    Netscape Cert Type:        SSL Server    Netscape Comment:        OpenSSL Generated Server Certificate    X509v3 Subject Key Identifier:        B1:B8:88:48:64:B7:45:52:21:CC:35:37:9E:24:50:EE:AD:58:02:B5    X509v3 Authority Key Identifier:        keyid:69:E8:EC:54:7F:25:23:60:E5:B6:E7:72:61:F1:D4:B9:21:D4:45:E9        DirName:/C=GB/ST=England/O=Alice Ltd/OU=Alice Ltd Certificate Authority/CN=Alice Ltd Root CA        serial:10:00    X509v3 Key Usage: critical        Digital Signature, Key Encipherment    X509v3 Extended Key Usage:        TLS Web Server Authentication

Use the CA certificate chain file we created earlier (ca-chain.cert.pem) to verfiy that the new certificate has a valid chain of trust.

# openssl verify -CAfile intermediate/certs/ca-chain.cert.pem \      intermediate/certs/www.example.com.cert.pemwww.example.com.cert.pem: OK

6-4-4) Deploy the certificate

You can now either deploy your new certificate to a server, or distribute the certificate to a client. When deploying to a server application (eg, Apache), you need to make the following files available:

  • ca-chain.cert.com
  • www.example.com.key.pem
  • www.example.com.cert.pem

If you’re signing a CSR from a third-party, you don’t have to access their private key so you only need to give them back the chain file (ca-chain.cert.pem) and the certificate (www.example.com.cert.pem).

6-5) Certificate Revocation Lists

A certifciate revocation list (CRL) provides a list of certificates that have been revoked. A client application, such as a web browser, can use a CRL to check a server’s authenticity. A server application, such as Apache or OpenVPN, can use a CRL to deny access to clients that are no longer trusted.

Publish the CRL at a public accessible location (eg, ). Third-parties can fetch the CRL from this location to check wheter any certificates they rely on have been revoked.

Note

Some application vendors have deprecated CRLs and are instead using the Online Certificate Status Protocol (OCSP)

6-5-1) Prepare the configuration file

When a certificate authority signs a certificate, it will normally encode the CRL location into the certificate. Add crlDistributionPoints to the appropriate sections. In our case, add it to the [ server_cert ] section.

[ server_cert ]# ... snipped ...crlDistributionPoints = URI:http://example.com/intermediate.crl.pem

6-5-2) Create the CRL

# cd /root/ca# openssl ca -config intermediate/openssl.cnf \      -gencrl -out intermediate/crl/intermediate.crl.pem

Note

The CRL OPTIONS section of the ca man page contains more information on how to create CRLs.

You can check the contents of the CRL with the crl tool.

openssl crl -in intermediate/crl/intermediate.crl.pem -noout -text

No certificates have been revoked yet, so the output will state No Revoked Certificates

You should re-create the CRLs at regular intervals. By default, the CRL expire after 30 days. This is controlled by the default_crl_days option in the [ CA_default ] section.

6-5-3) Revoke a certificate

Let’s walk through an example. Alice is running the Apache server and has a private folder of heart-meltingly cute kitten pictures. Alice wants to grant her friend, bob, access to this collection.

Bob create a private key and certificate signing request (CSR).

cd /home/bobopenssl genrsa -out bob@example.com.key.pem 2048openssl req -new -key bob@example.com.key.pem \    -out bob@example.com.csr.pemYou are about to be asked to enter information that will be incorporatedinto your certificate request.-----Country Name [XX]:USState or Province Name []:CaliforniaLocality Name []:San FranciscoOrganization Name []:Bob LtdOrganizational Unit Name []:Common Name []:bob@example.comEmail Address []:

Bob sends his CSR to Alice, who then signs it.

cd /root/caopenssl ca -config intermediate/openssl.cnf \    -extension usr_cert -notext -md sha256 \    -in intermediate/csr/bob@example.com.csr.pem \    -out intermediate/certs/bob@example.com.cert.pem

Alice verifies that the certificate is valid:

openssl verify -CAfile intermediate/certs/ca-chain.cert.pem \    intermediate/certs/bob@example.com.cert.pembob@example.com.cert.pem: OK

The index.txt file should contain a new entry

V 160420124740Z 1001 unknown ... /CN=bob@example.com

Alice sends Bob teh signed certificate. Bob installs the certificate in his web brower and is now able to access Alice’s kitten pictures. Hurray!

Sadly, it turns out that Bob is misbehaving. Bob has posted Alice’s kitten pictures to Hacker News, claiming that they’re his own and gaining huge popularity. Alice finds out and needs to revoke his access immediately.

cd /root/caopenssl ca -config intermediate/openssl.cnf \    -revoke intermediate/certs/bob@example.com.cert.pemEnter pass phrase for intermediate.key.pem: secretpasswordRevoking Certificate 1001.Data Base Updated

The line in index.txt that corresponds to Bob’s certificate now begins with the character R, This means the certificate has been revoked.

R 160420124740Z 150411125310Z 1001 unknown ... /CN=bob@example.com

After revoking Bob’s certificate, Alice must re-create the CRL.

6-5-4) Server-side use of the CRL

For client certificates, It’s typically a server-side application (eg, Apache) that doing the verification. This application need to have local access to the CRL.

In Alice’s case, she can add the SSLCARevocationPath directive to her Apache configuration and copy the CRL to her web server. The next time that Bob connects to the web server, Apache will check his client certificate against the CRL and deny access.

Similarly, OpenVPN has a crl-verfiy directive so that it can block clients that have had their certificates revoked.

6-5-5) Client-side use of the CRL

For server certificate, it’s typically a server-side application (eg, a web browser) that doing the verification. This application must have remove access to the CRL.

If a certificate was signed with an extension that include crlDistributionPoints, a client-side application can read this information and fetch the CRL from teh specified location.

The CRL distribution Point is visible in the certificate X509v3 details.

opnessl x509 -in cute-kitten-pictures.example.com.cert.pem -noout -textX509v3 CRL Distribution Points:        Full Name:          URI:http://example.com/intermediate.crl.pem

6-6) Online Certificate Status Protocol

The Online Certificate Status Protocol (OCSP) was created as an alternative to certificate revocation lists (CRLs). Similar to CRLs, OCSP enable a requesting party (eg, a web browser) to determine the revocation state of a certificate.

When a CA signs a certificate, they will typically include the OCSP server address in the certificate. This is similar in function to crlDistributionPoints used for CRLs.

As an example, when a web browser is presented with a server certificate, it will send a query to the OCSP server address sepcified in the certificate. at this address, an OCSP responder listens to queries and responds with the revocation status of the certificate.

Note:

It’s recommended to use OCSP instead where possible, though realistically you will tend to only need OCSP for website certficate. Some web browsers have deprecated or removed support for CRLs.

6-6-1) Prepare the configuartion file

To use OCSP, CA must encode the OCSP server location into the certificates that it signs. Use the authorityInfoAccess option in the appropriate sections, which in out case means the [ server_cert ] section.

[ server_cert ]# ... snipped ...authorityInfoAccess = OCSP;URI:http://ocsp.example.com

6-6-2) Create the OCSP pair

The OCSP responder requires a cryptographic pair for signing the response that it sends to the requesting party. The OCSP cryptographic pair. The OCSP cryptographic pair must be signed by the same CA that signed the certificate being checked.

Create a private key and encrypt it with AES-256 encryption.

# cd /root/ca# openssl genrsa -aes256 \      -out intermediate/private/ocsp.example.com.key.pem 4096

Create a certificate signing request (CSR). The details should generally match those of the signing CA. The Common Name, however, must be fully qualified domain name.

# cd /root/ca# openssl req -config intermediate/openssl.cnf -new -sha256 \      -key intermediate/private/ocsp.example.com.key.pem \      -out intermediate/csr/ocsp.example.com.csr.pemEnter pass phrase for intermediate.key.pem: secretpasswordYou are about to be asked to enter information that will be incorporatedinto your certificate request.-----Country Name (2 letter code) [XX]:GBState or Province Name []:EnglandLocality Name []:Organization Name []:Alice LtdOrganizational Unit Name []:Alice Ltd Certificate AuthorityCommon Name []:ocsp.example.comEmail Address []:

Sign the CSR with the intermediate CA.

# openssl ca -config intermediate/openssl.cnf \      -extensions ocsp -days 375 -notext -md sha256 \      -in intermediate/csr/ocsp.example.com.csr.pem \      -out intermediate/certs/ocsp.example.com.cert.pem

Verify that the certificate has the correct X509v3 extensions.

# openssl x509 -noout -text \      -in intermediate/certs/ocsp.example.com.cert.pem    X509v3 Key Usage: critical        Digital Signature    X509v3 Extended Key Usage: critical        OCSP Signing

6-6-3) Revoke a certificate

The OpenSSL ocsp tool can act as an OCSP responder, but it’s only intended for testing. Production ready OCSP responders exist, but those are beyond the scope of this guide.

Create a server certificate to test.

# cd /root/ca# openssl genrsa -out intermediate/private/test.example.com.key.pem 2048# openssl req -config intermediate/openssl.cnf \      -key intermediate/private/test.example.com.key.pem \      -new -sha256 -out intermediate/csr/test.example.com.csr.pem# openssl ca -config intermediate/openssl.cnf \      -extensions server_cert -days 375 -notext -md sha256 \      -in intermediate/csr/test.example.com.csr.pem \      -out intermediate/certs/test.example.com.cert.pem

Run the OCSP responder on localhost. Rather than storing revocation status in a separate CRL file, the OCSP responder reads index.txt directly. The response is signed with the OCSP cryptographic pair (using the -rkey and -rsigner options).

openssl ocsp -port 127.0.0.1:2560 -text -sha256 \      -index intermediate/index.txt \      -CA intermediate/certs/ca-chain.cert.pem \      -rkey intermediate/private/ocsp.example.com.key.pem \      -rsigner intermediate/certs/ocsp.example.com.cert.pem \      -nrequest 1

In another terminal, send a query to the OCSP responder. The -cert option specifies the certificate to query.

# openssl ocsp -CAfile intermediate/certs/ca-chain.cert.pem \      -url http://127.0.0.1:2560 -resp_text \      -issuer intermediate/certs/intermediate.cert.pem \      -cert intermediate/certs/test.example.com.cert.pem

The start of the output shows:

  • whether a successful response was received (OCSP Response Status)
  • then identity of the responder (Responder Id)
  • the revocation status of the certficate (Cert Status)
OCSP Response Data:    OCSP Response Status: successful (0x0)    Response Type: Basic OCSP Response    Version: 1 (0x0)    Responder Id: ... CN = ocsp.example.com    Produced At: Apr 11 12:59:51 2015 GMT    Responses:    Certificate ID:      Hash Algorithm: sha1      Issuer Name Hash: E35979B6D0A973EBE8AEDED75D8C27D67D2A0334      Issuer Key Hash: 69E8EC547F252360E5B6E77261F1D4B921D445E9      Serial Number: 1003    Cert Status: good    This Update: Apr 11 12:59:51 2015 GMT

Revoke the certificate.

# openssl ca -config intermediate/openssl.cnf \      -revoke intermediate/certs/test.example.com.cert.pemEnter pass phrase for intermediate.key.pem: secretpasswordRevoking Certificate 1003.Data Base Updated

As before, run the OCSP responder and on another terminal send a query. This time, the output shows Cert Status: revoked and a Revocation Time.

OCSP Response Data:    OCSP Response Status: successful (0x0)    Response Type: Basic OCSP Response    Version: 1 (0x0)    Responder Id: ... CN = ocsp.example.com    Produced At: Apr 11 13:03:00 2015 GMT    Responses:    Certificate ID:      Hash Algorithm: sha1      Issuer Name Hash: E35979B6D0A973EBE8AEDED75D8C27D67D2A0334      Issuer Key Hash: 69E8EC547F252360E5B6E77261F1D4B921D445E9      Serial Number: 1003    Cert Status: revoked    Revocation Time: Apr 11 13:01:09 2015 GMT    This Update: Apr 11 13:03:00 2015 GMT

6-7) Appendix

6-7-1) Root CA configuration file

# OpenSSL root CA configuration file.# Copy to `/root/ca/openssl.cnf`.[ ca ]# `man ca`default_ca = CA_default[ CA_default ]# Directory and file locations.dir               = /root/cacerts             = $dir/certscrl_dir           = $dir/crlnew_certs_dir     = $dir/newcertsdatabase          = $dir/index.txtserial            = $dir/serialRANDFILE          = $dir/private/.rand# The root key and root certificate.private_key       = $dir/private/ca.key.pemcertificate       = $dir/certs/ca.cert.pem# For certificate revocation lists.crlnumber         = $dir/crlnumbercrl               = $dir/crl/ca.crl.pemcrl_extensions    = crl_extdefault_crl_days  = 30# SHA-1 is deprecated, so use SHA-2 instead.default_md        = sha256name_opt          = ca_defaultcert_opt          = ca_defaultdefault_days      = 375preserve          = nopolicy            = policy_strict[ policy_strict ]# The root CA should only sign intermediate certificates that match.# See the POLICY FORMAT section of `man ca`.countryName             = matchstateOrProvinceName     = matchorganizationName        = matchorganizationalUnitName  = optionalcommonName              = suppliedemailAddress            = optional[ policy_loose ]# Allow the intermediate CA to sign a more diverse range of certificates.# See the POLICY FORMAT section of the `ca` man page.countryName             = optionalstateOrProvinceName     = optionallocalityName            = optionalorganizationName        = optionalorganizationalUnitName  = optionalcommonName              = suppliedemailAddress            = optional[ req ]# Options for the `req` tool (`man req`).default_bits        = 2048distinguished_name  = req_distinguished_namestring_mask         = utf8only# SHA-1 is deprecated, so use SHA-2 instead.default_md          = sha256# Extension to add when the -x509 option is used.x509_extensions     = v3_ca[ req_distinguished_name ]# See 
.countryName = Country Name (2 letter code)stateOrProvinceName = State or Province NamelocalityName = Locality Name0.organizationName = Organization NameorganizationalUnitName = Organizational Unit NamecommonName = Common NameemailAddress = Email Address# Optionally, specify some defaults.countryName_default = GBstateOrProvinceName_default = EnglandlocalityName_default =0.organizationName_default = Alice LtdorganizationalUnitName_default =emailAddress_default =[ v3_ca ]# Extensions for a typical CA (`man x509v3_config`).subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid:always,issuerbasicConstraints = critical, CA:truekeyUsage = critical, digitalSignature, cRLSign, keyCertSign[ v3_intermediate_ca ]# Extensions for a typical intermediate CA (`man x509v3_config`).subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid:always,issuerbasicConstraints = critical, CA:true, pathlen:0keyUsage = critical, digitalSignature, cRLSign, keyCertSign[ usr_cert ]# Extensions for client certificates (`man x509v3_config`).basicConstraints = CA:FALSEnsCertType = client, emailnsComment = "OpenSSL Generated Client Certificate"subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid,issuerkeyUsage = critical, nonRepudiation, digitalSignature, keyEnciphermentextendedKeyUsage = clientAuth, emailProtection[ server_cert ]# Extensions for server certificates (`man x509v3_config`).basicConstraints = CA:FALSEnsCertType = servernsComment = "OpenSSL Generated Server Certificate"subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid,issuer:alwayskeyUsage = critical, digitalSignature, keyEnciphermentextendedKeyUsage = serverAuth[ crl_ext ]# Extension for CRLs (`man x509v3_config`).authorityKeyIdentifier=keyid:always[ ocsp ]# Extension for OCSP signing certificates (`man ocsp`).basicConstraints = CA:FALSEsubjectKeyIdentifier = hashauthorityKeyIdentifier = keyid,issuerkeyUsage = critical, digitalSignatureextendedKeyUsage = critical, OCSPSigning

6-7-2) Intermediate CA configuration file

# OpenSSL intermediate CA configuration file.# Copy to `/root/ca/intermediate/openssl.cnf`.[ ca ]# `man ca`default_ca = CA_default[ CA_default ]# Directory and file locations.dir               = /root/ca/intermediatecerts             = $dir/certscrl_dir           = $dir/crlnew_certs_dir     = $dir/newcertsdatabase          = $dir/index.txtserial            = $dir/serialRANDFILE          = $dir/private/.rand# The root key and root certificate.private_key       = $dir/private/intermediate.key.pemcertificate       = $dir/certs/intermediate.cert.pem# For certificate revocation lists.crlnumber         = $dir/crlnumbercrl               = $dir/crl/intermediate.crl.pemcrl_extensions    = crl_extdefault_crl_days  = 30# SHA-1 is deprecated, so use SHA-2 instead.default_md        = sha256name_opt          = ca_defaultcert_opt          = ca_defaultdefault_days      = 375preserve          = nopolicy            = policy_loose[ policy_strict ]# The root CA should only sign intermediate certificates that match.# See the POLICY FORMAT section of `man ca`.countryName             = matchstateOrProvinceName     = matchorganizationName        = matchorganizationalUnitName  = optionalcommonName              = suppliedemailAddress            = optional[ policy_loose ]# Allow the intermediate CA to sign a more diverse range of certificates.# See the POLICY FORMAT section of the `ca` man page.countryName             = optionalstateOrProvinceName     = optionallocalityName            = optionalorganizationName        = optionalorganizationalUnitName  = optionalcommonName              = suppliedemailAddress            = optional[ req ]# Options for the `req` tool (`man req`).default_bits        = 2048distinguished_name  = req_distinguished_namestring_mask         = utf8only# SHA-1 is deprecated, so use SHA-2 instead.default_md          = sha256# Extension to add when the -x509 option is used.x509_extensions     = v3_ca[ req_distinguished_name ]# See 
.countryName = Country Name (2 letter code)stateOrProvinceName = State or Province NamelocalityName = Locality Name0.organizationName = Organization NameorganizationalUnitName = Organizational Unit NamecommonName = Common NameemailAddress = Email Address# Optionally, specify some defaults.countryName_default = GBstateOrProvinceName_default = EnglandlocalityName_default =0.organizationName_default = Alice LtdorganizationalUnitName_default =emailAddress_default =[ v3_ca ]# Extensions for a typical CA (`man x509v3_config`).subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid:always,issuerbasicConstraints = critical, CA:truekeyUsage = critical, digitalSignature, cRLSign, keyCertSign[ v3_intermediate_ca ]# Extensions for a typical intermediate CA (`man x509v3_config`).subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid:always,issuerbasicConstraints = critical, CA:true, pathlen:0keyUsage = critical, digitalSignature, cRLSign, keyCertSign[ usr_cert ]# Extensions for client certificates (`man x509v3_config`).basicConstraints = CA:FALSEnsCertType = client, emailnsComment = "OpenSSL Generated Client Certificate"subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid,issuerkeyUsage = critical, nonRepudiation, digitalSignature, keyEnciphermentextendedKeyUsage = clientAuth, emailProtection[ server_cert ]# Extensions for server certificates (`man x509v3_config`).basicConstraints = CA:FALSEnsCertType = servernsComment = "OpenSSL Generated Server Certificate"subjectKeyIdentifier = hashauthorityKeyIdentifier = keyid,issuer:alwayskeyUsage = critical, digitalSignature, keyEnciphermentextendedKeyUsage = serverAuth[ crl_ext ]# Extension for CRLs (`man x509v3_config`).authorityKeyIdentifier=keyid:always[ ocsp ]# Extension for OCSP signing certificates (`man ocsp`).basicConstraints = CA:FALSEsubjectKeyIdentifier = hashauthorityKeyIdentifier = keyid,issuerkeyUsage = critical, digitalSignatureextendedKeyUsage = critical, OCSPSigning

转载地址:http://peyvb.baihongyu.com/

你可能感兴趣的文章
结构体变量之间的比较和赋值原理
查看>>
C++ const修饰函数、函数参数、函数返回值
查看>>
将单链表的每k个节点之间逆序
查看>>
删除链表中重复的节点——重复节点不保留
查看>>
2018腾讯校招编程题——最重要的城市
查看>>
删除链表中重复的节点——重复节点保留一个
查看>>
实战c++中的vector系列--正确释放vector的内存(clear(), swap(), shrink_to_fit()).md
查看>>
链表排序.md
查看>>
进程与线程的区别与联系、进程与线程的通信方式
查看>>
C++与C的区别
查看>>
产生死锁的必要条件及处理方法
查看>>
TCP和UDP的区别
查看>>
事务具有四个特性
查看>>
static和const关键字的作用
查看>>
Hadoop Hdfs 配置
查看>>
tsung集群测试
查看>>
oracle定时删除表空间的数据并释放表空间
查看>>
servlet文件上传下载
查看>>
解决文件提示: /bin/ksh^M: bad interpreter: bad interpreter:No such file or directory
查看>>
ajaxanywhere jsp 使用
查看>>