Graphics: CentOS + Tomcat configuration SSL for server/client two-way authentication

Source: Internet
Author: User
Tags modulus openssl library openssl x509 pkcs12 nginx server


1. Install nginx1.1 Nginx Package and its dependent package download for module dependencies, Nginx relies on the following three packages:
    • Gzip module requires zlib library (http://www.zlib.net/);
    • Rewrite module requires Pcre library (http://www.pcre.org/);
    • The SSL feature requires the OpenSSL library (http://www.openssl.org/);
Download their latest stable version (as of the latest stable version of this article is zlib-1.2.8.tar.gz, pcre-8.36.tar.gz, openssl-fips-2.0.9.tar.gz), and finally download Nginx latest (HTTP// nginx.org/en/download.html) stable version (as of the latest stable version of this article is nginx-1.7.10.tar.gz).
The dependent packages are installed in the following order: OpenSSL, Zlib, Pcre, and finally the Nginx package is installed.
1.2 Nginx package and its dependent package installation 1.2.1 installation OpenSSL $ tar-zxvf openssl-fips-2.0.9.tar.gz
$ CD openssl-fips-2.0.9
$./config
$ make
$ sudo make install

1.2.2 Installation Zlib $ TAR-ZXVF zlib-1.2.8.tar.gz
$ CD zlib-1.2.8
$./configure
$ make
$ sudo make install

1.2.3 Installation Pcre $ tar-zxvf pcre-8.36.tar.gz
$ CD pcre-8.36
$./configure
$ make
$ sudo make install

1.2.4 Installing Nginx $ tar-zxvf nginx-1.7.10.tar.gz
$ CD nginx-1.7.10
$./configure--with-pcre=. /pcre-8.36--with-zlib=. /zlib-1.2.8--with-openssl=. /openssl-fips-2.0.9
$ make
$ sudo make install

Nginx is installed by default in the/usr/local/nginx directory.
1.3 Verify the Nginx installation is successful $ sudo/usr/local/nginx/sbin/nginx-t
Nginx:the configuration file/usr/local/nginx/conf/nginx.conf syntax is OK
Nginx:configuration file/usr/local/nginx/conf/nginx.conf test is successful


Prove that Nginx installation is successful.





2. SSL Server/Client Two-way authentication Certificate Generation 2.1 Create a new CA root certificate in the Nginx installation directory under the new CA folder, enter the CA and create several subfolders:
$ sudo mkdir CA
$ CD CA
$ sudo mkdir newcerts private conf server

The Newcerts subdirectory will be used to hold the CA-signed digital certificate (certificate backup directory), private to hold the CA's private key, and the Conf directory to hold some configuration files for simplified parameters;
2.1.1 Conf directory new openssl.conf file edit its contents as follows:
[ ca ]
default_ca      = foo                   # The default ca section
[ foo ]
dir            = /usr/local/nginx/ca         # top dir
database       = /usr/local/nginx/ca/index.txt          # index file.
new_certs_dir  = /usr/local/nginx/ca/newcerts           # new certs dir
certificate    = /usr/local/nginx/ca/private/ca.crt         # The CA cert
serial         = /usr/local/nginx/ca/serial             # serial no file
private_key    = /usr/local/nginx/ca/private/ca.key  # CA private key
RANDFILE       = /usr/local/nginx/ca/private/.rand      # random number file
default_days   = 365                     # how long to certify for
default_crl_days= 30                     # how long before next CRL
default_md     = md5                     # message digest method to use
unique_subject = no                      # Set to ‘no‘ to allow creation of
                                         # several ctificates with same subject.
policy         = policy_any              # default policy
[ policy_any ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = match
localityName            = optional
commonName              = supplied
emailAddress            = optional

2.1.2 Generating the private key key file $ cd/usr/local/nginx/ca
$ sudo openssl genrsa-out private/ca.key

Output
generating RSA private key, modulus bit long
.. ++++++++++++
.++++++++++++
E is 65537 (0x10001)
The private directory has the Ca.key file generated.
2.1.3 Generate a certificate request CSR file $ sudo openssl req-new-key private/ca.key-out PRIVATE/CA.CSR

Prompt to enter country Name, enter CN and return:

Prompt for state or province name (full name), enter Shanghai and return:

Prompt to enter Locality Name, enter Shanghai and return:

Prompt to enter Organization Name, enter defonds and return:

Tip Enter Organizational Unit Name, enter Dev and enter after:

Prompt to enter Common name, if there is no domain name, enter localhost and return:


Prompt to enter email Address, enter [email protected] and return:






Prompt for A challenge password, enter defonds and return:



Tip Enter an optional company name, enter DF and return. The private directory has the CA.CSR file generated.
2.1.4 Generating a voucher CRT file $ sudo openssl x509-req-days 365-in private/ca.csr-signkey private/ca.key-out private/ca.crt
Console output
Signature OK
Subject=/c=cn/st=shanghai/l=shanghai/o=defonds/ou=dev/cn=localhost/[email protected]
Getting Private Key
The private directory has the Ca.crt file generated.
2.1.5 Set the starting serial number for our key $ sudo echo face > Serial
Can be any of four characters
2.1.6 Creating the CA key Library $ sudo touch index.txt
2.1.7 Create a certificate revocation list for "User certificate" removal $ sudo openssl ca-gencrl-out/usr/local/nginx/ca/private/ca.crl-crldays 7-config "/usr/local/nginx/ca/conf/ Openssl.conf "
Output
Using Configuration from/usr/local/nginx/ca/conf/openssl.conf
The private directory has the Ca.crl file generated.
2.2 Generation of server certificates 2.2.1 Create a key $ sudo openssl genrsa-out server/server.key
Output
generating RSA private key, modulus bit long
...........................++++++++++++
.................++++++++++++
E is 65537 (0x10001)
The server directory has Server.key file generation.
2.2.2 Create a Certificate signing request CSR file for our key $ sudo openssl req-new-key server/server.key-out SERVER/SERVER.CSR
You will be asked to enter the same questions as 2.1.2.2 Steps. The input needs to be consistent with that step:

The server directory has SERVER.CSR file generation.
2.2.3 using our private CA key to sign just the key $ sudo openssl ca-in server/server.csr-cert private/ca.crt-keyfile private/ca.key-out server/server.crt-config "/ Usr/local/nginx/ca/conf/openssl.conf "
Output

Both enter the Y,server directory with the Server.crt file generated.
2.3 Build of the client certificate 2.3.1 Create the directory that holds the key users $ sudo mkdir users
Location/usr/local/nginx/ca/users.
2.3.2 Create a key for the user $ sudo openssl genrsa-des3-out/usr/local/nginx/ca/users/client.key 1024x768

Required to enter pass phrase. Two times Enter the same password (for example I enter Defonds here), the Users directory has Client.key file generation.
2.3.3 Create a Certificate signing request CSR file for key $ sudo openssl req-new-key/usr/local/nginx/ca/users/client.key-out/usr/local/nginx/ca/users/client.csr

Prompt for pass phrase, 2.3.2 steps to save the pass phrase input and enter:

Ask you to enter the same questions as 2.1.2.2 Steps. The input needs to be consistent with that step:

You are required to enter the certificate password, which can be consistent with the server certificate, such as the Defonds,users directory under the CLIENT.CSR file generation.
2.3.4 using our private CA key to sign just the key $ sudo OpenSSL ca-in/usr/local/nginx/ca/users/client.csr-cert/usr/local/nginx/ca/private/ca.crt-keyfile/usr/ Local/nginx/ca/private/ca.key-out/usr/local/nginx/ca/users/client.crt-config "/usr/local/nginx/ca/conf/ Openssl.conf "
Output
Using Configuration from/usr/local/nginx/ca/conf/openssl.conf
Check that the request matches the signature
Signature OK
The Subject ' s distinguished Name is as follows
CountryName:P rintable: ' CN '
Stateorprovincename:P rintable: ' Shanghai '
Localityname:P rintable: ' Shanghai '
OrganizationName:P rintable: ' Defonds '
Organizationalunitname:printable: ' Dev '
CommonName:P rintable: ' localhost '
emailaddress:ia5string: ' [email protected] '
Certificate is to be certified until Mar 11:47:48 GMT (365 days)
Sign the certificate? [Y/n]:y

1 out of 1 certificate requests certified, commit? [Y/n]y
Write out database with 1 new entries
Data Base Updated
Both enter the Y,users directory with the Client.crt file generated.
2.3.5 Convert certificates to PKCS12 files that most browsers can recognize $ sudo openssl pkcs12-export-clcerts-in/usr/local/nginx/ca/users/client.crt-inkey/u Sr/local/nginx/ca/users/client.key-out/usr/local/nginx/ca/users/client.p12

Ask for input Client.key pass phrase, enter 2.3.2 Step input Pass phrase and enter after:


Required to enter Export Password, this is the client certificate protection password, the client will need to enter this password when installing the certificate. I'm still typing in the defonds. The Client.p12 file is generated under the users directory.





3. Nginx configuration SSL is designed to ensure the security of network communication and data integrity. So, if there is nginx in front of Tomcat as a reverse proxy, there is no reason to encrypt the transmission between Nginx and Tomcat, after all, they are in the same intranet.

As shown, the client's access over SSL requests is received by the reverse proxy nginx, and Nginx ends the SSL and submits the request to Tomcat in pure HTTP. The Nginx configuration nginx.conf is as follows:
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;

    log_format  main  ‘[$time_local] $remote_addr - "$request" ‘
                      ‘$status "$http_user_agent" ‘
                      ‘"$args"‘;

    access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  120;
    client_max_body_size    120m;
    client_body_buffer_size 128k;
    server_names_hash_bucket_size 128;
    large_client_header_buffers 4 4k;
    open_file_cache max=8192 inactive=20s;
    open_file_cache_min_uses 1;
    open_file_cache_valid 30s;

	upstream tomcat_server {
	# Tomcat is listening on default 8080 port
        server 192.168.1.177:8080 fail_timeout=0;
    }

    server {
        listen       443;
        server_name  localhost;
        ssi on;
        ssi_silent_errors on;
        ssi_types text/shtml;

        ssl                  on;
        ssl_certificate      /usr/local/nginx/ca/server/server.crt;
        ssl_certificate_key  /usr/local/nginx/ca/server/server.key;
        ssl_client_certificate /usr/local/nginx/ca/private/ca.crt;

        ssl_session_timeout  5m;
        ssl_verify_client on;  #开户客户端证书验证

        ssl_protocols  SSLv2 SSLv3 TLSv1;
        ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        ssl_prefer_server_ciphers   on;
        
        charset utf-8;
		access_log  logs/host.access.log  main;

		#error_page  404              /404.html;

		# redirect server error pages to the static page /50x.html
		#

		error_page   500 502 503 504  /50x.html;
		location = /50x.html {
				root   html;
		}
		location = /favicon.ico {
				log_not_found off;
				access_log off;
				expires      90d;
		}
		location /swifton/ {
				proxy_pass http://tomcat_server;
				include proxy.conf;
		}      

    }
}


where Tomcat (in this case and Nginx) is the same LAN segment, Swifton is testing the Tomcat project. Proxy.conf content:





proxy_redirect   off;
proxy_set_header   Host             $host;
proxy_set_header   X-Real-IP        $remote_addr;
proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
proxy_connect_timeout 60;
proxy_read_timeout 600;
proxy_set_header   X-Forwarded-Proto $scheme;







4. The tomcat configuration differs from the HTTP proxy in that it is necessary to tell the previous proxy by changing the tomcat configuration file. The following sections will be%tomcat%/conf/:
  <Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />

Revision changed to
<Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443"
			   scheme="https"
			   proxyName="localhost"
			   proxyPort="443" />







5. Configure authentication 5.1 Tomcat reboot verify reboot tomcat, background log no problem, you can also see the kitten interface.
5.2 Nginx Restart Verify that the operating nginx is closed first, if you have already turned on.
$ sudo./nginx-t
Output
nginx: [Emerg] unknown directive "SSL" in/usr/local/nginx/conf/nginx.conf:50
Nginx:configuration file/usr/local/nginx/conf/nginx.conf Test Failed
The SSL module is not compiled in.
Switch to the Nginx installation directory in step 1.2.4 nginx-1.7.10,
$./configure--with-pcre=. /pcre-8.36--with-zlib=. /zlib-1.2.8--with-http_ssl_module
$ sudo make
$ sudo make install

Nginx re-installed successfully. Again
$ sudo./nginx-t
Prompt for test success.
Start Nginx.
5.3 Client Access SSL authentication Google Chrome access to the original project using HTTPS https://192.168.1.177/swifton,177 is the Nginx server, prompted by the bad Request (No required SSL cer Tificate was sent):

This is because HTTPS bidirectional authentication requires a client installation certificate. Under Windows OS get the step 2.3.5 generated certificate CLIENT.P12, double-click it directly and go to the Certificate Import Wizard:

Click "Next":

"File to import" has been selected for us, click "Next":

Private key Protection dialog box, enter 2.3.5 Steps of Export Password, click "Next":

Certificate Store dialog box, we use Windows automatic storage and click Next:

Click the "Finish" button to complete the certificate import.
Restart Google Browser, visit Https://192.168.1.177/swifton again, the browser asks us to select the certificate:

Select the certificate you just installed (localhost) and click "OK" to prompt "Privacy settings error":

This is because our server is using a certificate issued by itself. Choose to continue to visit, keep the cloud open to see the moon, finally see a long-lost project landing page, success:

Click the small lock icon on the left side of the browser's input box to view information about the client certificate we have imported:


CentOS + Tomcat configuration SSL for server/client two-way authentication, this concludes. The examples in this article cover installation packages openssl-fips-2.0.9.tar.gz, pcre-8.36.tar.gz, zlib-1.2.8.tar.gz, nginx-1.7.10.tar.gz,nginx configuration Files nginx.conf , proxy.conf, and Tomcat profile Server.xml have been packaged as blog attachments uploaded to CSDN resources, interested friends can go to download down reference,: Http://download.csdn.net/detail/defonds /8512071.





Resources
    • http://webapp.org.ua/sysadmin/setting-up-nginx-ssl-reverse-proxy-for-tomcat/
    • Http://serverfault.com/questions/172542/configuring-nginx-for-use-with-tomcat-and-ssl


Graphics: CentOS + Tomcat configuration SSL for server/client two-way authentication



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.