Nginx SSL Fast bidirectional Authentication configuration (script)

Source: Internet
Author: User
Tags pkcs12 letsencrypt nginx ssl
This article mainly introduces the Nginx SSL fast Two-way authentication configuration (script), has a certain reference value, now share to everyone, the need for friends can refer to

Currently encountering a project has security requirements that require only individual users to have access. In accordance with the configuration can be solved by no code to solve the principle of the nginx on the restrictions and modifications can be.

This kind of demand actually realizes the way many, after the comprehensive evaluation consideration, feels that the SSL bidirectional authentication scheme is the simplest for the user, then decides to use this scheme.

Note : This program is implemented in Ubuntu Server 16.04 Lts, and other operating systems should be modified as appropriate

SSL bidirectional authentication

The vast majority of SSL applications are one-way authentication, that is, the client as long as the trust server, you can use the server side of the public key encryption after the server to initiate a request, the server's private key decrypted after the request data.

If this process in turn, let the server trust the client, the server uses the client's public key encryption after the data back to the client, in fact, it can be done, the principle and implementation are similar to one-way authentication.

Server-side Trust client operations are often accompanied by the client authentication service side process, so that the server trust client SSL authentication method is often referred to as SSL bidirectional authentication, and to configure SSL bidirectional authentication must first turn on the server SSL, first configure the Client trust service side.

Nginx SSL Two-way authentication configuration

The first step is to turn on HTTPS access

Based on the theoretical knowledge, we must first open the Nginx SSL configuration, that is, enable HTTPS. This process is relatively simple, there is let's encrypt this free certificate scheme, no longer worry about themselves to build a CA self-signed. The process of applying for a free certificate is skipped and is directly affixed to the HTTPS-enabled configuration:

