gRPC之SAN证书生成

1、SAN证书生成

SAN(Subject Alternative Name)是 SSL 标准 x509 中定义的一个扩展。使用了 SAN 字段的 SSL 证书,可以扩

展此证书支持的域名,使得一个证书可以支持多个不同域名的解析。接下来我们重新利用配置文件生成CA证书,

再利用ca相关去生成服务端的证书。

1.1 CA根证书生成

新建工作目录:

[root@zsx cert]# pwd
/home/zhangshixing/cert

新建一个配置文件ca.conf,文件内容如下:

[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name

[ req_distinguished_name ]
countryName                 = Country Name (2 letter code)
countryName_default         = CN
stateOrProvinceName         = State or Province Name (full name)
stateOrProvinceName_default = SiChuan
localityName                = Locality Name (eg, city)
localityName_default        = Chengdu
organizationName            = Organization Name (eg, company)
organizationName_default    = Step
commonName                  = CommonName (e.g. server FQDN or YOUR name)
commonName_max              = 64
commonName_default          = tonghua

依次执行下面的命令,执行过程中遇到的填写国家之类的直接Enter跳过,选择配置文件中默认的,从而生成CA私

钥(ca.key)、签名请求(ca.csr)和签名证书(ca.pem)。

[root@zsx cert]# ll
total 4
-rw-r--r--. 1 root root 635 Feb 16 19:53 ca.conf
[root@zsx cert]# openssl genrsa -out ca.key 2048
Generating RSA private key, 2048 bit long modulus
...................................+++
......................+++
e is 65537 (0x10001)

[root@zsx cert]# ls
ca.conf  ca.key
[root@zsx cert]# openssl req -new -sha256 -out ca.csr -key ca.key -config ca.conf
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) [CN]:
State or Province Name (full name) [SiChuan]:
Locality Name (eg, city) [Chengdu]:
Organization Name (eg, company) [Step]:
CommonName (e.g. server FQDN or YOUR name) [tonghua]:

[root@zsx cert]# ls
ca.conf  ca.csr  ca.key
[root@zsx cert]# openssl x509 -req -days 3650 -in ca.csr -signkey ca.key -out ca.pem
Signature ok
subject=/C=CN/ST=SiChuan/L=Chengdu/O=Step/CN=tonghua
Getting Private key

[root@zsx cert]# ls
ca.conf  ca.csr  ca.key  ca.pem

1.2 签发服务端证书

接下来创建服务端配置文件server.conf,文件内容如下:

[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name

[ req_distinguished_name ]
countryName                 = Country Name (2 letter code)
countryName_default         = CN
stateOrProvinceName         = State or Province Name (full name)
stateOrProvinceName_default = SiChuan
localityName                = Locality Name (eg, city)
localityName_default        = Chengdu
organizationName            = Organization Name (eg, company)
organizationName_default    = Step
commonName                  = CommonName (e.g. server FQDN or YOUR name)
commonName_max              = 64
commonName_default          = tonghua
[ req_ext ]
# 添加subjectAltName 
subjectAltName = @alt_names
# www.example.cn代表允许的ServerName
[alt_names]
DNS.1   = www.example.cn
IP      = 127.0.0.1

同样,使用上面得到的CA根证书(ca.pem)签发服务端证书,依次执行下面命令生成服务端的密钥、签名请求和签

名证书:

# 服务端私钥
[root@zsx cert]# openssl genrsa -out server.key 2048
Generating RSA private key, 2048 bit long modulus
.......................................................................................................................................................+++
................................................+++
e is 65537 (0x10001)

[root@zsx cert]# ls
ca.conf  ca.csr  ca.key  ca.pem  server.conf  server.key
# 服务端签名请求
[root@zsx cert]# openssl req -new -sha256 -out server.csr -key server.key -config server.conf
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) [CN]:
State or Province Name (full name) [SiChuan]:
Locality Name (eg, city) [Chengdu]:
Organization Name (eg, company) [Step]:
CommonName (e.g. server FQDN or YOUR name) [tonghua]:

[root@zsx cert]# ls
ca.conf  ca.csr  ca.key  ca.pem  server.conf  server.csr  server.key
# 用根证书签发服务端证书server.pem
[root@zsx cert]# openssl x509 -req -days 3650 -CA ca.pem -CAkey ca.key -CAcreateserial -in server.csr -out server.pem -extensions req_ext -extfile server.conf
Signature ok
subject=/C=CN/ST=SiChuan/L=Chengdu/O=Step/CN=tonghua
Getting CA Private Key

[root@zsx cert]# ls
ca.conf  ca.csr  ca.key  ca.pem  ca.srl  server.conf  server.csr  server.key  server.pem

1.3 签发客户端证书

建立配置文件client.conf

[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name

[ req_distinguished_name ]
countryName                 = Country Name (2 letter code)
countryName_default         = CN
stateOrProvinceName         = State or Province Name (full name)
stateOrProvinceName_default = SiChuan
localityName                = Locality Name (eg, city)
localityName_default        = Chengdu
organizationName            = Organization Name (eg, company)
organizationName_default    = Step
commonName                  = CommonName (e.g. server FQDN or YOUR name)
commonName_max              = 64
commonName_default          = tonghua
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1   = www.example.cn
IP      = 127.0.0.1

执行下面命令生成客户端密钥、证书等:

[root@zsx cert]# openssl ecparam -genkey -name secp384r1 -out client.key

[root@zsx cert]# ls
ca.conf  ca.key  ca.srl       client.key   server.csr  server.pem
ca.csr   ca.pem  client.conf  server.conf  server.key
[root@zsx cert]# openssl req -new -sha256 -out client.csr -key client.key -config client.conf
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) [CN]:
State or Province Name (full name) [SiChuan]:
Locality Name (eg, city) [Chengdu]:
Organization Name (eg, company) [Step]:
CommonName (e.g. server FQDN or YOUR name) [tonghua]:

[root@zsx cert]# ls
ca.conf  ca.key  ca.srl       client.csr  server.conf  server.key
ca.csr   ca.pem  client.conf  client.key  server.csr   server.pem
[root@zsx cert]# openssl x509 -req -days 3650 -CA ca.pem -CAkey ca.key -CAcreateserial -in client.csr -out client.pem -extensions req_ext -extfile client.conf
Signature ok
subject=/C=CN/ST=SiChuan/L=Chengdu/O=Step/CN=tonghua
Getting CA Private Key

[root@zsx cert]# ls
ca.conf  ca.key  ca.srl       client.csr  client.pem   server.csr  server.pem
ca.csr   ca.pem  client.conf  client.key  server.conf  server.key

1.4 双向认证

1.4.1 proto编写和编译
syntax = "proto3";
package proto;
option go_package = "./base;base";

service BaseService {
    rpc GetTime (TimeRequest) returns (TimeResponse) {}
}

message TimeRequest {}

message TimeResponse {
    string time = 1;
}
protoc --go_out=plugins=grpc:. base.proto
1.4.2 服务端
package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	pb "demo/base"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"io/ioutil"
	"log"
	"net"
	"time"
)

const (
	// Address gRPC服务地址
	Address = "127.0.0.1:8888"
)

type service struct {
	pb.UnimplementedBaseServiceServer
}

func main() {
	// TLS认证
	// 从证书相关文件中读取和解析信息,得到证书公钥、密钥对
	cert, err := tls.LoadX509KeyPair("./cert/server.pem", "./cert/server.key")
	if err != nil {
		log.Fatalln("cert err: ", err)
	}
	// 初始化一个CertPool
	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile("./cert/ca.pem")
	if err != nil {
		log.Fatalln("ca err: ", err)
	}
	// 解析传入的证书,解析成功会将其加到池子中
	certPool.AppendCertsFromPEM(ca)
	// 构建基于TLS的TransportCredentials选项
	creds := credentials.NewTLS(&tls.Config{
		// 服务端证书链,可以有多个
		Certificates: []tls.Certificate{cert},
		// 要求必须验证客户端证书
		ClientAuth: tls.RequireAndVerifyClientCert,
		// 设置根证书的集合,校验方式使用 ClientAuth 中设定的模式
		ClientCAs: certPool,
	})
	// 实例化grpc Server
	rpcServer := grpc.NewServer(grpc.Creds(creds))
	// 创建带ca证书验证的服务端
	pb.RegisterBaseServiceServer(rpcServer, &service{})
	// 设置传输协议和监听地址
	listen, err := net.Listen("tcp", Address)
	if err != nil {
		log.Fatalln("listen err: ", err)
	}
	log.Println("Listen on " + Address + " with TLS")
	rpcServer.Serve(listen)
}

