Apache SSL开启与相关配置

Apache SSL开启与相关配置

6月 06, 2018     liumwei

2020.06.02更新。SSL站点访问方式似乎越来越多,包括Google、Apple、baidu都竞相开启SSL站点方式。那么,如何在自己的站点服务器中开启这一模式呢?下面以Ubuntu 14.04/16.04为环境,来看看基于Apache的SSL开启过程。由于阿里云的免费证书现在似乎不发放了,在更新方法的过程中,找到了一个更快捷的办法。为此,本篇进行了修订。

一、SSL开启通用过程部分

1. 安装相应的软件包

sudo apt install apache2 openssl ssl-cert

#说明,SSL服务本身需要LAMP支持,如何安装LAMP,请转至这个页面查看

2. 开启相应的SSL环境模块

sudo a2enmod ssl xml2enc &&  sudo a2ensite default-ssl && sudo service apache2 restart

二、最简单SSL证书配置方法

https://certbot.eff.org为SSL证书的生成和配置,提供了极其简单的办法。这是阿里云免费证书所不能提供的便利。

至于简单到什么程度,往下看:https://certbot.eff.org/lets-encrypt/ubuntuxenial-apache

sudo apt-get update && sudo apt-get install software-properties-common -y && sudo add-apt-repository ppa:certbot/certbot -y
sudo apt-get update && sudo apt-get install python-certbot-apache -y

执行完上面的命令,接着执行:

sudo certbot --apache

说明:上面的命令表示,为服务器apache相应的域名下载并安装证书

此时会看到如下的信息反馈:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator apache, Installer apache
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): 

输入邮件地址,回车继续:

Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org

-------------------------------------------------------------------------------
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v01.api.letsencrypt.org/directory
-------------------------------------------------------------------------------
(A)gree/(C)ancel: 

输入A,回车:

-------------------------------------------------------------------------------
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about EFF and
our work to encrypt the web, protect its users and defend digital rights.
-------------------------------------------------------------------------------
(Y)es/(N)o: 

输入N,或者Y,继续:

Which names would you like to activate HTTPS for?
-------------------------------------------------------------------------------
1: team.labd.cn
2: tcenter.labd.cn
3: www.labd.cn
-------------------------------------------------------------------------------
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel):

输入1,回车:

Obtaining a new certificate

Performing the following challenges:
http-01 challenge for iteam.ilabmed.cn
Waiting for verification...
Cleaning up challenges
Created an SSL vhost at /etc/apache2/sites-enabled/iteam_ilabmed_cn-le-ssl.conf
Deploying Certificate to VirtualHost /etc/apache2/sites-enabled/iteam_ilabmed_cn-le-ssl.conf

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 

输入1,继续进行:

-------------------------------------------------------------------------------

Congratulations! You have successfully enabled https://team.labd.cn

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=team.labd.cn
-------------------------------------------------------------------------------

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/labmed.liumwei.org/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/labmed.liumwei.org/privkey.pem
   Your cert will expire on 2018-09-04. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le
 

然后,重启Apache服务器:

sudo service apache2 restart

到此,可以用浏览器访问https:// team.labd.cn,可以看到SSL服务已经正常开启了。当然,如果要把原来的http强制转跳到https上,可在http的apche2的配置文件(etc/apache2/sites-enable/team.labd.cn.conf中加入如下代码:

               RewriteEngine on
               RewriteCond %{SERVER_PORT} 80
               RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

也就是这个结果:

<VirtualHost *:80>

        ServerName team.labd.cn
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/labd
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>

        <Directory /var/www/labd>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

               RewriteEngine on
               RewriteCond %{SERVER_PORT} 80
               RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

查看已安装的证书:

sudo certbot certificates

如果不需要证书,可如下命令进行删除

sudo certbot delete --cert-name example.com

为Apache重新下载证书(只下载)

sudo certbot certonly --apache -d www.liumwei.org

说明:certonly表示仅仅下载证书,不做配置;--apache表示为web服务器apache安装证书。-d表示下载;www.liumwei.org表示站点域名。如果出现Failed authorization procedure. alidns.cloudwe.tech (http-01): urn:ietf:params:acme:error:dns :: DNS problem: NXDOMAIN looking up A for alidns.cloudwe.tech - check that a DNS record exists for this domain的错误信息,表明该域名未能从域名提供商进行正常解析,此时需要进入域名提供上所提供的域名解析管理工具中,查看域名解析设置是否有错误。

