hosea1008
7/8/2019 - 3:13 PM

Docker Nginx 反向代理+密码认证 + http

Docker Nginx

先编写nginx配置文件

cat nginx_conf/nginx.conf
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}



http {


    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {
        listen 8088;
        server_name hsserver.tk;

        location / {
            proxy_pass http://127.0.0.1:8888;
            auth_basic "Please Login";
            auth_basic_user_file /hsli.password;
        }
    }

#    include /etc/nginx/conf.d/*.conf;
}

安装apache2-utils,使用里面的htpasswd生成密码文件

sudo htpasswd -c ~/nginx_conf/hsli.password hsli

启动docker,注意配置网络模式,挂载nginx.conf和密码文件

docker run --rm --name nginx -d --net=host -v /home/hsli/nginx_conf/nginx.conf:/etc/nginx/nginx.conf -v /home/hsli/nginx_conf/hsli.password:/hsli.password nginx

配置https 自签ssl证书

https://www.jianshu.com/p/5f9bd492f186

通过openssl生成证书

设置server.key,这里需要设置两遍密码:

openssl genrsa -des3 -out server.key 1024 

参数设置,首先这里需要输入之前设置的密码:

openssl req -new -key server.key -out server.csr

然后需要输入如下的信息,大概填一下就可以了,反正是测试用的

Country Name (2 letter code) [AU]: 国家名称
State or Province Name (full name) [Some-State]: 省
Locality Name (eg, city) []: 城市
Organization Name (eg, company) [Internet Widgits Pty Ltd]: 公司名
Organizational Unit Name (eg, section) []: 
Common Name (e.g. server FQDN or YOUR name) []: 网站域名
Email Address []: 邮箱

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: 这里要求输入密码
An optional company name []:

写RSA秘钥(这里也要求输入之前设置的密码):

openssl rsa -in server.key -out server_nopwd.key

获取私钥:

openssl x509 -req -days 365 -in server.csr -signkey server_nopwd.key -out server.crt

完成这一步之后就得到了我们需要的证书文件和私钥了

server.crt
server.key

server_nopwd.key这是免密认真的私钥

配置Nginx支持https

配置文件站点下增加ssl相关支持

server {
    listen    80;       #侦听80端口,如果强制所有的访问都必须是HTTPs的,这行需要注销掉
    listen    8088 ssl;
    server_name  www.buagengen.com;             #域名

    # 增加ssl
    #ssl on;        #如果强制HTTPs访问,这行要打开
    ssl_certificate /ssl/server.crt;
    ssl_certificate_key /ssl/server_nopwd.key;

    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

     # 指定密码为openssl支持的格式
     ssl_protocols  SSLv2 SSLv3 TLSv1.2;

     ssl_ciphers  HIGH:!aNULL:!MD5;  # 密码加密方式
     ssl_prefer_server_ciphers  on;   # 依赖SSLv3和TLSv1协议的服务器密码将优先于客户端密码

     # 定义首页索引目录和名称
     location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
     }

    #重定向错误页面到 /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

然后docker启动nginx时再加上-v /home/user/nginx_conf/cert:/ssl

Let's Encrypt 证书 + docker nginx + 域名认证

首先安装certbot

sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python-certbot-nginx

然后申请证书,通过域名DNS认证

运行sudo certbot --manual --preferred-challenges dns certonly命令,输入域名并同意记录本机IP后开始获取证书,接着certbot就会弹出如下的提示:

-------------------------------------------------------------------------------
Please deploy a DNS TXT record under the name
_acme-challenge.example.com with the following value:

IMdfdsfsJDqBRyRaaEgPPQlEuvtxJQAgWZTIVbLuzDi8U

Once this is deployed,
-------------------------------------------------------------------------------
Press Enter to Continue

此时certbot程序就会暂停,等待我们去添加DNS记录。

添加DNS的TXT记录 看到上述的提示后,修改域名的DNS记录,添加一条TXT记录,主机名为_acme-challenge,而其中的内容就是letsencrypt生成的随机字符串IMdfdsfsJDqBRyRaaEgPPQlEuvtxJQAgWZTIVbLuzDi8U。

注意记录主机名为_acme-challenge.service.hsli.top,要带上_acme-challenge并加在二级域名之上

验证成功 添加好DNS记录后,我们可以通过dig -t txt _acme-challenge.service.hsli.top来查看域名的内容,域名生效以后,在certbot程序中下按下回车键,程序继续运行。letsencrypt对DNS记录验证成功,证书就申请成功了。

配置nginx

参考

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}