// 实现接口
func (s *service) GetTime(ctx context.Context, in *pb.TimeRequest) (*pb.TimeResponse, error) {
	now := time.Now().Format("2006-01-02 15:04:05")
	return &pb.TimeResponse{Time: now}, nil
}
[root@zsx demo]# go run server.go
2023/02/16 20:53:13 Listen on 127.0.0.1:8888 with TLS
1.4.3 客户端
package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	pb "demo/base"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"io/ioutil"
	"log"
)

const (
	// Address gRPC服务地址
	Address = "127.0.0.1:8888"
)

func main() {
	// TLS连接
	// 从证书相关文件中读取和解析信息,得到证书公钥、密钥对
	cert, err := tls.LoadX509KeyPair("./cert/client.pem", "./cert/client.key")
	if err != nil {
		log.Fatalln("cert err: ", err)
	}
	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile("./cert/ca.pem")
	if err != nil {
		log.Fatalln("ca err: ", err)
	}
	certPool.AppendCertsFromPEM(ca)
	creds := credentials.NewTLS(&tls.Config{
		//客户端证书
		Certificates: []tls.Certificate{cert},
		//注意这里的参数为配置文件中所允许的ServerName,也就是其中配置的DNS
		ServerName: "www.example.cn",
		RootCAs:    certPool,
	})
	// 连接服务端
	conn, err := grpc.Dial(Address, grpc.WithTransportCredentials(creds))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	client := pb.NewBaseServiceClient(conn)
	reps, err := client.GetTime(context.Background(), &pb.TimeRequest{})
	// 初始化客户端
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("grpcClient response is %s\n", reps.Time)
}
[root@zsx demo]# go run client.go
grpcClient response is 2023-02-16 20:53:30

1.5 单向认证

1.5.1 服务端
package main

import (
	"context"
	pb "demo/base"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"log"
	"net"
	"time"
)

type service struct {
	pb.UnimplementedBaseServiceServer
}

func main() {
	creds, err := credentials.NewServerTLSFromFile("./cert/server.pem", "./cert/server.key")
	if err != nil {
		log.Fatal(err)
	}
	Address := "127.0.0.1:8888"
	//创建带ca证书验证的服务端
	rpcServer := grpc.NewServer(grpc.Creds(creds))
	pb.RegisterBaseServiceServer(rpcServer, &service{})
	listen, _ := net.Listen("tcp", Address)
	log.Println("Listen on " + Address + " with TLS")
	rpcServer.Serve(listen)
}

// 实现接口
func (s *service) GetTime(ctx context.Context, in *pb.TimeRequest) (*pb.TimeResponse, error) {
	now := time.Now().Format("2006-01-02 15:04:05")
	return &pb.TimeResponse{Time: now}, nil
}
[root@zsx demo]# go run server1.go
2023/02/16 20:53:55 Listen on 127.0.0.1:8888 with TLS
1.5.2 客户端
package main

import (
	"context"
	pb "demo/base"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"log"
)

func main() {
	creds, err := credentials.NewClientTLSFromFile("./cert/server.pem", "www.example.cn")
	if err != nil {
		log.Fatal(err)
	}
	conn, err := grpc.Dial("127.0.0.1:8888", grpc.WithTransportCredentials(creds))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	client := pb.NewBaseServiceClient(conn)
	resp, err := client.GetTime(context.Background(), &pb.TimeRequest{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("grpcClient response is %s\n", resp.Time)
}
[root@zsx demo]# go run client1.go
grpcClient response is 2023-02-16 20:54:14
# 项目结构
$ tree demo/
demo/
├── base
│   └── base.pb.go
├── base.proto
├── cert
│   ├── ca.conf
│   ├── ca.csr
│   ├── ca.key
│   ├── ca.pem
│   ├── ca.srl
│   ├── client.conf
│   ├── client.csr
│   ├── client.key
│   ├── client.pem
│   ├── server.conf
│   ├── server.csr
│   ├── server.key
│   └── server.pem
├── client1.go
├── client.go
├── go.mod
├── go.sum
├── server1.go
└── server.go

你可能感兴趣的:(gRPC,gRPC)