直接为网站跟目录重新下载安装证书

sudo certbot --webroot -d www.liumwei.org -w /var/www/mlab

说明:/var/www/mlab表示网站根目录

重新下载安装证书(同时安装)

sudo certbot --apache -d www.liumwei.org

测试证书

sudo certbot renew --dry-run

三、传统手动SSL开启办法

先按"一、SSL开启通用过程部分"安装相关的软件。然后按下面的办法进行SSL站点文件

依据/etc/apache2/sites-enabled/default-ssl.conf示例,新建/etc/apache2/sites-enabled/owncloud-ssl.conf配置文件,其代码大致如下:

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerAdmin webmaster@localhost
        ServerName owncloud.bioinfoserv.org

        DocumentRoot /var/www/owncloud

        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        #Include conf-available/serve-cgi-bin.conf

        SSLEngine on

        SSLCertificateFile    /etc/ssl/certs/ssl-cert-snakeoil.pem #可自己生成或认证购买
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key #可自己生成或认证购买

        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>

        # BrowserMatch "MSIE [2-6]" \
        #        nokeepalive ssl-unclean-shutdown \
        #        downgrade-1.0 force-response-1.0

    </VirtualHost>
</IfModule>

重启apache服务:

sudo service apache2 restart

现在通过https://localhost访问了。浏览器会提示不安全访问,此时需要添加安全访问例外即可。当然,为了避免浏览器的安全访问提示,可以使用经过认证的ssl证书(阿里云有免费现成的ssl证书可购买申请)

3. 生成或认证SSL证书(.crt)(正式站点不建议使用自己生成的证书)

采用openssl或StartComTool.exe来生成CSR证书,然后生成crt证书。openssl生成CSR证书的命令为:

openssl req -newkey rsa:2048 -keyout yourname.key -out yourname.csr

以下是这个命令的运行过程:

Generating a 2048 bit RSA private key
............................................+++
....+++
writing new private key to 'youname.key'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:   //该短语在后面配置到apache SSL站点重启服务器时,需要输入此处输入的短语
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CN
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 []:

此时,会生成yourname.key和yourname.csr两个文件。将生成的证书拷贝至 /etc/ssl/certs/或/etc/ssl/private/,然后再修改/etc/apache2/sites-enabled/owncloud-ssl.conf中相应的配置处。完毕,再重启apache服务器即可。

当然,要生成pem证书,相对还要复杂一点,但可以通过https://startssl.com来有效生成或获取。而且https://startssl.com和阿里云服务提供了免费认证的SSL证书。

4. 阿里云免费的SSL证书申请:

进入阿里云证书服务,点击“购买证书”,如下,可进行多个域名的证书免费购买服务(免费型DVSSL):

购买一旦完成,即可进一步补全相关资料,即可进行相应域名的SSL证书申领。需要注意的是,阿里云会自动生成一个验证文件fileauth.txt。根据提示,该文件需放入站点根目录下的.well-known/pki-validation中(一定要保证该文件可访问)。当阿里云验证通过后,会提示证书签发(下图)。此时,下载获得的相应证书文件(并将其到服务器相应的位置),并根据你自己的web服务器类型进行相应配置(见页末代码)。

将上面提到的owncloud-ssl.conf配置文件中的蓝色代码删除,并加入如下的代码:

        SSLProtocol TLSv1 TLSv1.1 TLSv1.2

        SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4

        SSLCertificateFile    /etc/ssl/certs/tcenter.cqmu.edu.cn/tcenter_cqmu_edu_cn_public.pem
        SSLCertificateKeyFile /etc/ssl/certs/tcenter.cqmu.edu.cn/tcenter_cqmu_edu_cn_214068752410536.key

        SSLCertificateChainFile /etc/ssl/certs/tcenter.cqmu.edu.cn/tcenter_cqmu_edu_cn_chain.pem

进行如此修改后,重启服务器即可看到https安全访问已经顺利开启:

sudo service apache2 restart

 

参考

https://certbot.eff.org/lets-encrypt/ubuntuxenial-apache.html
https://community.letsencrypt.org/t/how-to-avoid-too-many-failed-authori...
https://medium.com/@dd0425/lets-encrypt%E5%85%8D%E8%B2%BBssl-tls%E6%86%91%E8%AD%89%E5%AE%89%E8%A3%9D-98059946fabd