Skip to main content

使用 Cloudflare cfssl 自建 CA

据称 cloudflare 在开源 cfssl 时已经在用它管理所有证书了。

安装

go install github.com/cloudflare/cfssl/cmd/...@latest

签发 CA

配置 ca-csr.json

{
  "CN": "Example Trust Service Root ECC",
  "key": {
    "algo": "ecdsa",
    "size": 384
  },
  "ca": {
    "expiry": "438000h"
  },
  "names": [
    {
      "C": "US"
    }
  ]
}
  • CN: Common name,也就是 CA 的名字
  • key.algo: 加密方式,cfssl v1.6.4 默认为 ecdsa-256, 还可选 rsa-2048, rsa-4056
  • ca.expiry: CA 证书的过期时间默认为 5 年,这里配置为 50 年
  • C: Country, 也就是国家

生成证书

cfssl gencert -initca ca-csr.json | cfssljson -bare ca
% ls
ca.csr	ca-csr.json  ca-key.pem  ca.pem
  • ca.csr: 签名请求
  • ca-key.pem: 私钥
  • ca.pem: 自签名 CA 证书

查看证书信息

cfssl-certinfo -cert ca.pem
# or
openssl x509 -in ca.pem -text -noout

使用 CA 签发域名证书

配置域名csr example-csr.json

{
  "CN": "example.com",
  "hosts": ["example.com", "*.example.com", "127.0.0.1"],
  "key": {
    "algo": "ecdsa",
    "size": 384
  },
  "names": [
    {
      "C": "US"
    }
  ]
}
  • CN: common name,证书的名称
  • hosts: 通常称为 SAN(Subject Alt Names),可以填写证书的域名、IP

使用CA 签发域名证书

cfssl gencert -ca ../ca.pem -ca-key ../ca-key.pem example-csr.json | cfssljson -bare example

证书默认时长为 1 年,如果想自定义时长,需要配置 ca-config.json

获取默认的 config.json

cfssl print-defaults config > ca-config.json

添加一个自定义的 profile,参考下边配置, 17520h 即为 2 年

{
  "signing": {
    "default": {
      "expiry": "168h"
    },
    "profiles": {
      "2year": {
        "expiry": "17520h",
        "usages": ["signing", "key encipherment", "server auth", "client auth"]
      }
    }
  }
}

使用 2 年的 profile签发证书

cfssl gencert -ca ../ca.pem -ca-key ../ca-key.pem -config=../ca-config.json -profile=2year example-csr.json | cfssljson -bare example

客户端安装证书

使用 CA 签发域名证书的好处是,只需要在客户端上安装 CA 的 ca.pem ,客户端即无需再去手动信任每个域名证书,而是会信任所有通过 CA 签发的域名证书。

请注意, 在多数 Linux 上将 pem 加入证书链时,文件名需要改为 .crt 后缀。

以下是几个发行版信任证书的相关操作: