YOLO813

如何在网站被Cloudflare代理的情况下更新服务器上的ssl证书

    最近在使用cloudflare时发现了一个问题:服务器上的lets encrypted(下称LE)证书自动更新程序失效了。

    研究了半天,搞明白了,LE默认使用HTTP-01的验证方式来验证您对证书中域名的控制权,原文如下:

    因为使用了cloudflare,访问域名指向的IP都是cloudflare的IP地址,因此验证失败。

    所以考虑使用DNS-01 验证方式。

    首先前往CF控制台创建一个受限的API TOKENS(为了安全起见),因为我们只需要Zone:DNS:Edit权限即可,所以使用模板即可

    前往服务器控制台,安装

# (解决unrecognized arguments: –dns-cloudflare-credentials的问题)
yum install python3-certbot-dns-cloudflare
# 创建文件cf API token
mkdir .secrets
chmod 0700 .secrets
cd .secrets/; vim cloudflare.ini
# cloudflare.ini
dns_cloudflare_api_token = api-tokens
chmod 0400 cloudflare.ini
# 使用如下命令更新
certbot certonly \
  --dns-cloudflare \
  --dns-cloudflare-credentials /root/MyScripts/.secrets/cloudflare.ini \
  -d domain.com \
  -d www.domain.com

    顺利的话,使用如下命令查看cert.pem就可以看到证书成功更新了

openssl x509 -in cert.pem -noout -dates

    接下来可以看到/etc/letsencrypt/renewal/目录下,有一个conf配置文件

# renew_before_expiry = 30 days
version = 1.22.0
archive_dir = /etc/letsencrypt/archive/...
cert = /etc/letsencrypt/live/...
privkey = /etc/letsencrypt/live/.../privkey.pem
chain = /etc/letsencrypt/live/.../chain.pem
fullchain = /etc/letsencrypt/live/.../fullchain.pem

# Options used in the renewal process
[renewalparams]
account = account
authenticator = dns-cloudflare
server = https://acme-v02.api.letsencrypt.org/directory
dns_cloudflare_credentials = /root/MyScripts/.secrets/cloudflare.ini


    定时脚本

00 00 */2 * * root /usr/local/bin/certbot renew --pre-hook "/bin/systemctl stop nginx.service" --post-hook "/bin/systemctl start nginx.service"


    但是,由于我的服务器版本是Centos 8,而该版本已经停止维护,所以会出现yum无法安装的情况,如果不想转换成stream版本,可以考虑重新更换yum源

cd /etc/yum.repos.d
vi CentOS-Linux-BaseOS.repo
[baseos]
name=CentOS Linux $releasever - BaseOS
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=BaseOS&infra=$infra
baseurl=https://vault.centos.org/centos/$releasever/BaseOS/$basearch/os/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
vi CentOS-Linux-AppStream.repo
[appstream]
name=CentOS Linux $releasever - AppStream
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=AppStream&infra=$infra
baseurl=https://vault.centos.org/centos/$releasever/AppStream/$basearch/os/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial

清理缓存生效

yum clean all

    这种方式需要certbot版本>=1.22.0,否则报错

pkg_resources.VersionConflict: (certbot 1.19.0 (/usr/local/lib/python3.6/site-packages), Requirement.parse('certbot>=1.22.0'))

    更新即可

pip install certbot==1.22.0

    也许还会碰到这种报错,我的josepy版本为josepy 1.9.0:

AttributeError: module 'josepy' has no attribute 'field'

    更新josepy

pip install josepy==1.13.0


参考:

https://letsencrypt.org/zh-cn/docs/challenge-types/
#  DNS 提供商的列表
https://community.letsencrypt.org/t/dns-providers-who-easily-integrate-with-lets-encrypt-dns-validation/86438
https://blog.csdn.net/watson2017/article/details/122887710
https://blog.yuncun.me/?p=144