本文代码
https://github.com/XiMuQ/go-grpc
问题重现
golang 1.15+ 版本上,用 gRPC通过TLS实现数据传输加密时,会报错证书的问题:
rpc error: code = Unavailable desc = connection error: desc = "transport: authentication handshake failed: x509: certificate is not valid for any names, but wanted to match www.ximu.info"
是因为用的TLS证书,并没有开启SAN扩展(默认是没有开启SAN扩展)所生成的,导致客户端和服务端无法建立连接。
什么是 SAN?
SAN(Subject Alternative Name)是 SSL 标准 x509 中定义的一个扩展。使用了 SAN 字段的 SSL 证书,可以扩展此证书支持的域名,使得一个证书可以支持多个不同域名的解析。
解决办法
一、生成CA根证书
后面需要使用根证书CA来生成服务端、客户端证书
1.1 在证书存放文件夹下 新建 ca.conf ,写入内容如下:
[ req ]
default_bits = 4096
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 = BeiJing
localityName = Locality Name (eg, city)
localityName_default = BeiJing
organizationName = Organization Name (eg, company)
organizationName_default = XiMu
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = ximu
1.2 生成ca秘钥,得到ca.key
openssl genrsa -out ca.key 4096
1.3 生成ca证书签发请求,得到ca.csr
openssl req -new -sha256 -out ca.csr -key ca.key -config ca.conf
1.4 生成ca根证书,得到ca.crt
openssl x509 -req -days 3650 -in ca.csr -signkey ca.key -out ca.crt
二、 生成服务端证书
2.1 在证书存放文件夹下,新建server.conf ,写入内容如下:
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
req_extensions = req_ext
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = BeiJing
localityName = Locality Name (eg, city)
localityName_default = BeiJing
organizationName = Organization Name (eg, company)
organizationName_default = XiMu
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = ximu
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = ximu.info
DNS.3 = www.ximu.info
IP = 127.0.0.1
2.2 生成秘钥,得到server.key
openssl genrsa -out server.key 2048
2.3 生成证书签发请求,得到server.csr
openssl req -new -sha256 -out server.csr -key server.key -config server.conf
2.4 用CA证书生成服务端证书,得到server.pem
openssl x509 -req -days 3650 -CA ca.crt -CAkey ca.key -CAcreateserial -in server.csr -out server.pem -extensions req_ext -extfile server.conf
现在证书已经生成完毕, server.pem 和 server.key就是我们需要的证书和密钥。
key: 服务器上的私钥文件,用于对发送给客户端数据的加密,以及对从客户端接收到数据的解密。 csr: 证书签名请求文件,用于提交给证书颁发机构(CA)对证书签名。 crt: 由证书颁发机构(CA)签名后的证书,或者是开发者自签名的证书,包含证书持有人的信息,持有人的公钥,以及签署者的签名等信息。 pem: 是基于Base64编码的证书格式,扩展名包括PEM、CRT和CER。
ca.conf和server.conf对比
可以发现ca.conf和server.conf的配置大致相同,这是因为ca.conf生成的是根证书,用户证书需要在根证书的基础上创建,所以高度相同,对于两个证书的配置信息不必过于深究,够使用即可。
三、证书的使用(单向认证)
3.1 服务端
package main
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"grpc01/service"
"log"
"net"
)
type server struct {
service.UnimplementedQueryUserServer
}
func (s *server) GetUserInfo(ctx context.Context, in *service.ReqParam) (*service.ResParam, error) {
return &service.ResParam{Id: in.Id, Name: in.Name, Age: 20, Address: "Beijing"}, nil
}
func main() {
creds, err := credentials.NewServerTLSFromFile("keys/server.pem", "keys/server.key")
if err != nil {
grpclog.Fatalf("Failed to generate credentials %v", err)
}
ser := grpc.NewServer(grpc.Creds(creds))
service.RegisterQueryUserServer(ser, &server{})
listener, err := net.Listen("tcp", ":8002")
if err != nil {
log.Fatal("服务监听端口失败", err)
}
_ = ser.Serve(listener)
}
3.2 客户端
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"grpc01/service"
"log"
)
func main() {
creds, err := credentials.NewClientTLSFromFile("keys/server.pem", "localhost")
if err != nil {
grpclog.Fatalf("Failed to create TLS credentials %v", err)
}
conn, err := grpc.Dial(":8002", grpc.WithTransportCredentials(creds))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
request := &service.ReqParam{
Id: 123,
Name: "西木",
}
query := service.NewQueryUserClient(conn)
res, err := query.GetUserInfo(context.Background(), request)
if err != nil {
log.Fatal("调用gRPC方法错误: ", err)
}
fmt.Println("调用gRPC方法成功,ProdStock = ", res)
}
四、双向认证
注意事项
前面我们生成的根证书是ca.crt,这个在单向认证没有问题,但是在双向认证时,就需要更改证书的类型,改为ca.pem,因为双向认证时只能解析pem类型的根证书。 只需将1.4的生成ca.crt的命令改为ca.pem即可;
4.1 修改根证书生成命令
4.1.1 生成ca秘钥,得到ca.key【命令与1.2完全一致】
openssl genrsa -out ca.key 4096
4.1.2 生成ca证书签发请求,得到ca.csr【命令与1.3完全一致】
openssl req -new -sha256 -out ca.csr -key ca.key -config ca.conf
4.1.3 生成ca根证书,得到ca.pem 的命令:
openssl x509 -req -days 3650 -in ca.csr -signkey ca.key -out ca.pem
4.2 修改服务端证书生成命令
4.2.1 生成秘钥,得到server.key【命令与2.2完全一致】
openssl genrsa -out server.key 2048
4.2.2 生成证书签发请求,得到server.csr【命令与2.3完全一致】
openssl req -new -sha256 -out server.csr -key server.key -config server.conf
4.2.3 用CA证书生成服务端证书,得到server.pem
将ca.crt 替换成ca.pem 使用ca.pem的命令:
openssl x509 -req -days 3650 -CA ca.pem -CAkey ca.key -CAcreateserial -in server.csr -out server.pem -extensions req_ext -extfile server.conf
4.3 在证书存放文件夹下,新建client.conf,写入内容如下:
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
req_extensions = req_ext
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = BeiJing
localityName = Locality Name (eg, city)
localityName_default = BeiJing
organizationName = Organization Name (eg, company)
organizationName_default = XiMu
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = ximu
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = ximu.info
DNS.3 = www.ximu.info
IP = 127.0.0.1
4.4 生成秘钥,得到client.key
openssl ecparam -genkey -name secp384r1 -out client.key
4.5 生成证书签发请求,得到client.csr
openssl req -new -sha256 -out client.csr -key client.key -config client.conf
4.6 用CA证书生成客户端证书,得到client.pem
使用ca.pem 的命令:
openssl x509 -req -days 3650 -CA ca.pem -CAkey ca.key -CAcreateserial -in client.csr -out client.pem -extensions req_ext -extfile client.conf
4.7 服务端代码
将ca.pem 、server.key 和server.pem 到服务端代码中:
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"go-grpc/service"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"io/ioutil"
"log"
"net"
)
type server struct {
service.UnimplementedQueryUserServer
}
func (s *server) GetUserInfo(ctx context.Context, in *service.ReqParam) (*service.ResParam, error) {
return &service.ResParam{Id: in.Id, Name: in.Name, Age: 20, Address: "Beijing"}, nil
}
const (
Address = "127.0.0.1:8003"
)
func main() {
cert, _ := tls.LoadX509KeyPair("keys2/server.pem", "keys2/server.key")
certPool := x509.NewCertPool()
ca, _ := ioutil.ReadFile("keys2/ca.pem")
certPool.AppendCertsFromPEM(ca)
creds := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: certPool,
})
ser := grpc.NewServer(grpc.Creds(creds))
service.RegisterQueryUserServer(ser, &server{})
listener, err := net.Listen("tcp", Address)
if err != nil {
log.Fatal("服务监听端口失败", err)
}
_ = ser.Serve(listener)
}
4.8 客户端代码
将ca.pem 、client.key 和client.pem 到客户端代码中:
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"go-grpc/service"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"io/ioutil"
"log"
)
const (
Address = "127.0.0.1:8003"
)
func main() {
cert, _ := tls.LoadX509KeyPair("keys2/client.pem", "keys2/client.key")
certPool := x509.NewCertPool()
ca, _ := ioutil.ReadFile("keys2/ca.pem")
certPool.AppendCertsFromPEM(ca)
creds := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: "ximu.info",
RootCAs: certPool,
})
conn, err := grpc.Dial(Address, grpc.WithTransportCredentials(creds))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
request := &service.ReqParam{
Id: 123,
Name: "西木",
}
query := service.NewQueryUserClient(conn)
res, err := query.GetUserInfo(context.Background(), request)
if err != nil {
log.Fatal("调用gRPC方法错误: ", err)
}
fmt.Println("双向认证:调用gRPC方法成功,ProdStock = ", res)
}
五、Token认证
5.1 服务端代码
package main
import (
"context"
"fmt"
"go-grpc/service"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"log"
"net"
)
type server struct {
service.UnimplementedQueryUserServer
}
func (s *server) GetUserInfo(ctx context.Context, in *service.ReqParam) (*service.ResParam, error) {
return &service.ResParam{Id: in.Id, Name: in.Name, Age: 20, Address: "Beijing"}, nil
}
const (
Address = "127.0.0.1:8003"
)
func main() {
var authInterceptor grpc.UnaryServerInterceptor
authInterceptor = func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
err = Auth(ctx)
if err != nil {
return
}
return handler(ctx, req)
}
ser := grpc.NewServer(grpc.UnaryInterceptor(authInterceptor))
service.RegisterQueryUserServer(ser, &server{})
listener, err := net.Listen("tcp", Address)
if err != nil {
log.Fatal("服务监听端口失败", err)
}
_ = ser.Serve(listener)
}
func Auth(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return fmt.Errorf("missing credentials")
}
var user string
var password string
if val, ok := md["user"]; ok {
user = val[0]
}
if val, ok := md["password"]; ok {
password = val[0]
}
if user != "admin" || password != "admin" {
return status.Errorf(codes.Unauthenticated, "客户端请求的token不合法")
}
return nil
}
5.2 客户端
5.2.1 客户端需要实现 PerRPCCredentials 接口
package service
import "context"
type PerRPCCredentials interface {
GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
RequireTransportSecurity() bool
}
具体实现:
package impl
import "context"
type Authentication struct {
User string
Password string
}
func (a *Authentication) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return map[string]string{"user": a.User, "password": a.Password}, nil
}
func (a *Authentication) RequireTransportSecurity() bool {
return false
}
5.3 客户端
package main
import (
"context"
"fmt"
"go-grpc/service"
"go-grpc/token/service/impl"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"log"
)
const (
Address = "127.0.0.1:8003"
)
func main() {
user := &impl.Authentication{
User: "admin",
Password: "admin2",
}
conn, err := grpc.Dial(Address, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithPerRPCCredentials(user))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
request := &service.ReqParam{
Id: 123,
Name: "西木",
}
query := service.NewQueryUserClient(conn)
res, err := query.GetUserInfo(context.Background(), request)
if err != nil {
log.Fatal("调用gRPC方法错误: ", err)
}
fmt.Println("Token:调用gRPC方法成功,ProdStock = ", res)
}
六、拦截器
参考:拦截器
|