• nginx配置SSL实现服务器/客户端双向认证


    http://blog.csdn.net/kunoy/article/details/8239653


        本人不才,配置了两天,终于搞出来了,结合网上诸多博文,特此总结一下!

    配置环境:

          Ubuntu 11.04

         PCRE 8.31

         Openssl 2.0.2

         Nginx 1.2.5

        为了确保能在 nginx中使用正则表达式进行更灵活的配置,安装之前需要确定系统是否安装有 PCREPerl Compatible Regular Expressions)包。可以到ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ 下载最新的 PCRE 源码包,使用下面命令下载编译和安装 PCRE 包:

    [html] view plaincopy
    1. # wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.31.tar.bz2  
    2. # tar jxvf pcre-8.31.tar.bz2  
    3. # cd pcre-8.31  
    4. # ./configure –enable-utf8  
    5. # make  
    6. # make install  

            openssl为开源软件,在Linux(或UNIX/Cygwin)下创建一个简单的CA。我们可以利用这个CA进行PKI、数字证书相关的测试。比如,在测试用Tomcat或Apache构建HTTPS双向认证时,我们可以利用自己建立的测试CA来为服务器端颁发服务器数字证书,为客户端(浏览器)生成文件形式的数字证书(可以同时利用openssl生成客户端私钥),安装方法和上面类似。

           下面重点说说nginx的安装方法:

            下载最新稳定版本1.2.5,使用命令:

    [html] view plaincopy
    1. # tar zxvf nginx-1.2.5.tar.gz  
    2. # cd nginx-1.2.5  
    3. # ./configure  
    4. --prefix=/usr  
    5. --sbin-path=/usr/sbin/nginx  
    6. --conf-path=/etc/nginx/nginx.conf  
    7. --error-log-path=/var/log/nginx/error.log  
    8. --pid-path=/var/run/nginx/nginx.pid  
    9. --lock-path=/var/lock/nginx.lock  
    10. --user=www-nginx  
    11. --group=www  
    12. --with-http_ssl_module  
    13. --with-http_stub_status_module  
    14. --with-http_flv_module  
    15. --with-http_gzip_static_module  
    16. --http-log-path=/var/log/nginx/access.log  
    17. --http-client-body-temp-path=/var/tmp/nginx/client/  
    18. --http-proxy-temp-path=/var/tmp/nginx/proxy/  
    19. --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/  
    20. # 简单安装 ./configure --prefix=/opt/nginx --with-http_stub_status_module --with-http_ssl_module  
    21. # make  
    22. # make install  

          注意:在使用"--prefix"等配置项时,前面是两横"--",而不是"-",这里有些博文根本没注意到,害得我晕了半天。    

          --with-http_stub_status_module 是为了启用 nginx 的 NginxStatus 功能,用来监控 nginx 的当前状态。
          --with-http_ssl_module 启用http_ssl模块
          --with-ipv6 支持ipv6

           安装成功后 /opt/nginx 目录下有四个子目录分别是:conf、html、logs、sbin 。其中 nginx 的配置文件存放于 conf/nginx.conf,nginx 只有一个程序文件位于 sbin 目录下。确保系统的 80 端口没被其他程序占用,运行 sbin/./nginx 命令来启动 Nginx,打开浏览器访问此机器的 IP,如果浏览器出现 Welcome to nginx! 则表示 nginx 已经安装并运行成功。

           注:此处采用sbin/./nginx命令启动是因为我这里如果用网上说的sbin/nginx启动的话,根本启动不了,而且会出现安装nginx的提示,很怪!

    使用openssl制作证书:

        1、服务器单向验证

        创建并进入sslkey存放目录

           # mkdir /opt/nginx/sslkey

           # cd /opt/nginx/sslkey

        ①、生成RSA密钥:

           # openssl genrsa -out key.pem 2048

        ②、生成一个证书请求

           # openssl req -new -key key.pem -out cert.csr

           # //会提示输入省份、城市、域名信息等,重要的是,email 一定要是你的域名后缀的你可以拿着这个文件去数字证书颁发机构(即CA)申请一个数字证书。CA会给你一个新的文件cacert.pem,那才是你的数字证书。

        如果是自己做测试,就可以用下面这个命令来生成证书:

           # openssl req -new -x509 -nodes -out server.crt -keyout server.key

        ③、修改 nginx 配置

    [html] view plaincopy
    1. # HTTPS server  
    2. #  
    3. server {  
    4. listen 443;  
    5. server_name localhost;  
    6.   
    7. ssl on;  
    8. ssl_certificate /opt/nginx/sslkey/server.crt;  
    9. ssl_certificate_key /opt/nginx/sslkey/server.key;  
    10.   
    11. ssl_session_timeout 5m;  
    12.   
    13. ssl_protocols SSLv2 SSLv3 TLSv1;  
    14. ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;  
    15. ssl_prefer_server_ciphers on;  
    16.   
    17. location / {      
    18.         root /home/workspace/;      
    19.         index index.asp index.aspx;         
    20.     }  
    21. }  

       配置好后,重启nginx,采用 https打开网站,浏览器会提示证书错误,点击继续浏览即可。

       2、服务器-客户端双向验证

       在nginx 目录下建立ca文件夹,进入ca。

            # mkdir newcerts private conf server

       其中newcerts子目录将存放CA签署(颁发)过的数字证书(证书备份目录)。而private目录用于存放CA的私钥。目录conf只是用于存放一些简化参数

    用的配置文件,server存放服务器证书文件。

       ①、conf目录创建文件openssl.conf配置文件,内容如下:

    [html] view plaincopy
    1. [ ca ]  
    2. default_ca      = foo                   # The default ca section  
    3.    
    4. [ foo ]  
    5. dir            = /opt/nginx/ca         # top dir  
    6. database       = /opt/nginx/ca/index.txt          # index file.  
    7. new_certs_dir  = /opt/nginx/ca/newcerts           # new certs dir  
    8.    
    9. certificate    = /opt/nginx/ca/private/ca.crt         # The CA cert  
    10. serial         = /opt/nginx/ca/serial             # serial no file  
    11. private_key    = /opt/nginx/ca/private/ca.key  # CA private key  
    12. RANDFILE       =/opt/nginx/ca/private/.rand      # random number file  
    13.    
    14. default_days   = 365                     # how long to certify for  
    15. default_crl_days30                     # how long before next CRL  
    16. default_md     = md5                     # message digest method to use  
    17. unique_subject = no                      # Set to 'no' to allow creation of  
    18.                                          # several ctificates with same subject.  
    19. policy         = policy_any              # default policy  
    20.    
    21. [ policy_any ]  
    22. countryName = match  
    23. stateOrProvinceName = match  
    24. organizationName = match  
    25. organizationalUnitName = match  
    26. localityName            = optional  
    27. commonName              = supplied  
    28. emailAddress            = optional  

            注:你也可以直接修改openssl的配置文件,这样的话后面制作证书的代码中就不用引用这个配置文件了。

       ②、使用脚本创建证书

       下面的几个脚本都放在/nginx/ca/目录下。

       创建一个新的CA根证书。

    new_ca.sh:

    [html] view plaincopy
    1. #!/bin/sh  
    2. # Generate the key.  
    3. openssl genrsa -out private/ca.key  
    4. # Generate a certificate request.  
    5. openssl req -new -key private/ca.key -out private/ca.csr  
    6. # 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.  
    7. # 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  
    8. # service will never see the light of an unencrypted Internet see the cheap and lazy remark.  
    9. # So self sign our root key.  
    10. openssl x509 -req -days 365 -in private/ca.csr -signkey private/ca.key -out private/ca.crt  
    11. # 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.  
    12. echo FACE > serial  
    13. # Create the CA's key database.  
    14. touch index.txt  
    15. # Create a Certificate Revocation list for removing 'user certificates.'  
    16. openssl ca -gencrl -out /opt/nginx/ca/private/ca.crl -crldays 7 -config "/opt/nginx/ca/conf/openssl.conf"  

        执行 sh new_ca.sh生成新的CA证书。

        生成服务器证书的脚本。

    new_server.sh:

    [html] view plaincopy
    1. # 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.  
    2. openssl genrsa -out server/server.key  
    3. # Take our key and create a Certificate Signing Request for it.  
    4. openssl req -new -key server/server.key -out server/server.csr  
    5. # Sign this bastard key with our bastard CA key.  
    6. 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"  

        执行 sh new_server.sh生成新服务器的证书

        配置 nginxssl支持:

    [html] view plaincopy
    1. #user  www-nginx;  
    2. worker_processes  1;  
    3.   
    4. #error_log  logs/error.log;  
    5. #error_log  logs/error.log  notice;  
    6. #error_log  logs/error.log  info;  
    7.   
    8. #pid        logs/nginx.pid;  
    9.   
    10.   
    11. events {  
    12.     worker_connections  1024;  
    13. }  
    14. http {  
    15.     include       mime.types;  
    16.     default_type  application/octet-stream;  
    17.     sendfile        on;  
    18.     keepalive_timeout  65;  
    19.     #gzip  on;  
    20.   
    21.     # HTTPS server  
    22.     #  
    23.     server {  
    24.         listen       443;  
    25.         server_name  localhost;  
    26.         ssi on;  
    27.         ssi_silent_errors on;  
    28.         ssi_types text/shtml;  
    29.   
    30.         ssl                  on;  
    31.         ssl_certificate      /opt/nginx/ca/server/server.crt;  
    32.         ssl_certificate_key  /opt/nginx/ca/server/server.key;  
    33.         ssl_client_certificate /opt/nginx/ca/private/ca.crt;  
    34.   
    35.         ssl_session_timeout  5m;  
    36.         ssl_verify_client on;  #开户客户端证书验证  
    37.   
    38.         ssl_protocols  SSLv2 SSLv3 TLSv1;  
    39.         ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;  
    40.         ssl_prefer_server_ciphers   on;  
    41.           
    42.         location / {      
    43.         root /home/workspace/;      
    44.         index index.asp index.aspx;         
    45.     }  
    46.     }  
    47. }  

        启动nginx ,等待客户连接,如果此时连接服务器,将提示400 Bad request certification的错误,故还需要生成客户端证书。

    new_user.sh:

    [html] view plaincopy
    1. #!/bin/sh  
    2. # The base of where our SSL stuff lives.  
    3. base="/opt/nginx/ca"  
    4. # Were we would like to store keys... in this case we take the username given to us and store everything there.  
    5. mkdir -p $base/users/  
    6.   
    7. # 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.  
    8. openssl genrsa -des3 -out $base/users/client.key 1024  
    9. # Create a Certificate Signing Request for said key.  
    10. openssl req -new -key $base/users/client.key -out $base/users/client.csr  
    11. # Sign the key with our CA's key and cert and create the user's certificate out of it.  
    12. 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"  
    13.   
    14. # This is the tricky bit... convert the certificate into a form that most browsers will understand PKCS12 to be specific.  
    15. # 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.  
    16. # Take the same precaution with the export password that would take with any other password based authentication scheme.  
    17. openssl pkcs12 -export -clcerts -in $base/users/client.crt -inkey $base/users/client.key -out $base/users/client.p12  
    18.   
    19.    

       执行 shnew_user.sh生成一个 client证书。
           按照提示一步一步来,这里要注意的是客户证书的几个项目要和根证书匹配。
           也就是前面配置的:
                 countryName = match
                 stateOrProvinceName = match
                 organizationName = match
                 organizationalUnitName = match

            不一致的话无法生成最后的客户证书,证书生成后,客户端导入证书浏览器,即可打开网站。

    注意事项:

        1、制作证书时会提示输入密码,服务器证书和客户端证书密码可以不相同。

        2、服务器证书和客户端证书制作时提示输入省份、城市、域名信息等,需保持一致。

        3、Nginx默认未开启SSI,上面配置已开启。

        4、Nginx不能自启动,需要如下配置:

    [html] view plaincopy
    1. cd /etc/init.d    
    2. sudo touch nginx    
    3. sudo chmod +x nginx   

    nginx内容:

    1. #! /bin/sh  
    2. #  
    3. ### BEGIN INIT INFO  
    4. # Provides:          nginx  
    5. # Required-Start:    $syslog $local_fs $remote_fs  
    6. # Required-Stop:     $syslog $local_fs $remote_fs  
    7. # Should-Start:      dbus avahi  
    8. # Should-Stop:       dbus avahi  
    9. # Default-Start:     2 3 4 5  
    10. # Default-Stop:      1  
    11. # Short-Description: Nginx Server  
    12. # Description:       Nginx  
    13. ### END INIT INFO  
    14.   
    15. PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/nginx/sbin  
    16. DAEMON=/opt/nginx/sbin/nginx  
    17. NAME=nginx  
    18. DESC="Nginx Server"  
    19. PID_FILE=/opt/nginx/logs/nginx.pid  
    20.   
    21. test -x $DAEMON || exit 0  
    22.   
    23. RUN=yes  
    24. #RUN_AS_USER=root  
    25.   
    26. #DAEMON_OPTS="-a $RUN_AS_USER"  
    27.   
    28. set -e  
    29.   
    30. case "$1" in  
    31.   start)  
    32.     echo -n "Starting $DESC: "  
    33.     start-stop-daemon --start --quiet --pidfile $PID_FILE   
    34.         --exec $DAEMON  
    35.     echo "$NAME."  
    36.     ;;  
    37.   stop)  
    38.     echo -n "Stopping $DESC: "  
    39.     start-stop-daemon --stop --oknodo --quiet --pidfile $PID_FILE   
    40.         --exec $DAEMON  
    41.     echo "$NAME."  
    42.     ;;  
    43.   force-reload)  
    44.     # check whether $DAEMON is running. If so, restart  
    45.     start-stop-daemon --stop --test --quiet --pidfile   
    46.         $PID_FILE --exec $DAEMON   
    47.     && $0 restart   
    48.     || exit 0  
    49.     ;;  
    50.   restart)  
    51.     echo -n "Restarting $DESC: "  
    52.     start-stop-daemon --stop --oknodo --quiet --pidfile   
    53.         $PID_FILE --exec $DAEMON  
    54.     sleep 1  
    55.     start-stop-daemon --start --quiet --pidfile   
    56.         $PID_FILE --exec $DAEMON  
    57.     echo "$NAME."  
    58.     ;;  
    59.   status)  
    60.     if [ -s $PID_FILE ]; then  
    61.             RUNNING=$(cat $PID_FILE)  
    62.             if [ -d /proc/$RUNNING ]; then  
    63.                 if [ $(readlink /proc/$RUNNING/exe) = $DAEMON ]; then  
    64.                     echo "$NAME is running."  
    65.                     exit 0  
    66.                 fi  
    67.             fi  
    68.   
    69.             # No such PID, or executables don't match  
    70.             echo "$NAME is not running, but pidfile existed."  
    71.             rm $PID_FILE  
    72.             exit 1  
    73.         else  
    74.             rm -f $PID_FILE  
    75.             echo "$NAME not running."  
    76.             exit 1  
    77.         fi  
    78.     ;;  
    79.   *)  
    80.     N=/etc/init.d/$NAME  
    81.     echo "Usage: $N {start|stop|restart|force-reload}" >&2  
    82.     exit 1  
    83.     ;;  
    84. esac  
    85.   
    86. exit 0  

    设置自启动:

    [html] view plaincopy
    1. sudo chkconfig --list nginx    
    2. sudo chkconfig nginx on   

     

    作者:kunoy
    申明:作者写博是为了总结经验,和交流学习之用。
    如需转载,请尽量保留此申明,并在文章页面明显位置给出原文连接。谢谢!

  • 相关阅读:
    node异步转同步(循环)
    三级省市区PCASClass.js插件
    微信公众号基础总结(待更新)
    ES6详解
    webpack配置
    高性能 CSS3 动画
    github上传口令
    纯css3 实现3D轮播图
    优美的js代码,拿去玩~
    关于列举属性用点还是用【】
  • 原文地址:https://www.cnblogs.com/dingxiaoyue/p/4926852.html
Copyright © 2020-2023  润新知