Commit 88e31175f07eb3b27f7dbc0bc2f3fdfd9dd0f46c

Authored by zhangqijia
1 parent b6e571c3

grpc 增加tls, 使用san证书

Makefile
... ... @@ -2,7 +2,7 @@
2 2  
3 3 all: ge build run
4 4  
5   -ge:
  5 +gen:
6 6 protoc -I./protos --go_out=./protos --go-grpc_out=./protos ./protos/*proto
7 7 protoc-go-inject-tag -input=./protos/pb/*.pb.go
8 8  
... ... @@ -16,4 +16,19 @@ build:
16 16 go build -o bin/account account.go
17 17 go build -o bin/game game.go
18 18  
  19 +cert:
  20 + openssl req \
  21 + -x509 \
  22 + -nodes \
  23 + -newkey rsa:2048 \
  24 + -keyout keys/ca.key \
  25 + -out keys/ca.crt \
  26 + -days 3650 \
  27 + -subj "/C=CN/ST=ZheJiang/L=ZheJiang/O=Global/CN=pro2d Security/OU=IT Department/CN=pro2d"
  28 + openssl genpkey -algorithm RSA -out keys/server.key
  29 + openssl req -new -nodes -key keys/server.key -out keys/server.csr -days 3650 -subj "/C=CN/OU=IT/O=Global/CN=pro2d/L=ZheJiang" -config keys/openssl.cnf -extensions v3_req
  30 + openssl x509 -req -days 365 -in keys/server.csr -out keys/server.pem -CA keys/ca.crt -CAkey keys/ca.key -CAcreateserial -extfile keys/openssl.cnf -extensions v3_req
  31 +
  32 +
  33 +
19 34 .PHONY: all build protos test
20 35 \ No newline at end of file
... ...
README.md
... ... @@ -24,6 +24,10 @@ $ go install google.golang.org/protobuf/cmd/protoc-gen-go
24 24 $ go get google.golang.org/grpc/cmd/protoc-gen-go-grpc
25 25 $ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc
26 26 ```
  27 +## 文档
  28 +[证书制作](doc/cret.md)
  29 +
  30 +
27 31 ## Usage
28 32 编译 & 运行
29 33 ```shell
... ...
actions/server.go
... ... @@ -4,6 +4,7 @@ import (
4 4 "context"
5 5 "fmt"
6 6 "google.golang.org/grpc"
  7 + "google.golang.org/grpc/credentials"
7 8 "google.golang.org/grpc/reflection"
8 9 "pro2d/conf"
9 10 "pro2d/models"
... ... @@ -39,15 +40,27 @@ func (s *LoginServer)Start() error {
39 40  
40 41 models.InitAccountServerModels()
41 42  
  43 + var opts []grpc.ServerOption
  44 + //TLS
  45 + creds, err := credentials.NewServerTLSFromFile("keys/server.pem", "keys/server.key")
  46 + if err != nil {
  47 + utils.Sugar.Errorf("Failed to generate credentials %v", err)
  48 + return err
  49 + }
  50 + opts = append(opts, grpc.Creds(creds))
  51 +
  52 + //拦截器
  53 + opts = append(opts, grpc.UnaryInterceptor(AccountServerInterceptor))
  54 +
42 55 //new一个grpc
43   - s.GrpcServer = grpc.NewServer(grpc.UnaryInterceptor(AccountServerInterceptor))
  56 + s.GrpcServer = grpc.NewServer(opts...)
44 57  
45 58 pb.RegisterLoginServer(s.GrpcServer, s)
46 59 reflection.Register(s.GrpcServer) //在给定的gRPC服务器上注册服务器反射服务
47 60  
48 61 // Serve方法在lis上接受传入连接,为每个连接创建一个ServerTransport和server的goroutine。
49 62 // 该goroutine读取gRPC请求,然后调用已注册的处理程序来响应它们。
50   - utils.Sugar.Debugf("Start LoginServer listening on %d", conf.GlobalConf.AccountConf.Port)
  63 + utils.Sugar.Debugf("Start LoginServer listening on %d with TLS", conf.GlobalConf.AccountConf.Port)
51 64  
52 65 return s.GrpcServer.Serve(lis)
53 66 }
... ... @@ -88,15 +101,27 @@ func (s *GameServer)Start() error {
88 101  
89 102 models.InitGameServerModels()
90 103  
  104 + var opts []grpc.ServerOption
  105 + //TLS
  106 + creds, err := credentials.NewServerTLSFromFile("keys/server.pem", "keys/server.key")
  107 + if err != nil {
  108 + utils.Sugar.Errorf("Failed to generate credentials %v", err)
  109 + return err
  110 + }
  111 + opts = append(opts, grpc.Creds(creds))
  112 +
  113 + //拦截器
  114 + opts = append(opts, grpc.UnaryInterceptor(GameServerInterceptor))
  115 +
91 116 //new一个grpc
92   - s.GrpcServer = grpc.NewServer(grpc.UnaryInterceptor(GameServerInterceptor))
  117 + s.GrpcServer = grpc.NewServer(opts...)
93 118  
94 119 pb.RegisterGameServer(s.GrpcServer, s)
95 120 reflection.Register(s.GrpcServer) //在给定的gRPC服务器上注册服务器反射服务
96 121  
97 122 // Serve方法在lis上接受传入连接,为每个连接创建一个ServerTransport和server的goroutine。
98 123 // 该goroutine读取gRPC请求,然后调用已注册的处理程序来响应它们。
99   - utils.Sugar.Debugf("Start GameServer listening on %d", conf.GlobalConf.GameConf.Port)
  124 + utils.Sugar.Debugf("Start GameServer listening on %d with TLS", conf.GlobalConf.GameConf.Port)
100 125 return s.GrpcServer.Serve(lis)
101 126 }
102 127  
... ...
doc/cret.md 0 → 100644
... ... @@ -0,0 +1,46 @@
  1 +## 证书制作
  2 +
  3 +## ca证书生成流程(在升级版本的GO中已经不支持读取)
  4 +使用-subj参数,指定服务器的相关信息,与之前的不同,此时不需要引导输入。
  5 +```shell
  6 +openssl req \
  7 + -x509 \
  8 + -nodes \
  9 + -newkey rsa:2048 \
  10 + -keyout ca.key \
  11 + -out ca.crt \
  12 + -days 3650 \
  13 + -subj "/C=CN/ST=ZheJiang/L=ZheJiang/O=Global/CN=pro2d Security/OU=IT Department/CN=pro2d"
  14 +```
  15 +
  16 +### SAN证书生成(使用开启扩展SAN的证书)
  17 +生成私钥
  18 +```shell
  19 +$ openssl genpkey -algorithm RSA -out server.key
  20 +```
  21 +根据私钥server.key生成证书请求文件server.csr:
  22 +```shell
  23 +openssl req -new -nodes -key server.key -out server.csr -days 3650 \
  24 + -subj "/C=CN/OU=IT/O=Global/CN=pro2d/L=ZheJiang" \
  25 + -config openssl.cnf -extensions v3_req
  26 +```
  27 +验证证书CSR的扩展属性
  28 +```shell
  29 +$ openssl req -noout -text -in server.csr
  30 +```
  31 +
  32 +生成san证书
  33 +```shell
  34 +$ openssl x509 -req -days 365 -in server.csr -out server.pem \
  35 + -CA ca.crt -CAkey ca.key -CAcreateserial \
  36 + -extfile openssl.cnf -extensions v3_req
  37 +```
  38 +* server.csr是前面步骤生成的证书请求文件。
  39 +* ca.crt & ca.key 是CA证书文件和key,用来对server.csr进行签名认证。
  40 +
  41 +查看SAN信息在证书内容
  42 +```shell
  43 +$ openssl x509 -noout -text -in server.pem
  44 +```
  45 +
  46 +现在证书已经生成完毕, server.pem 和 server.key正式我们需要的证书和密钥
... ...
keys/ca.crt 0 → 100644
... ... @@ -0,0 +1,21 @@
  1 +-----BEGIN CERTIFICATE-----
  2 +MIIDiDCCAnACCQDvizTzfA5snjANBgkqhkiG9w0BAQsFADCBhTELMAkGA1UEBhMC
  3 +Q04xETAPBgNVBAgMCFpoZUppYW5nMREwDwYDVQQHDAhaaGVKaWFuZzEPMA0GA1UE
  4 +CgwGR2xvYmFsMRcwFQYDVQQDDA5wcm8yZCBTZWN1cml0eTEWMBQGA1UECwwNSVQg
  5 +RGVwYXJ0bWVudDEOMAwGA1UEAwwFcHJvMmQwHhcNMjIwMjIyMDYwNzIzWhcNMzIw
  6 +MjIwMDYwNzIzWjCBhTELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFpoZUppYW5nMREw
  7 +DwYDVQQHDAhaaGVKaWFuZzEPMA0GA1UECgwGR2xvYmFsMRcwFQYDVQQDDA5wcm8y
  8 +ZCBTZWN1cml0eTEWMBQGA1UECwwNSVQgRGVwYXJ0bWVudDEOMAwGA1UEAwwFcHJv
  9 +MmQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC+eik5acnrHwEz+Zwb
  10 +j7R1eCb9VrJymCii7PtCeeqCZaRBuUYUwKSkEdv367HRH00CW2tYCMMsoBqBewxO
  11 +tBwa+1rpCbUvqWdmipMTjE4vmA5Kb50HS3/VxTlnICPb0P0CO2kArrktEPg3W7c5
  12 +Xwmbe8BvYtdEV/BkLUG0+NQbXfXgkKBEs6t1FOqtJAubURann3wAH9pLIDRUcj5B
  13 +QzM9b+8qvTjLLj4/uaac4b7X6bfVyaeX8cWOXLHDYEXwIdlRXYz4l+gSVO/EKIgA
  14 +5QfwLJTWuxnzcM/klOPsIamQtOYIwEkc1KiCNPZ2CAkzXFspKweR1IwsDM8N/hUU
  15 +BWxZAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAFzY2wB6phXffFwAcGQZx9FYY9S5
  16 +3L0Xm4mji50+e6UA+N9MjO/4SXNpjt6qMQ3zwSUalapmr8uh9DWLsjRv6HRvgoIm
  17 +9tkx8UQkjOoFKcee2+Z780BjsR7SI1HS3VLKUOjm8avKazFGGxjsOtayxzGytAT2
  18 +DK1ubsqSbiK7hFFJqU3cUPP7D3pJOAKaBnLq8MA63vSGTsz2sQUR2Y5DKMXpIhEQ
  19 +zlSQvMzsQXv0yll3DhPv76yV6ZKQzCHCoqaPBNU+9QhrWFqIP2QXLR5smeFqOGQM
  20 +ngBFwwv9ysSMmcpanMePiuuvXykZiPJpknxdAxry6+A8+/KQ/07hFAHarbI=
  21 +-----END CERTIFICATE-----
... ...
keys/ca.key 0 → 100644
... ... @@ -0,0 +1,28 @@
  1 +-----BEGIN PRIVATE KEY-----
  2 +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC+eik5acnrHwEz
  3 ++Zwbj7R1eCb9VrJymCii7PtCeeqCZaRBuUYUwKSkEdv367HRH00CW2tYCMMsoBqB
  4 +ewxOtBwa+1rpCbUvqWdmipMTjE4vmA5Kb50HS3/VxTlnICPb0P0CO2kArrktEPg3
  5 +W7c5Xwmbe8BvYtdEV/BkLUG0+NQbXfXgkKBEs6t1FOqtJAubURann3wAH9pLIDRU
  6 +cj5BQzM9b+8qvTjLLj4/uaac4b7X6bfVyaeX8cWOXLHDYEXwIdlRXYz4l+gSVO/E
  7 +KIgA5QfwLJTWuxnzcM/klOPsIamQtOYIwEkc1KiCNPZ2CAkzXFspKweR1IwsDM8N
  8 +/hUUBWxZAgMBAAECggEATl/Jkpwavyn0vsQYHacVo7gaoucHaet93PwRrpqniZv0
  9 +6C4pzeQuWmwWzH4onll4wF2JX6HLXRNLlLdiqwelAN0n3PdnnALiTuj593MlwKOa
  10 +Tbp7LEM+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0bRDhjEpZDwjyK0
  26 +gJUWilI8DYTvMa/fdpuVtc5qJErwfNmhRIWiWWryE1OrD1dprQYZzeAy/0+5HDrb
  27 +lhQhMGXOJbhiQdKPMcwGbw==
  28 +-----END PRIVATE KEY-----
... ...
keys/ca.srl 0 → 100644
... ... @@ -0,0 +1 @@
  1 +D4E715D41B6F9424
... ...
keys/openssl.cnf 0 → 100644
... ... @@ -0,0 +1,357 @@
  1 +#
  2 +# OpenSSL example configuration file.
  3 +# This is mostly being used for generation of certificate requests.
  4 +#
  5 +
  6 +# Note that you can include other files from the main configuration
  7 +# file using the .include directive.
  8 +#.include filename
  9 +
  10 +# This definition stops the following lines choking if HOME isn't
  11 +# defined.
  12 +HOME = .
  13 +RANDFILE = $ENV::HOME/.rnd
  14 +
  15 +# Extra OBJECT IDENTIFIER info:
  16 +#oid_file = $ENV::HOME/.oid
  17 +oid_section = new_oids
  18 +
  19 +# To use this configuration file with the "-extfile" option of the
  20 +# "openssl x509" utility, name here the section containing the
  21 +# X.509v3 extensions to use:
  22 +# extensions =
  23 +# (Alternatively, use a configuration file that has only
  24 +# X.509v3 extensions in its main [= default] section.)
  25 +
  26 +[ new_oids ]
  27 +
  28 +# We can add new OIDs in here for use by 'ca', 'req' and 'ts'.
  29 +# Add a simple OID like this:
  30 +# testoid1=1.2.3.4
  31 +# Or use config file substitution like this:
  32 +# testoid2=${testoid1}.5.6
  33 +
  34 +# Policies used by the TSA examples.
  35 +tsa_policy1 = 1.2.3.4.1
  36 +tsa_policy2 = 1.2.3.4.5.6
  37 +tsa_policy3 = 1.2.3.4.5.7
  38 +
  39 +####################################################################
  40 +[ ca ]
  41 +default_ca = CA_default # The default ca section
  42 +
  43 +####################################################################
  44 +[ CA_default ]
  45 +
  46 +dir = ./demoCA # Where everything is kept
  47 +certs = $dir/certs # Where the issued certs are kept
  48 +crl_dir = $dir/crl # Where the issued crl are kept
  49 +database = $dir/index.txt # database index file.
  50 +#unique_subject = no # Set to 'no' to allow creation of
  51 + # several certs with same subject.
  52 +new_certs_dir = $dir/newcerts # default place for new certs.
  53 +
  54 +certificate = $dir/cacert.pem # The CA certificate
  55 +serial = $dir/serial # The current serial number
  56 +crlnumber = $dir/crlnumber # the current crl number
  57 + # must be commented out to leave a V1 CRL
  58 +crl = $dir/crl.pem # The current CRL
  59 +private_key = $dir/private/cakey.pem# The private key
  60 +RANDFILE = $dir/private/.rand # private random number file
  61 +
  62 +x509_extensions = usr_cert # The extensions to add to the cert
  63 +
  64 +# Comment out the following two lines for the "traditional"
  65 +# (and highly broken) format.
  66 +name_opt = ca_default # Subject Name options
  67 +cert_opt = ca_default # Certificate field options
  68 +
  69 +# Extension copying option: use with caution.
  70 +copy_extensions = copy
  71 +
  72 +# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
  73 +# so this is commented out by default to leave a V1 CRL.
  74 +# crlnumber must also be commented out to leave a V1 CRL.
  75 +# crl_extensions = crl_ext
  76 +
  77 +default_days = 365 # how long to certify for
  78 +default_crl_days= 30 # how long before next CRL
  79 +default_md = default # use public key default MD
  80 +preserve = no # keep passed DN ordering
  81 +
  82 +# A few difference way of specifying how similar the request should look
  83 +# For type CA, the listed attributes must be the same, and the optional
  84 +# and supplied fields are just that :-)
  85 +policy = policy_match
  86 +
  87 +# For the CA policy
  88 +[ policy_match ]
  89 +countryName = match
  90 +stateOrProvinceName = match
  91 +organizationName = match
  92 +organizationalUnitName = optional
  93 +commonName = supplied
  94 +emailAddress = optional
  95 +
  96 +# For the 'anything' policy
  97 +# At this point in time, you must list all acceptable 'object'
  98 +# types.
  99 +[ policy_anything ]
  100 +countryName = optional
  101 +stateOrProvinceName = optional
  102 +localityName = optional
  103 +organizationName = optional
  104 +organizationalUnitName = optional
  105 +commonName = supplied
  106 +emailAddress = optional
  107 +
  108 +####################################################################
  109 +[ req ]
  110 +default_bits = 2048
  111 +default_keyfile = privkey.pem
  112 +distinguished_name = req_distinguished_name
  113 +attributes = req_attributes
  114 +x509_extensions = v3_ca # The extensions to add to the self signed cert
  115 +
  116 +# Passwords for private keys if not present they will be prompted for
  117 +# input_password = secret
  118 +# output_password = secret
  119 +
  120 +# This sets a mask for permitted string types. There are several options.
  121 +# default: PrintableString, T61String, BMPString.
  122 +# pkix : PrintableString, BMPString (PKIX recommendation before 2004)
  123 +# utf8only: only UTF8Strings (PKIX recommendation after 2004).
  124 +# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
  125 +# MASK:XXXX a literal mask value.
  126 +# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
  127 +string_mask = utf8only
  128 +
  129 +req_extensions = v3_req # The extensions to add to a certificate request
  130 +
  131 +[ req_distinguished_name ]
  132 +countryName = Country Name (2 letter code)
  133 +countryName_default = AU
  134 +countryName_min = 2
  135 +countryName_max = 2
  136 +
  137 +stateOrProvinceName = State or Province Name (full name)
  138 +stateOrProvinceName_default = Some-State
  139 +
  140 +localityName = Locality Name (eg, city)
  141 +
  142 +0.organizationName = Organization Name (eg, company)
  143 +0.organizationName_default = Internet Widgits Pty Ltd
  144 +
  145 +# we can do this but it is not needed normally :-)
  146 +#1.organizationName = Second Organization Name (eg, company)
  147 +#1.organizationName_default = World Wide Web Pty Ltd
  148 +
  149 +organizationalUnitName = Organizational Unit Name (eg, section)
  150 +#organizationalUnitName_default =
  151 +
  152 +commonName = Common Name (e.g. server FQDN or YOUR name)
  153 +commonName_max = 64
  154 +
  155 +emailAddress = Email Address
  156 +emailAddress_max = 64
  157 +
  158 +# SET-ex3 = SET extension number 3
  159 +
  160 +[ req_attributes ]
  161 +challengePassword = A challenge password
  162 +challengePassword_min = 4
  163 +challengePassword_max = 20
  164 +
  165 +unstructuredName = An optional company name
  166 +
  167 +[ usr_cert ]
  168 +
  169 +# These extensions are added when 'ca' signs a request.
  170 +
  171 +# This goes against PKIX guidelines but some CAs do it and some software
  172 +# requires this to avoid interpreting an end user certificate as a CA.
  173 +
  174 +basicConstraints=CA:FALSE
  175 +
  176 +# Here are some examples of the usage of nsCertType. If it is omitted
  177 +# the certificate can be used for anything *except* object signing.
  178 +
  179 +# This is OK for an SSL server.
  180 +# nsCertType = server
  181 +
  182 +# For an object signing certificate this would be used.
  183 +# nsCertType = objsign
  184 +
  185 +# For normal client use this is typical
  186 +# nsCertType = client, email
  187 +
  188 +# and for everything including object signing:
  189 +# nsCertType = client, email, objsign
  190 +
  191 +# This is typical in keyUsage for a client certificate.
  192 +# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
  193 +
  194 +# This will be displayed in Netscape's comment listbox.
  195 +nsComment = "OpenSSL Generated Certificate"
  196 +
  197 +# PKIX recommendations harmless if included in all certificates.
  198 +subjectKeyIdentifier=hash
  199 +authorityKeyIdentifier=keyid,issuer
  200 +
  201 +# This stuff is for subjectAltName and issuerAltname.
  202 +# Import the email address.
  203 +# subjectAltName=email:copy
  204 +# An alternative to produce certificates that aren't
  205 +# deprecated according to PKIX.
  206 +# subjectAltName=email:move
  207 +
  208 +# Copy subject details
  209 +# issuerAltName=issuer:copy
  210 +
  211 +#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
  212 +#nsBaseUrl
  213 +#nsRevocationUrl
  214 +#nsRenewalUrl
  215 +#nsCaPolicyUrl
  216 +#nsSslServerName
  217 +
  218 +# This is required for TSA certificates.
  219 +# extendedKeyUsage = critical,timeStamping
  220 +
  221 +[ v3_req ]
  222 +
  223 +# Extensions to add to a certificate request
  224 +
  225 +basicConstraints = CA:FALSE
  226 +keyUsage = nonRepudiation, digitalSignature, keyEncipherment
  227 +subjectAltName = @alt_names
  228 +
  229 +[alt_names]
  230 +DNS.1 = localhost
  231 +DNS.1 = pro2d
  232 +
  233 +[ v3_ca ]
  234 +
  235 +
  236 +# Extensions for a typical CA
  237 +
  238 +
  239 +# PKIX recommendation.
  240 +
  241 +subjectKeyIdentifier=hash
  242 +
  243 +authorityKeyIdentifier=keyid:always,issuer
  244 +
  245 +basicConstraints = critical,CA:true
  246 +
  247 +# Key usage: this is typical for a CA certificate. However since it will
  248 +# prevent it being used as an test self-signed certificate it is best
  249 +# left out by default.
  250 +# keyUsage = cRLSign, keyCertSign
  251 +
  252 +# Some might want this also
  253 +# nsCertType = sslCA, emailCA
  254 +
  255 +# Include email address in subject alt name: another PKIX recommendation
  256 +# subjectAltName=email:copy
  257 +# Copy issuer details
  258 +# issuerAltName=issuer:copy
  259 +
  260 +# DER hex encoding of an extension: beware experts only!
  261 +# obj=DER:02:03
  262 +# Where 'obj' is a standard or added object
  263 +# You can even override a supported extension:
  264 +# basicConstraints= critical, DER:30:03:01:01:FF
  265 +
  266 +[ crl_ext ]
  267 +
  268 +# CRL extensions.
  269 +# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
  270 +
  271 +# issuerAltName=issuer:copy
  272 +authorityKeyIdentifier=keyid:always
  273 +
  274 +[ proxy_cert_ext ]
  275 +# These extensions should be added when creating a proxy certificate
  276 +
  277 +# This goes against PKIX guidelines but some CAs do it and some software
  278 +# requires this to avoid interpreting an end user certificate as a CA.
  279 +
  280 +basicConstraints=CA:FALSE
  281 +
  282 +# Here are some examples of the usage of nsCertType. If it is omitted
  283 +# the certificate can be used for anything *except* object signing.
  284 +
  285 +# This is OK for an SSL server.
  286 +# nsCertType = server
  287 +
  288 +# For an object signing certificate this would be used.
  289 +# nsCertType = objsign
  290 +
  291 +# For normal client use this is typical
  292 +# nsCertType = client, email
  293 +
  294 +# and for everything including object signing:
  295 +# nsCertType = client, email, objsign
  296 +
  297 +# This is typical in keyUsage for a client certificate.
  298 +# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
  299 +
  300 +# This will be displayed in Netscape's comment listbox.
  301 +nsComment = "OpenSSL Generated Certificate"
  302 +
  303 +# PKIX recommendations harmless if included in all certificates.
  304 +subjectKeyIdentifier=hash
  305 +authorityKeyIdentifier=keyid,issuer
  306 +
  307 +# This stuff is for subjectAltName and issuerAltname.
  308 +# Import the email address.
  309 +# subjectAltName=email:copy
  310 +# An alternative to produce certificates that aren't
  311 +# deprecated according to PKIX.
  312 +# subjectAltName=email:move
  313 +
  314 +# Copy subject details
  315 +# issuerAltName=issuer:copy
  316 +
  317 +#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
  318 +#nsBaseUrl
  319 +#nsRevocationUrl
  320 +#nsRenewalUrl
  321 +#nsCaPolicyUrl
  322 +#nsSslServerName
  323 +
  324 +# This really needs to be in place for it to be a proxy certificate.
  325 +proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo
  326 +
  327 +####################################################################
  328 +[ tsa ]
  329 +
  330 +default_tsa = tsa_config1 # the default TSA section
  331 +
  332 +[ tsa_config1 ]
  333 +
  334 +# These are used by the TSA reply generation only.
  335 +dir = ./demoCA # TSA root directory
  336 +serial = $dir/tsaserial # The current serial number (mandatory)
  337 +crypto_device = builtin # OpenSSL engine to use for signing
  338 +signer_cert = $dir/tsacert.pem # The TSA signing certificate
  339 + # (optional)
  340 +certs = $dir/cacert.pem # Certificate chain to include in reply
  341 + # (optional)
  342 +signer_key = $dir/private/tsakey.pem # The TSA private key (optional)
  343 +signer_digest = sha256 # Signing digest to use. (Optional)
  344 +default_policy = tsa_policy1 # Policy if request did not specify it
  345 + # (optional)
  346 +other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional)
  347 +digests = sha1, sha256, sha384, sha512 # Acceptable message digests (mandatory)
  348 +accuracy = secs:1, millisecs:500, microsecs:100 # (optional)
  349 +clock_precision_digits = 0 # number of digits after dot. (optional)
  350 +ordering = yes # Is ordering defined for timestamps?
  351 + # (optional, default: no)
  352 +tsa_name = yes # Must the TSA name be included in the reply?
  353 + # (optional, default: no)
  354 +ess_cert_id_chain = no # Must the ESS cert id chain be included?
  355 + # (optional, default: no)
  356 +ess_cert_id_alg = sha1 # algorithm to compute certificate
  357 + # identifier (optional, default: sha1)
... ...
keys/server.csr 0 → 100644
... ... @@ -0,0 +1,18 @@
  1 +-----BEGIN CERTIFICATE REQUEST-----
  2 +MIICzjCCAbYCAQAwTjELMAkGA1UEBhMCQ04xCzAJBgNVBAsMAklUMQ8wDQYDVQQK
  3 +DAZHbG9iYWwxDjAMBgNVBAMMBXBybzJkMREwDwYDVQQHDAhaaGVKaWFuZzCCASIw
  4 +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANd6QZzSWnpQN74TzcN8WoUYwutx
  5 +mSQB2x8h17VBlVJepFpog1ujWoZUl1xQ7lgPr2DhMHM1qNkroahdI/AZGj2juuC2
  6 +1vg2WZ4Wa/8vsICGPvTTqEd7VSpY66ybk0kd7rWFp7naXLBGFVf7mi3RPDW9Y3mO
  7 +cyTR7Iwtm1iBhMDS5uczUOzrZ63yd0FA62iizKqckfwXVsYFUJqdG0uUUt88whnt
  8 +qAPRKrkuU+Y6I+jo+C6gf7i7RTLz6aI01QYLRMENmJI5NqFcJ4cNKWsLIWY3sDz0
  9 +XoyueWl3tHrjiX4TmZM28OZAHl/rKd0lQpQEB0UiHe7At/8xZHLDol6ip4MCAwEA
  10 +AaA7MDkGCSqGSIb3DQEJDjEsMCowCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwEAYD
  11 +VR0RBAkwB4IFcHJvMmQwDQYJKoZIhvcNAQELBQADggEBAKytMdGU/yLmC5uUUdWd
  12 +0dnqloVaCiyPCjWBsv44H2jiVq2UT5nQeiTWJ2hAt6RIsIUyymrY6Flg6ZpCfKaa
  13 +yqYNDBzDwGAJAWTHicNyQT/Uxb5rn+6R4qfyBOkFGaPlF9dxCgKRTqaSX5WmWFE6
  14 +FzsAiwYcc8fb+ioljnN3NJ7MZLz0n6RU52PCwYDbgC941t3yFa5R1wHgGoK1/93B
  15 +2/+IUNWaS8XRGfRe3SUZ2rSTuCgr8J9jfsvsx3qga3KWTpyAxOe3vexKpnhO9Xw0
  16 +wDVRApMMmlPVrLrKMNGSCXNaBT0JdTpFn9CJFheJs9jqv+q77T8qpqln9leMgtvF
  17 +ql8=
  18 +-----END CERTIFICATE REQUEST-----
... ...
keys/server.key 0 → 100644
... ... @@ -0,0 +1,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WaBXPOGZ26KboWoClrStHow2VCnqEx9pewA6+4m0cv4JXiCXa1/uoY9XxHRI
  18 +Tz3BSycqAOFTGhz9Z+Nq8Rc9PIFYBHzjyVgrsXiO86TKK33uE7GAqXZGB+MeDOf0
  19 +FSb8a8vooQKBgDkR715oKkjRnZH+KQ+dRm/nSSSLWlyFj3TxO4pxgQ6GpwnYR0hd
  20 +PwE7YPEc0XGehcNa2z2WCc7Rc/NATUhvAIMWgPYAqI9nFvC6Cc+Gym+Eo14am+fi
  21 +t+SO1a+V6qB8htn/wOt7REqjpZePTfrbbX2guDLs8Jw/1rhvJjlkzfa/AoGBAJ+/
  22 +RbQsPZDjoE6b+CKgKqf0v2+YNcBB3MVVRzn48N17i4VW8ILstM6Did3KC36rWXP7
  23 +gDOAshPyR9p/dx2hSsYeyZV8bt5G2q8iCpR5sdmvWwks+iQ5eRiImGRT33Qrpei4
  24 +8ocpwgUrm1OHSJ8ebSjAumVospBqhjmgaP8+F1rhAoGBAIaDv/yhFtEQaldOkK8X
  25 +YQACUmt3YflHxWmdlmulVqAOCDH8nV3YYHGFIEatBx2w0OBvxoLtw5HTvEq1pFcF
  26 +4cL8ulNQeozLTsGfNeLgIe7NOb6T54QZFVg1+dgePtBIsab59sZE3817j5zmkr0A
  27 +DywcIXZFRNuOpQgL2I4JF7PX
  28 +-----END PRIVATE KEY-----
... ...
keys/server.pem 0 → 100644
... ... @@ -0,0 +1,21 @@
  1 +-----BEGIN CERTIFICATE-----
  2 +MIIDgzCCAmugAwIBAgIJANTnFdQbb5QkMA0GCSqGSIb3DQEBBQUAMIGFMQswCQYD
  3 +VQQGEwJDTjERMA8GA1UECAwIWmhlSmlhbmcxETAPBgNVBAcMCFpoZUppYW5nMQ8w
  4 +DQYDVQQKDAZHbG9iYWwxFzAVBgNVBAMMDnBybzJkIFNlY3VyaXR5MRYwFAYDVQQL
  5 +DA1JVCBEZXBhcnRtZW50MQ4wDAYDVQQDDAVwcm8yZDAeFw0yMjAyMjIwNjA3MjNa
  6 +Fw0yMzAyMjIwNjA3MjNaME4xCzAJBgNVBAYTAkNOMQswCQYDVQQLDAJJVDEPMA0G
  7 +A1UECgwGR2xvYmFsMQ4wDAYDVQQDDAVwcm8yZDERMA8GA1UEBwwIWmhlSmlhbmcw
  8 +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXekGc0lp6UDe+E83DfFqF
  9 +GMLrcZkkAdsfIde1QZVSXqRaaINbo1qGVJdcUO5YD69g4TBzNajZK6GoXSPwGRo9
  10 +o7rgttb4NlmeFmv/L7CAhj7006hHe1UqWOusm5NJHe61hae52lywRhVX+5ot0Tw1
  11 +vWN5jnMk0eyMLZtYgYTA0ubnM1Ds62et8ndBQOtoosyqnJH8F1bGBVCanRtLlFLf
  12 +PMIZ7agD0Sq5LlPmOiPo6PguoH+4u0Uy8+miNNUGC0TBDZiSOTahXCeHDSlrCyFm
  13 +N7A89F6Mrnlpd7R644l+E5mTNvDmQB5f6yndJUKUBAdFIh3uwLf/MWRyw6JeoqeD
  14 +AgMBAAGjLDAqMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgXgMBAGA1UdEQQJMAeCBXBy
  15 +bzJkMA0GCSqGSIb3DQEBBQUAA4IBAQBmCfF8okV2lCH7KBA4gKjKh7dCKdLiTBWP
  16 +q5qHNt2dYOmZAi3CFlgvAqgg30/Ql9pILN+0XJTL7TnJRhvvCZ/eObtCJbmZD/jP
  17 +SzmowtCyydPtj/DGmxY+UQZk4KqtRuDGD5LQRU2VYzHJvrf9yEse2uIf+uUetx7b
  18 +r2dklvP+H33rMB1k3hswHg2/EmhJxtfvQCLQX8+Ofur/wW8uYKFj3hTabzYfcew3
  19 +Uw1/5a+rLHBLAA1SYoviwnoNgiVBxkWkfEH7tsheFapVULltz3vll013Q69RBXVw
  20 +K7QloFM0LgoJKM+X65ymUGPGL3F4WvewSOiWyFLQdW43wRlUUNkq
  21 +-----END CERTIFICATE-----
... ...
test/client.go
... ... @@ -6,6 +6,7 @@ import (
6 6 "context"
7 7 "fmt"
8 8 "google.golang.org/grpc"
  9 + "google.golang.org/grpc/credentials"
9 10 _ "pro2d/conf"
10 11 "pro2d/protos/pb"
11 12 "pro2d/utils"
... ... @@ -31,7 +32,20 @@ func Register(c pb.LoginClient, phone, password string) error {
31 32 func Login(loginUri, token, uid string) {
32 33 var opts []grpc.DialOption
33 34 // 指定自定义认证
34   - opts = append(opts, grpc.WithPerRPCCredentials(&utils.AuthToken{Token: token}), grpc.WithInsecure())
  35 + opts = append(opts, grpc.WithPerRPCCredentials(&utils.AuthToken{Token: token}))
  36 + if TLS {
  37 + // TLS连接
  38 + creds, err := credentials.NewClientTLSFromFile("keys/server.pem", ServerName)
  39 + if err != nil {
  40 + utils.Sugar.Fatalf("Failed to create TLS credentials %v", err)
  41 + return
  42 + }
  43 + opts = append(opts, grpc.WithTransportCredentials(creds))
  44 +
  45 + }else{
  46 + opts = append(opts, grpc.WithInsecure())
  47 + }
  48 +
35 49 gameConn, err := grpc.Dial(loginUri, opts...)
36 50 if err != nil {
37 51 utils.Sugar.Errorf("game conn err: %v", err)
... ... @@ -66,15 +80,35 @@ func Login(loginUri, token, uid string) {
66 80 utils.Sugar.Debugf("login successful role: %v", role)
67 81 }
68 82  
  83 +const (
  84 + TLS = true
  85 + ServerName = "pro2d"
  86 +)
  87 +
69 88 func main() {
70   - conn, err := grpc.Dial("localhost:8848", grpc.WithInsecure())
  89 +
  90 + var opts []grpc.DialOption
  91 + if TLS {
  92 + // TLS连接
  93 + creds, err := credentials.NewClientTLSFromFile("keys/server.pem", ServerName)
  94 + if err != nil {
  95 + utils.Sugar.Fatalf("Failed to create TLS credentials %v", err)
  96 + return
  97 + }
  98 + opts = append(opts, grpc.WithTransportCredentials(creds))
  99 +
  100 + }else{
  101 + opts = append(opts, grpc.WithInsecure())
  102 + }
  103 +
  104 + conn, err := grpc.Dial("localhost:8848", opts...)
71 105 if err != nil {
72 106 utils.Sugar.Errorf("conn err: %v", err)
73 107 return
74 108 }
75 109 defer conn.Close()
76 110 c := pb.NewLoginClient(conn)
77   - err = Register(c,"17683852936", "123456")
  111 + //err = Register(c,"17683852936", "123456")
78 112 //if err != nil {
79 113 // utils.Sugar.Errorf("register err: %v", err)
80 114 // return
... ... @@ -97,4 +131,4 @@ func main() {
97 131 if len(rsp.GameService) >0 {
98 132 Login(rsp.GameService[0].Address, rsp.Token, rsp.Uid)
99 133 }
100 134 -}
  135 +}
101 136 \ No newline at end of file
... ...