http {


    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    server {
        listen 8088 ssl;
        server_name service.hsli.top;

        # ssl_certificate /ssl/server.crt;
        # ssl_certificate_key /ssl/server_nopwd.key;
        
        ssl_certificate /etc/letsencrypt/live/service.hsli.top/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/service.hsli.top/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/service.hsli.top/chain.pem;

        # ssl_session_cache shared:SSL:1m;
        # ssl_session_timeout   5m;
        
        # ssl_protocols SSLv2 SSLv3 TLSv1.2;

        # ssl_ciphers HIGH:!aNULL:!MD5;
        # ssl_prefer_server_ciphers on;

        location / {
            proxy_pass http://127.0.0.1:8888;
            auth_basic "Please Login";
            auth_basic_user_file /hsli.password;
        }
    }
    server {
        listen 7500 ssl;
        server_name service.hsli.top;

        ssl_certificate /etc/letsencrypt/live/service.hsli.top/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/service.hsli.top/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/service.hsli.top/chain.pem;

        location / {
            proxy_pass http://127.0.0.1:3000;
        }
    }


#    include /etc/nginx/conf.d/*.conf;
}

指定了密钥位置

启动nginx docker

多加一个目录映射

docker run --rm --name nginx --net=host -v /home/hsli/nginx_conf/nginx.conf:/etc/nginx/nginx.conf -v /home/hsli/nginx_conf/hsli.password:/hsli.password -v /etc/letsencrypt:/etc/letsencrypt -d nginx

自动更新证书

证书默认有效期只有90天,加crontab任务自动更新

自动更新命令:

sudo certbot certonly --renew-by-default -d YOURDOMAIN --manual --preferred-challenges dns

加到crontab里面

0 12 25 * * certbot certonly --renew-by-default -d service.hsli.top --manual --preferred-challenges dns

每月25号12点0分自动更新证书

更新完证书需要重启nginx?

非标准端口强制https

站点配置加上

error_page 497 https://$host:port$request_uri;
server {
  listen      1234 ssl;
  server_name your.site.tld;
  ssl         on;
  ...
  error_page  497 https://$host:1234$request_uri;
  ...
  location
  ...
}

自制CA证书机构,自签证书

https://www.cnblogs.com/ciaos/p/4887505.html

第一步,自制CA证书和Server证书,私钥

自制CA私钥

openssl genrsa -des3 -out ca.key 4096

自制CA证书

openssl req -new -x509 -days 3650 -key ca.key -out ca.crt

自制Server私钥,生成免密码版本

openssl genrsa -des3 -out server.key 4096
openssl rsa -in server.key -out server.nosecret.key

制作csr文件

openssl req -new -key server.key -out server.csr

用CA证书私钥对csr签名(CA不能用X509,这点需要注意)生成Server证书

openssl ca -days 3650 -in server.csr -cert ca.crt -keyfile ca.key -out server.crt
I am unable to access the ./demoCA/newcerts directory
    ./demoCA/newcerts: No such file or directory

解决办法是在你当前操作目录。新建demoCA\newcerts文件夹。。。注意是2层文件夹哦。。。然后再demoCA文件夹下新建一个空的index.txt文件。。再新建一个serial文件,没有后缀。里面填入01。。。就OK了。。 

第二步,配置web服务器,nginx配置方法如下

server {
    listen 443;
    server_name www.mydomain.com;

    ssl on;
    ssl_certificate ssl/server.crt;
    ssl_certificate_key ssl/server.nosecret.key;

    location /t {
            echo "Hello World";
    }
}

lighttpd配置如下(需要cat server.nosecret.key server.crt > server.pem)

$HTTP["host"] =~ "(^.*\.|)mydomain.com" {
        $SERVER["socket"] == ":443" {
                ssl.engine                  = "enable"
                ssl.pemfile                 = "/etc/lighttpd/server.pem"
                ssl.ca-file                 = "/etc/lighttpd/server.crt"
        }

        proxy.balance = "round-robin"
        proxy.server = (
                "/" => ((
                        "host"  =>      "127.0.0.1",
                        "port"  =>      9000
                ))
        )
}

第三步,验证方法如下

浏览器使用需导入ca.crt到根证书,curl和wget命令行工具使用方法如下

curl -v --cacert ca.crt "https://www.mydomain.com/t"
wget --ca-certificate=ca.crt https://www.mydomain.com/t

不检查证书

curl需要指定-k参数,wget需要带参数-no-check-certificate

附,libcurl使用如下

function curlPost($url, $data = array(), $timeout = 30, $CA = true){

    $cacert = getcwd() . '/ca.crt'; //CA根证书  
    $SSL = substr($url, 0, 8) == "https://" ? true : false;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout-2);
    if ($SSL && $CA) {
        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//默认PEM
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);   // 只信任CA颁布的证书  
        curl_setopt($ch, CURLOPT_SSLCERTPASSWD, true);   // 只信任CA颁布的证书  

        curl_setopt($ch, CURLOPT_CAINFO, $cacert); // CA根证书(用来验证的网站证书是否是CA颁布)  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名,并且是否与提供的主机名匹配  
    } else if ($SSL && !$CA) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名  
    }
    curl
    _setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); //避免data数据过长问题  
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); //data with URLEncode  

    $ret = curl_exec($ch);
    //var_dump(curl_error($ch));  //查看报错信息  

    curl_close($ch);
    return $ret;
}

$ret = curlPost("https://www.mydomain.com/t");
echo $ret;

查看证书内容,有效期,用途方法如下

openssl x509 -in ca.crt -noout -text 
openssl x509 -in ca.crt -noout -dates
openssl x509 -in ca.crt -noout -purpose