llhuii / dive-into-k8s

Apache License 2.0
0 stars 0 forks source link

cfssl 生成证书的脚本 #33

Open llhuii opened 7 months ago

llhuii commented 7 months ago
#!/bin/bash

set -e -u

ORG=foo-inc.com
CN=apiserver
HOST=foo-inc.com

: "${OUT_DIR:=pki}"
mkdir -p "$OUT_DIR" && cd "$OUT_DIR"

PATH=$PATH:$(go env GOPATH)/bin

function check_and_install() {

  command cfssl version >/dev/null 2>&1 && return

  version=v1.6.4

  go install github.com/cloudflare/cfssl/cmd/cfssl@$version

  go install github.com/cloudflare/cfssl/cmd/cfssljson@$version

}

function gen_ca() {
  cat >root-ca-csr.json <<EOF
  {
      "CN": "$CN",
      "key": {
          "algo": "rsa",
          "size": 2048
      },
      "names": [
          {
              "O": "$ORG"
          }
      ],
      "ca": {
          "expiry": "438000h"
      }
  }

EOF
  cfssl gencert -initca root-ca-csr.json | cfssljson -bare root-ca

}

function gen_server_certs() {
  cat >server-csr.json <<EOF
{
    "CN": "dbaas-apiserver",
    "hosts": [
        "localhost",
         "127.0.0.1",
        "$HOST"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "O": "$ORG"
        }
    ]
}

EOF

  cat >root-ca-config.json <<EOF
{
    "signing": {
        "default": {
            "expiry": "87600h",
            "usages": [
                "signing",
                "key encipherment",
                "server auth",
                "client auth"
            ]
        },
        "profiles": {
            "server": {
                "expiry": "87600h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "server auth"
                ]
            },
            "client": {
                "expiry": "87600h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "client auth"
                ]
            }
        }
    },
    "cn": "$CN",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "O": "$ORG"
        }
    ]
}
EOF
  cfssl genkey -config=root-ca-config.json -profile=server server-csr.json | cfssljson -bare server

  cfssl sign -config=root-ca-config.json -profile=server -ca=root-ca.pem -ca-key=root-ca-key.pem server.csr | cfssljson -bare server

}

function clean_certs() {
  rm root-ca-config.json root-ca.csr root-ca-csr.json server-csr.json server.csr

  mv root-ca.pem ca.crt && mv root-ca-key.pem ca.key
  mv server.pem server.crt && mv server-key.pem server.key

}

check_and_install

gen_ca

gen_server_certs

clean_certs