Configure SSL for nginx to implement two-way server/Client Authentication

Source: Internet
Author: User
Tags openssl x509 pkcs12 syslog nginx server nginx ssl

After two days of configuration, I finally came up with it. In combination with many blog posts on the internet, I would like to summarize it!

Configuration environment:

Ubuntu 11.04

PCRE 8.31

OpenSSL 2.0.2

Nginx 1.2.5

To make sure that you can use regular expressions in nginx for more flexible configuration, You need to determine whether the PCRE (Perl Compatible Regular Expressions) package is installed in the system before installation. Can go to ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/
Download the latest PCRE source code package. Use the following command to download and compile the PCRE package:

# wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.31.tar.bz2# tar jxvf pcre-8.31.tar.bz2# cd pcre-8.31# ./configure –enable-utf8# make# make install

OpenSSL is an open-source software that creates a simple CA in Linux (or UNIX/cygwin. We can use this ca to test PKI and digital certificates. For example, in the test of using tomcat or Apache to build HTTPS two-way authentication, we can use our own test CA to Issue Server digital certificates to the server, and provide the client (browser) generate a digital certificate in file format (you can use OpenSSL to generate the client private key at the same time). The installation method is similar to the above.

The following describes how to install nginx:

Download the latest stable version 1.2.5 and run the following command:

# Tar zxvf nginx-1.2.5.tar.gz # D nginx-1.2.5 #. /configure -- prefix =/usr -- sbin-Path =/usr/sbin/nginx -- conf-Path =/etc/nginx. conf -- error-log-Path =/var/log/nginx/error. log -- PID-Path =/var/run/nginx. PID -- lock-Path =/var/lock/nginx. lock -- user = www-nginx -- group = WWW -- with-http_ssl_module -- with-http_stub_status_module -- with-http_flv_module -- with-http_gzip_static_module -- http-log-Path =/var/log/nginx/access. log -- http-client-body-temp-Path =/var/tmp/nginx/client/-- http-proxy-temp-Path =/var/tmp/nginx/Proxy /-- HTTP-FastCGI-temp-Path =/var/tmp/nginx/fcgi/# simple installation. /configure -- prefix =/opt/nginx -- with-http_stub_status_module -- with-http_ssl_module # Make # make install

Note: When using "-- prefix" and other configuration items, the front is two horizontal "--", rather than "-". Some blog posts did not notice this, causing me to be dizzy for a long time.

-- The with-http_stub_status_module is used to enable nginx's nginxstatus function to monitor the current state of nginx.
-- With-http_ssl_module enables the http_ssl Module
-- With-ipv6 supports IPv6

After the installation is successful, the/opt/nginx directory contains four subdirectories: Conf, HTML, logs, and sbin. The nginx configuration file is stored in CONF/nginx. conf, and nginx only has one program file in the sbin directory. Make sure that port 80 of the system is not occupied by other programs. Run the sbin/./nginx command to start nginx and open the browser to access the IP address of the machine. If the browser displays welcome to nginx! Nginx has been installed and runs successfully.

Note: here we use the sbin/./nginx command to start it because if I start it with the sbin/nginx mentioned on the internet, it cannot be started at all, and the prompt for installing nginx will appear, which is strange!

Use OpenSSL to create a certificate:

1. One-way server Verification

Create and enter the sslkey storage directory

# Mkdir/opt/nginx/sslkey

# Cd/opt/nginx/sslkey

① Generate an RSA key:

# OpenSSL genrsa-out key. pem 2048

② Generate a certificate request

# OpenSSL req-New-Key key. pem-out cert. CSR

# // The system will prompt you to enter the province, city, domain name information, etc. What's important is that email must be your domain name suffix. You can take this file to the Digital Certificate Authority (CA) apply for a digital certificate. CA will give you a new file cacert. Pem, which is your digital certificate.

If you do the test on your own, you can use the following command to generate the certificate:

# OpenSSL req-New-X509-nodes-out server. CRT-keyout server. Key

③ Modify nginx Configuration

# HTTPS server#server {listen 443;server_name localhost;ssl on;ssl_certificate /opt/nginx/sslkey/server.crt;ssl_certificate_key /opt/nginx/sslkey/server.key;ssl_session_timeout 5m;ssl_protocols SSLv2 SSLv3 TLSv1;ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;ssl_prefer_server_ciphers on;location / {    root /home/workspace/;    index index.asp index.aspx;       }}

After configuration, restart nginx and Use https to open the website. the browser will prompt a certificate error and click Continue browsing.

2. Server-client two-way Verification

Create a ca folder in the nginx directory and enter ca.

#
Mkdir newcerts private conf server.

The newcerts subdirectory stores the digital certificates (certificate Backup Directory) signed (issued) by the CA ). The private directory is used to store the private key of the CA. The directory conf is only used to store some simplified parameters.

The configuration file used by the server to store the server certificate file.

① Create the OpenSSL. conf configuration file in the conf directory. The content is as follows:

[ ca ]default_ca      = foo                   # The default ca section [ foo ]dir            = /opt/nginx/ca         # top dirdatabase       = /opt/nginx/ca/index.txt          # index file.new_certs_dir  = /opt/nginx/ca/newcerts           # new certs dir certificate    = /opt/nginx/ca/private/ca.crt         # The CA certserial         = /opt/nginx/ca/serial             # serial no fileprivate_key    = /opt/nginx/ca/private/ca.key  # CA private keyRANDFILE       =/opt/nginx/ca/private/.rand      # random number file default_days   = 365                     # how long to certify fordefault_crl_days= 30                     # how long before next CRLdefault_md     = md5                     # message digest method to useunique_subject = no                      # Set to 'no' to allow creation of                                         # several ctificates with same subject.policy         = policy_any              # default policy [ policy_any ]countryName = matchstateOrProvinceName = matchorganizationName = matchorganizationalUnitName = matchlocalityName            = optionalcommonName              = suppliedemailAddress            = optional

Note: You can also directly modify the OpenSSL configuration file, so that you do not need to reference this configuration file in the code that creates the certificate later.

② Use scripts to create certificates

The following scripts are stored in the/nginx/CA/directory.

Create a new CA root certificate.

New_ca.sh:

#!/bin/sh# Generate the key.openssl genrsa -out private/ca.key# Generate a certificate request.openssl req -new -key private/ca.key -out private/ca.csr# Self signing key is bad... this could work with a third party signed key... registeryfly has them on for $16 but I'm too cheap lazy to get one on a lark.# I'm also not 100% sure if any old certificate will work or if you have to buy a special one that you can sign with. I could investigate further but since this# service will never see the light of an unencrypted Internet see the cheap and lazy remark.# So self sign our root key.openssl x509 -req -days 365 -in private/ca.csr -signkey private/ca.key -out private/ca.crt# Setup the first serial number for our keys... can be any 4 digit hex string... not sure if there are broader bounds but everything I've seen uses 4 digits.echo FACE > serial# Create the CA's key database.touch index.txt# Create a Certificate Revocation list for removing 'user certificates.'openssl ca -gencrl -out /opt/nginx/ca/private/ca.crl -crldays 7 -config "/opt/nginx/ca/conf/openssl.conf"

Execute sh new_ca.sh to generate a new CA certificate.

Generate the script for the server certificate.

New_server.sh:

# Create us a key. Don't bother putting a password on it since you will need it to start apache. If you have a better work around I'd love to hear it.openssl genrsa -out server/server.key# Take our key and create a Certificate Signing Request for it.openssl req -new -key server/server.key -out server/server.csr# Sign this bastard key with our bastard CA key.openssl ca -in server/server.csr -cert private/ca.crt -keyfile private/ca.key -out server/server.crt -config "/opt/nginx/ca/conf/openssl.conf"

Execute sh new_server.sh to generate the certificate for the new server

Configure nginx SSL support:

# User www-nginx; worker_processes 1; # error_log logs/error. log; # error_log logs/error. log notice; # error_log logs/error. log Info; # PID logs/nginx. PID; events {worker_connections 1024;} HTTP {include mime. types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; # gzip on; # https server # server {Listen 443; SERVER_NAME localhost; SSI on; ssi_silent_errors on; ssi_types text/shtml; SSL on; ssl_certificate/opt/nginx/CA/Server/server. CRT; ssl_certificate_key/opt/nginx/CA/Server/server. key; ssl_client_certificate/opt/nginx/CA/private/CA. CRT; ssl_session_timeout 5 m; ssl_verify_client on; # verify ssl_protocols SSLv2 SSLv3 tlsv1; ssl_ciphers all :! ADH :! Export56: RC4 + RSA: + high: + medium: + low: + SSLv2: + exp; ssl_prefer_server_ciphers on; Location/{root/home/workspace/; Index. ASP index. aspx ;}}}

Start nginx and wait for the client to connect. If you connect to the server at this time, the error 400 bad request certification will be prompted. Therefore, you need to generate a client certificate.