server {Listen 80;  Listen 443 SSL HTTP2;  server_name example.com;  SSL_CERTIFICATE/ETC/LETSENCRYPT/LIVE/EXAMPLE.COM/FULLCHAIN.PEM;  SSL_CERTIFICATE_KEY/ETC/LETSENCRYPT/LIVE/EXAMPLE.COM/PRIVKEY.PEM;  # only Nginx >= 1.13.0 version only support TLSv1.3 protocol # Ssl_protocols TLSv1.3;  # Nginx below 1.13.0 version with this configuration Ssl_protocols TLSv1 TLSv1.1 TLSv1.2;   Ssl_prefer_server_ciphers on; Ssl_dhparam Dhparam.pem;  # OpenSSL Dhparam-out/etc/nginx/dhparam.pem 4096 ssl_ciphers ' Eecdh+aesgcm:edh+aesgcm:aes256+eecdh:aes256+edh '; Ssl_ecdh_curve secp384r1;  # Requires Nginx >= 1.1.0 ssl_session_timeout 10m;  Ssl_session_cache shared:ssl:10m; Ssl_session_tickets off; # Requires Nginx >= 1.5.9 ssl_stapling on; # Requires Nginx >= 1.3.7 ssl_stapling_verify on;  # Requires Nginx = 1.3.7 resolver 223.5.5.5 114.114.114.114 valid=300s;   Resolver_timeout 5s; # Enable HSTs configuration, do not enable HSTs # Add_header strict-transport-security "max-age=63072000 If you have a non-standard port access HTTP app under your domain name; Includesubdomains;  Preload "; # The following configuration will reject frameLabel content, please confirm that your site does not frame/iframe add_header x-frame-options DENY;  Add_header x-content-type-options Nosniff; Add_header x-xss-protection "1;  Mode=block ";  # in order to let ' s encrypt renew, do not let ' s encrypt do not need this location location/.well-known {root/usr/share/nginx/html; }   ...  SNIP. # force HTTP Jump to HTTPS if ($scheme! = "https") {return 301 https://$http _host$request_uri; }}
that's a lot of SSL configuration reference from: https://cipherli.st/Enhanced SSL Security Configuration

Pay special attention to the last mandatory https jump, our purpose is SSL bidirectional authentication, do not walk https no meaning, so must force jump HTTPS.

The second step is to generate a client certificate and a visa (script)

This process detailed description of the article too much, here is not verbose introduction OpenSSL and visa process, this article is to quickly generate two-way authentication configuration certificate, so directly paste the script on the line, commands are reference to the Internet on various OpenSSL bidirectional configuration documents, On this basis, the simplified and non-interactive support on the command is carried out.

Entire Directory structure:

# Tree/etc/nginx/ssl_certs//etc/nginx/ssl_certs/├──create_ca_cert.sh├──create_client_cert.sh├──revoke_cert.sh0 Directories, 3 files

Create your own /etc/nginx/ssl_certs/ , put in three scripts, respectively, to generate the CA certificate and the CA directory ( create_ca_cert.sh the role of the script, only the first time you need to run), create a client certificate, and a CA certificate visa ( create_client_cert.sh the role of the script must first generate a CA certificate), the revoke_cert.sh script is used to revoke the certificate, You can use it when you need to revoke permissions.

The contents of each script are as follows:

    • create_ca_cert.sh

#!/bin/bash-e# Create the CA root certificate # non-interactive Create the following: # Country name (2 letters code) c=cn# province st=shannxi# City l=xian# Company name O=my company# Organization or department name Ou= Technical Department # Server FQDN or issuer name cn=www.example.com# mailbox address emailaddress=admin@example.commkdir-p./democa/{private,newcerts}touch.  Democa/index.txt[!-F/democa/seria] && echo >/democa/serial[!-F./democa/crlnumber] && Echo >/democa/crlnumber[!-F./democa/cacert.pem] && OpenSSL req-utf8-new-x509-days 36500-newkey rsa:20 48-nodes-keyout./democa/private/cakey.pem-out./democa/cacert.pem-subj "/c=${c}/st=${st}/l=${l}/o=${o}/ou=${ou}/ Cn=${cn}/emailaddress=${emailaddress} "[!-F./democa/private/ca.crl] && OpenSSL ca-crldays 36500-gencrl-out" ./democa/private/ca.crl "
    • create_client_cert.sh

#!/bin/bash-eshow_help () {echo "$ [-h|-?| --HELP] [--ou ou] [--CN cn] [--email Email] "echo"-h|-?|         --help Display Help "echo"--ou set the organization or department name, such as: Technical department "echo"--CN set FQDN or owner name, such as: Feng Yu "echo"--email Set FQDN or owner mail, such as: fengyu@example.com "}while [[$#-gt 0]]do case $ in-h|-\?|        --HELP) show_help exit 0;;                --ou) ou= "${2}" shift;        --CN) cn= "${2}" shift;        --email) emailaddress= "${2}" shift;        --) shift break;; *) echo-e "Error: $ invalid option ' $ \ntry ' $--help ' for more information.\n" >&2 exit    1;; esacshiftdone# Create a client certificate # non-interactive Create the following: # Country name (2 letter code) c=cn# Province st=shannxi# City l=xian# Company name O=my company# Organization or department name ou=${ou:-Test Department}# Server FQDN or grant name cn=${cn:-demo}# e-mail address emailaddress=${emailaddress:-Demo@example.com}mkdir-p "${CN}" [!-F "${cn}/${cn}.key"] && OpenSSL req-utf8-nodes-newkey rsa:2048-keyout " ${cn}/${cn}.key "-new-days 36500-out" ${CN}/${CN}.CSR "-SUBJ"/c=${c}/st=${st}/l=${l}/o=${o}/ou=${ou}/cn=${cn}/ Emailaddress=${emailaddress} "[!-F" ${cn}/${cn}.crt "] && OpenSSL ca-utf8-batch-days 36500-in" ${cn}/${cn}.cs R "-out" ${CN}/${CN}.CRT "[!-F" ${CN}/${CN}.P12 "] && OpenSSL pkcs12-export-clcerts-capath./democa/-inkey" $ {Cn}/${cn}.key "-in" ${cn}/${cn}.crt "-certfile"./democa/cacert.pem "-passout Pass:-out" ${CN}/${CN}.P12 "
    • revoke_cert.sh

#!/bin/bash-e# revoke a visa over the certificate OpenSSL ca-revoke "${1}/${1}.CRT" OpenSSL ca-gencrl-out "./democa/private/ca.crl"

Simple analysis of a wave of scripts, the first is to create a CA, for Ubuntu system, the /etc/ssl/openssl.cnf default CA path in the configuration is ./demoCA , in order to not change the default configuration, directly follow the default configuration of the content to create these directories and files. There are a lot of OpenSSL subcommands, but as with git, you can combine commands, such as generating private keys and visa requests at the same time with a single command openssl req -nodes -newkey rsa:2048 -keyout client.key -new -out client.csr , at req the same time genrsa . Since the creation of the CA script is only a first-run requirement, it is time to write the certificate configuration directly to death in the script.

Next is to create a client certificate, in order to simplify the user's use, in the service side to help users to generate certificates and visas, the certificate issued to users to the visa. Because the user may be different departments, different names, different e-mail addresses, so the three parameters of the external, do a parameter resolution, plus friendly command line prompts to prevent forgetting. This script takes particular note of the last line and generates a PKCS12 certificate in a format. OpenSSL produces the default certificate format, which PEM separates the public key from the private key, but it needs to be merged to form when the browser is imported, 证书链 so you need to merge the certificate and the private key file into a single PKCS12 .p12 -format certificate, directly The format of the certificate is given to the user.

Finally, the revocation of the certificate, when you want to recover the access rights of a user, run the script directly to keep up with the directory name.

Next run the script that creates the CA:

./create_ca_cert.shgenerating a 2048 bit RSA private key.......................+++  ..... ..... ..... ..... ..... ..... ..... ....... ....... ......... ..... ..... ..... ..... ..... ..... ............ ........... +++writing New private key to './democa/private/cakey.pem '-----Using configuration from/usr/ssl/openssl.cnf

The resulting ./demoCA directory structure looks like this:

democa/├──cacert.pem├──crlnumber├──crlnumber.old├──index.txt├──newcerts├──private│   ├──ca.crl│   └── Cakey.pem└──serial2 directories, 7 files

Now you can configure Nginx, in the above one-way SSL configuration, append the following configuration:

  Ssl_client_certificate Ssl_certs/democa/cacert.pem;  SSL_CRL ssl_certs/democa/private/ca.crl;  Ssl_verify_client on;

ssl_client_certificateis the CA certificate of the client certificate, the certificate issued on behalf of this CA is trusted, on behalf of the ssl_verify_client on; mandatory client authentication, the illegal client (no certificate, the certificate is not trustworthy) will return 400 error.

Pay special attention ssl_crl to this configuration, on behalf of Nginx will read a CRL (Certificate Revoke List) file, previously said that there may be a need to recover user rights, so we must have the ability to revoke the certificate, Generate a CRL file to let Nginx know which certificates have been revoked.

Note : The Nginx configuration is static and will be loaded into memory after reading the configuration file, even if the contents of the file are not re-read. Therefore, when the CRL file changes, Nginx will not be aware that a new certificate has been revoked, so you must use the reload instructions to let Nginx reread the configuration file: service nginx reload or nginx -s reload

Restart the Nginx service at this time, you can complete the SSL two-way authentication configuration.

We issue a certificate to see:

 ./create_client_cert.sh--ou Finance Department--CN finance manager--email cy@example.comgenerating a 2048 bit RSA private key ...... ..... ....... +++.............................................................................+++writing New Private key to ' finance manager/Finance manager. Key '-----Using configuration from/usr/ssl/openssl.cnfcheck that the request matches the Signatu Resignature okcertificate details:serial number:1 (0x1) validity not Before:jun 14 16:03:46 20            GMT not after:may 16:03:46 2118 GMT subject:countryname = CN    Stateorprovincename = Shannxi OrganizationName = My company Organizationalunitname              = \u8d22\u52a1\u90e8 CommonName = \u8d22\u52a1\u7ecf\u7406 EmailAddress = cy@example.com x509v3 extensions:x509v3 Basic Constraints:CA:FALSE Nets Cape Comment:openssl Generated Certificate x509v3 Subject Key identifier:b5:91:0b:1f:fc:25:3b:2a:f9:ef:39:39:51:e3:1f : 64:78:8a:c3:75 x509v3 Authority Key IDENTIFIER:KEYID:86:55:76:15:A3:F5:58:CB:8F:39:A3:56:8E:FF : 18:97:ae:27:60:0fcertificate is to being certified until May 16:03:46 2118 GMT (36500 days) Write out database with 1 new Entriesdata Base Updatedtree Finance Manager/Finance Manager/├── Finance manager crt├── Finance manager csr├── Finance manager key└── finance manager p120 directories, 4 files

This script generates a private key file key , a visa request file csr , a certificate file after the CA Visa crt (there is no private key inside), and a certificate file in the format of the bundle of CRT files and keys, to download the PKCS12 p12 p12 file locally, Double-click the next import certificate.

Note : Because the CA's certificate file does not change, the visa new client certificate does not require restart or reload Nginx

This time to open our website https://www.example.com , the browser will prompt us to choose an existing client certificate for authentication, no problem can see the content of the site

Note : Each time you import a new certificate, you must restart your browser to prompt for the new certificate file

In this way, how many people need authorization, you can use this script to issue how many such certificates, the user will p12 import the certificate locally can access the site normally.

When we need to reclaim someone's authority (such as leaving the office), we need to revoke his certificate:

./revoke_cert.sh finance Manager using configuration from/usr/ssl/openssl.cnfrevoking Certificate 01.Data Base updatedusing Configuration From/usr/ssl/openssl.cnfservice Nginx Reload

This script will automatically revoke his visa file crt and automatically update the CRL file. Pay special attention to reload or restart Nginx to allow Nginx to reload the CRL. The revoked certificate will not be able to access the site.

Summary

In this paper, we use the Nginx configuration SSL two-way authentication to the client encryption authentication, we used a simple script to help us quickly generate a variety of certificates and visas, eliminating the memory cumbersome OpenSSL command line, simplified use.

This is, of course, a minimum available set, and many improvements may be required when the scale is large, such as a Web UI that joins a CA, direct operation of visas and revocation of certificates, and the ability to automatically restart Nginx.

Again such as the CRL this static configuration file is not suitable for your scene, the hope of Dynamic Update revocation certificate list, you can consider the OCSP scheme, this nginx is also supported by the Ssl_stapling_responder configuration to specify an OCSP address, This will not require each revocation of the certificate at the time to restart Nginx, OpenSSL also provides the functionality of the OCSP server, here will not repeat, you can find the relevant information.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.