New_user.sh:

#!/bin/sh# The base of where our SSL stuff lives.base="/opt/nginx/ca"# Were we would like to store keys... in this case we take the username given to us and store everything there.mkdir -p $base/users/# Let's create us a key for this user... yeah not sure why people want to use DES3 but at least let's make us a nice big key.openssl genrsa -des3 -out $base/users/client.key 1024# Create a Certificate Signing Request for said key.openssl req -new -key $base/users/client.key -out $base/users/client.csr# Sign the key with our CA's key and cert and create the user's certificate out of it.openssl ca -in $base/users/client.csr -cert $base/private/ca.crt -keyfile $base/private/ca.key -out $base/users/client.crt -config "/opt/nginx/ca/conf/openssl.conf"# This is the tricky bit... convert the certificate into a form that most browsers will understand PKCS12 to be specific.# The export password is the password used for the browser to extract the bits it needs and insert the key into the user's keychain.# Take the same precaution with the export password that would take with any other password based authentication scheme.openssl pkcs12 -export -clcerts -in $base/users/client.crt -inkey $base/users/client.key -out $base/users/client.p12 

Run shnew_user.sh to generate a client certificate.
Follow the prompts to make sure that the items of the client certificate match the root certificate.
That is, the preceding Configuration:
Countryname = match
Stateorprovincename = match
Organizationname = match
Organizationalunitname = match

Otherwise, the final customer certificate cannot be generated. After the certificate is generated, the client can open the website by importing the certificate browser.

Note:

1. When creating a certificate, you will be prompted to enter the password. The password of the server certificate and client certificate may be different.

2. When the server certificate and client certificate are created, the system prompts you to enter the province, city, domain name information, and so on. The information must be consistent.

3. ssi is not enabled for nginx by default. The above configuration is enabled.

4. nginx cannot be started by itself. The following configuration is required:

cd /etc/init.d  sudo touch nginx  sudo chmod +x nginx 

Nginx content:

#! /bin/sh#### BEGIN INIT INFO# Provides:          nginx# Required-Start:    $syslog $local_fs $remote_fs# Required-Stop:     $syslog $local_fs $remote_fs# Should-Start:      dbus avahi# Should-Stop:       dbus avahi# Default-Start:     2 3 4 5# Default-Stop:      1# Short-Description: Nginx Server# Description:       Nginx### END INIT INFOPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/nginx/sbinDAEMON=/opt/nginx/sbin/nginxNAME=nginxDESC="Nginx Server"PID_FILE=/opt/nginx/logs/nginx.pidtest -x $DAEMON || exit 0RUN=yes#RUN_AS_USER=root#DAEMON_OPTS="-a $RUN_AS_USER"set -ecase "$1" in  start)echo -n "Starting $DESC: "start-stop-daemon --start --quiet --pidfile $PID_FILE \--exec $DAEMONecho "$NAME.";;  stop)echo -n "Stopping $DESC: "start-stop-daemon --stop --oknodo --quiet --pidfile $PID_FILE \--exec $DAEMONecho "$NAME.";;  force-reload)# check whether $DAEMON is running. If so, restartstart-stop-daemon --stop --test --quiet --pidfile \$PID_FILE --exec $DAEMON \&& $0 restart \|| exit 0;;  restart)echo -n "Restarting $DESC: "start-stop-daemon --stop --oknodo --quiet --pidfile \$PID_FILE --exec $DAEMONsleep 1start-stop-daemon --start --quiet --pidfile \$PID_FILE --exec $DAEMONecho "$NAME.";;  status)if [ -s $PID_FILE ]; then            RUNNING=$(cat $PID_FILE)            if [ -d /proc/$RUNNING ]; then                if [ $(readlink /proc/$RUNNING/exe) = $DAEMON ]; then                    echo "$NAME is running."                    exit 0                fi            fi            # No such PID, or executables don't match            echo "$NAME is not running, but pidfile existed."            rm $PID_FILE            exit 1        else            rm -f $PID_FILE            echo "$NAME not running."            exit 1        fi;;  *)N=/etc/init.d/$NAMEecho "Usage: $N {start|stop|restart|force-reload}" >&2exit 1;;esacexit 0

Set auto-start:

sudo chkconfig --list nginx  sudo chkconfig nginx on 

 

Author:Kunoy Source:Http://blog.csdn.net/kunoy Statement:The authors write blogs to sum up experience and exchange learning.
If you need to reprint the statement, please keep it as much as possible and provide the original article connection clearly on the article page. Thank you!

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.