diff --git a/Makefile b/Makefile index 89cbb36..b13a6c2 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ all: ge build run -ge: +gen: protoc -I./protos --go_out=./protos --go-grpc_out=./protos ./protos/*proto protoc-go-inject-tag -input=./protos/pb/*.pb.go @@ -16,4 +16,19 @@ build: go build -o bin/account account.go go build -o bin/game game.go +cert: + openssl req \ + -x509 \ + -nodes \ + -newkey rsa:2048 \ + -keyout keys/ca.key \ + -out keys/ca.crt \ + -days 3650 \ + -subj "/C=CN/ST=ZheJiang/L=ZheJiang/O=Global/CN=pro2d Security/OU=IT Department/CN=pro2d" + openssl genpkey -algorithm RSA -out keys/server.key + 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 + 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 + + + .PHONY: all build protos test \ No newline at end of file diff --git a/README.md b/README.md index 7ebca25..f6344f8 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,10 @@ $ go install google.golang.org/protobuf/cmd/protoc-gen-go $ go get google.golang.org/grpc/cmd/protoc-gen-go-grpc $ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc ``` +## 文档 +[证书制作](doc/cret.md) + + ## Usage 编译 & 运行 ```shell diff --git a/actions/server.go b/actions/server.go index 3d362b2..c9dcf19 100644 --- a/actions/server.go +++ b/actions/server.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "google.golang.org/grpc" + "google.golang.org/grpc/credentials" "google.golang.org/grpc/reflection" "pro2d/conf" "pro2d/models" @@ -39,15 +40,27 @@ func (s *LoginServer)Start() error { models.InitAccountServerModels() + var opts []grpc.ServerOption + //TLS + creds, err := credentials.NewServerTLSFromFile("keys/server.pem", "keys/server.key") + if err != nil { + utils.Sugar.Errorf("Failed to generate credentials %v", err) + return err + } + opts = append(opts, grpc.Creds(creds)) + + //拦截器 + opts = append(opts, grpc.UnaryInterceptor(AccountServerInterceptor)) + //new一个grpc - s.GrpcServer = grpc.NewServer(grpc.UnaryInterceptor(AccountServerInterceptor)) + s.GrpcServer = grpc.NewServer(opts...) pb.RegisterLoginServer(s.GrpcServer, s) reflection.Register(s.GrpcServer) //在给定的gRPC服务器上注册服务器反射服务 // Serve方法在lis上接受传入连接,为每个连接创建一个ServerTransport和server的goroutine。 // 该goroutine读取gRPC请求,然后调用已注册的处理程序来响应它们。 - utils.Sugar.Debugf("Start LoginServer listening on %d", conf.GlobalConf.AccountConf.Port) + utils.Sugar.Debugf("Start LoginServer listening on %d with TLS", conf.GlobalConf.AccountConf.Port) return s.GrpcServer.Serve(lis) } @@ -88,15 +101,27 @@ func (s *GameServer)Start() error { models.InitGameServerModels() + var opts []grpc.ServerOption + //TLS + creds, err := credentials.NewServerTLSFromFile("keys/server.pem", "keys/server.key") + if err != nil { + utils.Sugar.Errorf("Failed to generate credentials %v", err) + return err + } + opts = append(opts, grpc.Creds(creds)) + + //拦截器 + opts = append(opts, grpc.UnaryInterceptor(GameServerInterceptor)) + //new一个grpc - s.GrpcServer = grpc.NewServer(grpc.UnaryInterceptor(GameServerInterceptor)) + s.GrpcServer = grpc.NewServer(opts...) pb.RegisterGameServer(s.GrpcServer, s) reflection.Register(s.GrpcServer) //在给定的gRPC服务器上注册服务器反射服务 // Serve方法在lis上接受传入连接,为每个连接创建一个ServerTransport和server的goroutine。 // 该goroutine读取gRPC请求,然后调用已注册的处理程序来响应它们。 - utils.Sugar.Debugf("Start GameServer listening on %d", conf.GlobalConf.GameConf.Port) + utils.Sugar.Debugf("Start GameServer listening on %d with TLS", conf.GlobalConf.GameConf.Port) return s.GrpcServer.Serve(lis) } diff --git a/doc/cret.md b/doc/cret.md new file mode 100644 index 0000000..6e585a6 --- /dev/null +++ b/doc/cret.md @@ -0,0 +1,46 @@ +## 证书制作 + +## ca证书生成流程(在升级版本的GO中已经不支持读取) +使用-subj参数,指定服务器的相关信息,与之前的不同,此时不需要引导输入。 +```shell +openssl req \ + -x509 \ + -nodes \ + -newkey rsa:2048 \ + -keyout ca.key \ + -out ca.crt \ + -days 3650 \ + -subj "/C=CN/ST=ZheJiang/L=ZheJiang/O=Global/CN=pro2d Security/OU=IT Department/CN=pro2d" +``` + +### SAN证书生成(使用开启扩展SAN的证书) +生成私钥 +```shell +$ openssl genpkey -algorithm RSA -out server.key +``` +根据私钥server.key生成证书请求文件server.csr: +```shell +openssl req -new -nodes -key server.key -out server.csr -days 3650 \ + -subj "/C=CN/OU=IT/O=Global/CN=pro2d/L=ZheJiang" \ + -config openssl.cnf -extensions v3_req +``` +验证证书CSR的扩展属性 +```shell +$ openssl req -noout -text -in server.csr +``` + +生成san证书 +```shell +$ openssl x509 -req -days 365 -in server.csr -out server.pem \ + -CA ca.crt -CAkey ca.key -CAcreateserial \ + -extfile openssl.cnf -extensions v3_req +``` +* server.csr是前面步骤生成的证书请求文件。 +* ca.crt & ca.key 是CA证书文件和key,用来对server.csr进行签名认证。 + +查看SAN信息在证书内容 +```shell +$ openssl x509 -noout -text -in server.pem +``` + +现在证书已经生成完毕, server.pem 和 server.key正式我们需要的证书和密钥 diff --git a/keys/ca.crt b/keys/ca.crt new file mode 100644 index 0000000..231a8ec --- /dev/null +++ b/keys/ca.crt @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDiDCCAnACCQDvizTzfA5snjANBgkqhkiG9w0BAQsFADCBhTELMAkGA1UEBhMC +Q04xETAPBgNVBAgMCFpoZUppYW5nMREwDwYDVQQHDAhaaGVKaWFuZzEPMA0GA1UE +CgwGR2xvYmFsMRcwFQYDVQQDDA5wcm8yZCBTZWN1cml0eTEWMBQGA1UECwwNSVQg +RGVwYXJ0bWVudDEOMAwGA1UEAwwFcHJvMmQwHhcNMjIwMjIyMDYwNzIzWhcNMzIw +MjIwMDYwNzIzWjCBhTELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFpoZUppYW5nMREw +DwYDVQQHDAhaaGVKaWFuZzEPMA0GA1UECgwGR2xvYmFsMRcwFQYDVQQDDA5wcm8y +ZCBTZWN1cml0eTEWMBQGA1UECwwNSVQgRGVwYXJ0bWVudDEOMAwGA1UEAwwFcHJv +MmQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC+eik5acnrHwEz+Zwb +j7R1eCb9VrJymCii7PtCeeqCZaRBuUYUwKSkEdv367HRH00CW2tYCMMsoBqBewxO +tBwa+1rpCbUvqWdmipMTjE4vmA5Kb50HS3/VxTlnICPb0P0CO2kArrktEPg3W7c5 +Xwmbe8BvYtdEV/BkLUG0+NQbXfXgkKBEs6t1FOqtJAubURann3wAH9pLIDRUcj5B +QzM9b+8qvTjLLj4/uaac4b7X6bfVyaeX8cWOXLHDYEXwIdlRXYz4l+gSVO/EKIgA +5QfwLJTWuxnzcM/klOPsIamQtOYIwEkc1KiCNPZ2CAkzXFspKweR1IwsDM8N/hUU +BWxZAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAFzY2wB6phXffFwAcGQZx9FYY9S5 +3L0Xm4mji50+e6UA+N9MjO/4SXNpjt6qMQ3zwSUalapmr8uh9DWLsjRv6HRvgoIm +9tkx8UQkjOoFKcee2+Z780BjsR7SI1HS3VLKUOjm8avKazFGGxjsOtayxzGytAT2 +DK1ubsqSbiK7hFFJqU3cUPP7D3pJOAKaBnLq8MA63vSGTsz2sQUR2Y5DKMXpIhEQ +zlSQvMzsQXv0yll3DhPv76yV6ZKQzCHCoqaPBNU+9QhrWFqIP2QXLR5smeFqOGQM +ngBFwwv9ysSMmcpanMePiuuvXykZiPJpknxdAxry6+A8+/KQ/07hFAHarbI= +-----END CERTIFICATE----- diff --git a/keys/ca.key b/keys/ca.key new file mode 100644 index 0000000..2993d6f --- /dev/null +++ b/keys/ca.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC+eik5acnrHwEz ++Zwbj7R1eCb9VrJymCii7PtCeeqCZaRBuUYUwKSkEdv367HRH00CW2tYCMMsoBqB +ewxOtBwa+1rpCbUvqWdmipMTjE4vmA5Kb50HS3/VxTlnICPb0P0CO2kArrktEPg3 +W7c5Xwmbe8BvYtdEV/BkLUG0+NQbXfXgkKBEs6t1FOqtJAubURann3wAH9pLIDRU +cj5BQzM9b+8qvTjLLj4/uaac4b7X6bfVyaeX8cWOXLHDYEXwIdlRXYz4l+gSVO/E +KIgA5QfwLJTWuxnzcM/klOPsIamQtOYIwEkc1KiCNPZ2CAkzXFspKweR1IwsDM8N +/hUUBWxZAgMBAAECggEATl/Jkpwavyn0vsQYHacVo7gaoucHaet93PwRrpqniZv0 +6C4pzeQuWmwWzH4onll4wF2JX6HLXRNLlLdiqwelAN0n3PdnnALiTuj593MlwKOa +Tbp7LEM+iGEsa2hoGMx3LnHvlJ5QB2ESIQUV8P9P3rAe0DYlSTO98BpHDQXNkKx0 +UPo85k5IgnjueeHdxn8lokQsKXN5R8bS9GduRaEyMR/SHrT3T6YmRKr666N/AQas +7dDe9qGwTpUFympP3PEX/VHQsF9x3/ng6wbRsiijKsUUeGpbslulKi5kHw3j+5Eo +YkeHjH/iMySd41m4oszM4QmCYr5t49AAQl2bYW3b4QKBgQDxFW297lVS8O+z/ANR +yVKI7iejiLKdpc0wlZiFWkAKCve+SCGJ2GZ907NKzLq1O6/byhs7XCu229oLvIFm +/e1sCxdHR/bEf3CTlgoQYXiya0jCgF2GUM/hZpvWZHL0ECZfhwPsks4NWhdKEPyD +9XWpjfC0qlVh18xAF7Zyrw4sTQKBgQDKQyp/wJub0UZ9FmaLORpxr7rO5pROEFov +SiwoJ8gYLo7eU0QT6ipVD/vOTE2+5FdYuk41euYZLOzR0N72kqddUlVAtq9bly92 +sjtvM8iPSGU5cN0D+Up9KT0ZU3zIXH1mVFHsNmm62uN4B3s9Rs+0JvLTI6OwqLAW +LtyqK09WPQKBgEOFP+YpASaoqknbdEaMvxvwr5Nirrvueuh3jW8T1sm5Rqe5ZgNI +Y3QsPZPegRBPNjK1iSj36JpfOtN8qTViOwO+m3dwVVG1a586L3llAzvdRlSLRSZg +LciwR0clfPiUKVsp4lR4zVL5/3nUBhUjQyAIy/idmCo+GUt+GLBIDQ0lAoGABnmT ++Lb/xEM00HhRHA/d6tnHTyxOfxlC6dSkCT0MyMlkxXVA7qpGZKa4VuhWbM/+g9ai +/k9K4m9vvV/EY3xaY0BpfkLa5kG2wUP/ZxXvS7bzlp0oViI64jrZu9/SVM+xK/9z +B+7N/69WLNeAeHu11nyQtXWkndkome0yHzh3t7kCgYBM/U2XmSx0LYHqe+699NXy +4ey3B4IQHb55Fw8LNiaI96ylQG43kNQpZUELjaPBTpQ1a76uL0bRDhjEpZDwjyK0 +gJUWilI8DYTvMa/fdpuVtc5qJErwfNmhRIWiWWryE1OrD1dprQYZzeAy/0+5HDrb +lhQhMGXOJbhiQdKPMcwGbw== +-----END PRIVATE KEY----- diff --git a/keys/ca.srl b/keys/ca.srl new file mode 100644 index 0000000..a71a80f --- /dev/null +++ b/keys/ca.srl @@ -0,0 +1 @@ +D4E715D41B6F9424 diff --git a/keys/openssl.cnf b/keys/openssl.cnf new file mode 100644 index 0000000..eea897a --- /dev/null +++ b/keys/openssl.cnf @@ -0,0 +1,357 @@ +# +# OpenSSL example configuration file. +# This is mostly being used for generation of certificate requests. +# + +# Note that you can include other files from the main configuration +# file using the .include directive. +#.include filename + +# This definition stops the following lines choking if HOME isn't +# defined. +HOME = . +RANDFILE = $ENV::HOME/.rnd + +# Extra OBJECT IDENTIFIER info: +#oid_file = $ENV::HOME/.oid +oid_section = new_oids + +# To use this configuration file with the "-extfile" option of the +# "openssl x509" utility, name here the section containing the +# X.509v3 extensions to use: +# extensions = +# (Alternatively, use a configuration file that has only +# X.509v3 extensions in its main [= default] section.) + +[ new_oids ] + +# We can add new OIDs in here for use by 'ca', 'req' and 'ts'. +# Add a simple OID like this: +# testoid1=1.2.3.4 +# Or use config file substitution like this: +# testoid2=${testoid1}.5.6 + +# Policies used by the TSA examples. +tsa_policy1 = 1.2.3.4.1 +tsa_policy2 = 1.2.3.4.5.6 +tsa_policy3 = 1.2.3.4.5.7 + +#################################################################### +[ ca ] +default_ca = CA_default # The default ca section + +#################################################################### +[ CA_default ] + +dir = ./demoCA # Where everything is kept +certs = $dir/certs # Where the issued certs are kept +crl_dir = $dir/crl # Where the issued crl are kept +database = $dir/index.txt # database index file. +#unique_subject = no # Set to 'no' to allow creation of + # several certs with same subject. +new_certs_dir = $dir/newcerts # default place for new certs. + +certificate = $dir/cacert.pem # The CA certificate +serial = $dir/serial # The current serial number +crlnumber = $dir/crlnumber # the current crl number + # must be commented out to leave a V1 CRL +crl = $dir/crl.pem # The current CRL +private_key = $dir/private/cakey.pem# The private key +RANDFILE = $dir/private/.rand # private random number file + +x509_extensions = usr_cert # The extensions to add to the cert + +# Comment out the following two lines for the "traditional" +# (and highly broken) format. +name_opt = ca_default # Subject Name options +cert_opt = ca_default # Certificate field options + +# Extension copying option: use with caution. +copy_extensions = copy + +# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs +# so this is commented out by default to leave a V1 CRL. +# crlnumber must also be commented out to leave a V1 CRL. +# crl_extensions = crl_ext + +default_days = 365 # how long to certify for +default_crl_days= 30 # how long before next CRL +default_md = default # use public key default MD +preserve = no # keep passed DN ordering + +# A few difference way of specifying how similar the request should look +# For type CA, the listed attributes must be the same, and the optional +# and supplied fields are just that :-) +policy = policy_match + +# For the CA policy +[ policy_match ] +countryName = match +stateOrProvinceName = match +organizationName = match +organizationalUnitName = optional +commonName = supplied +emailAddress = optional + +# For the 'anything' policy +# At this point in time, you must list all acceptable 'object' +# types. +[ policy_anything ] +countryName = optional +stateOrProvinceName = optional +localityName = optional +organizationName = optional +organizationalUnitName = optional +commonName = supplied +emailAddress = optional + +#################################################################### +[ req ] +default_bits = 2048 +default_keyfile = privkey.pem +distinguished_name = req_distinguished_name +attributes = req_attributes +x509_extensions = v3_ca # The extensions to add to the self signed cert + +# Passwords for private keys if not present they will be prompted for +# input_password = secret +# output_password = secret + +# This sets a mask for permitted string types. There are several options. +# default: PrintableString, T61String, BMPString. +# pkix : PrintableString, BMPString (PKIX recommendation before 2004) +# utf8only: only UTF8Strings (PKIX recommendation after 2004). +# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings). +# MASK:XXXX a literal mask value. +# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings. +string_mask = utf8only + +req_extensions = v3_req # The extensions to add to a certificate request + +[ req_distinguished_name ] +countryName = Country Name (2 letter code) +countryName_default = AU +countryName_min = 2 +countryName_max = 2 + +stateOrProvinceName = State or Province Name (full name) +stateOrProvinceName_default = Some-State + +localityName = Locality Name (eg, city) + +0.organizationName = Organization Name (eg, company) +0.organizationName_default = Internet Widgits Pty Ltd + +# we can do this but it is not needed normally :-) +#1.organizationName = Second Organization Name (eg, company) +#1.organizationName_default = World Wide Web Pty Ltd + +organizationalUnitName = Organizational Unit Name (eg, section) +#organizationalUnitName_default = + +commonName = Common Name (e.g. server FQDN or YOUR name) +commonName_max = 64 + +emailAddress = Email Address +emailAddress_max = 64 + +# SET-ex3 = SET extension number 3 + +[ req_attributes ] +challengePassword = A challenge password +challengePassword_min = 4 +challengePassword_max = 20 + +unstructuredName = An optional company name + +[ usr_cert ] + +# These extensions are added when 'ca' signs a request. + +# This goes against PKIX guidelines but some CAs do it and some software +# requires this to avoid interpreting an end user certificate as a CA. + +basicConstraints=CA:FALSE + +# Here are some examples of the usage of nsCertType. If it is omitted +# the certificate can be used for anything *except* object signing. + +# This is OK for an SSL server. +# nsCertType = server + +# For an object signing certificate this would be used. +# nsCertType = objsign + +# For normal client use this is typical +# nsCertType = client, email + +# and for everything including object signing: +# nsCertType = client, email, objsign + +# This is typical in keyUsage for a client certificate. +# keyUsage = nonRepudiation, digitalSignature, keyEncipherment + +# This will be displayed in Netscape's comment listbox. +nsComment = "OpenSSL Generated Certificate" + +# PKIX recommendations harmless if included in all certificates. +subjectKeyIdentifier=hash +authorityKeyIdentifier=keyid,issuer + +# This stuff is for subjectAltName and issuerAltname. +# Import the email address. +# subjectAltName=email:copy +# An alternative to produce certificates that aren't +# deprecated according to PKIX. +# subjectAltName=email:move + +# Copy subject details +# issuerAltName=issuer:copy + +#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem +#nsBaseUrl +#nsRevocationUrl +#nsRenewalUrl +#nsCaPolicyUrl +#nsSslServerName + +# This is required for TSA certificates. +# extendedKeyUsage = critical,timeStamping + +[ v3_req ] + +# Extensions to add to a certificate request + +basicConstraints = CA:FALSE +keyUsage = nonRepudiation, digitalSignature, keyEncipherment +subjectAltName = @alt_names + +[alt_names] +DNS.1 = localhost +DNS.1 = pro2d + +[ v3_ca ] + + +# Extensions for a typical CA + + +# PKIX recommendation. + +subjectKeyIdentifier=hash + +authorityKeyIdentifier=keyid:always,issuer + +basicConstraints = critical,CA:true + +# Key usage: this is typical for a CA certificate. However since it will +# prevent it being used as an test self-signed certificate it is best +# left out by default. +# keyUsage = cRLSign, keyCertSign + +# Some might want this also +# nsCertType = sslCA, emailCA + +# Include email address in subject alt name: another PKIX recommendation +# subjectAltName=email:copy +# Copy issuer details +# issuerAltName=issuer:copy + +# DER hex encoding of an extension: beware experts only! +# obj=DER:02:03 +# Where 'obj' is a standard or added object +# You can even override a supported extension: +# basicConstraints= critical, DER:30:03:01:01:FF + +[ crl_ext ] + +# CRL extensions. +# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL. + +# issuerAltName=issuer:copy +authorityKeyIdentifier=keyid:always + +[ proxy_cert_ext ] +# These extensions should be added when creating a proxy certificate + +# This goes against PKIX guidelines but some CAs do it and some software +# requires this to avoid interpreting an end user certificate as a CA. + +basicConstraints=CA:FALSE + +# Here are some examples of the usage of nsCertType. If it is omitted +# the certificate can be used for anything *except* object signing. + +# This is OK for an SSL server. +# nsCertType = server + +# For an object signing certificate this would be used. +# nsCertType = objsign + +# For normal client use this is typical +# nsCertType = client, email + +# and for everything including object signing: +# nsCertType = client, email, objsign + +# This is typical in keyUsage for a client certificate. +# keyUsage = nonRepudiation, digitalSignature, keyEncipherment + +# This will be displayed in Netscape's comment listbox. +nsComment = "OpenSSL Generated Certificate" + +# PKIX recommendations harmless if included in all certificates. +subjectKeyIdentifier=hash +authorityKeyIdentifier=keyid,issuer + +# This stuff is for subjectAltName and issuerAltname. +# Import the email address. +# subjectAltName=email:copy +# An alternative to produce certificates that aren't +# deprecated according to PKIX. +# subjectAltName=email:move + +# Copy subject details +# issuerAltName=issuer:copy + +#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem +#nsBaseUrl +#nsRevocationUrl +#nsRenewalUrl +#nsCaPolicyUrl +#nsSslServerName + +# This really needs to be in place for it to be a proxy certificate. +proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo + +#################################################################### +[ tsa ] + +default_tsa = tsa_config1 # the default TSA section + +[ tsa_config1 ] + +# These are used by the TSA reply generation only. +dir = ./demoCA # TSA root directory +serial = $dir/tsaserial # The current serial number (mandatory) +crypto_device = builtin # OpenSSL engine to use for signing +signer_cert = $dir/tsacert.pem # The TSA signing certificate + # (optional) +certs = $dir/cacert.pem # Certificate chain to include in reply + # (optional) +signer_key = $dir/private/tsakey.pem # The TSA private key (optional) +signer_digest = sha256 # Signing digest to use. (Optional) +default_policy = tsa_policy1 # Policy if request did not specify it + # (optional) +other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional) +digests = sha1, sha256, sha384, sha512 # Acceptable message digests (mandatory) +accuracy = secs:1, millisecs:500, microsecs:100 # (optional) +clock_precision_digits = 0 # number of digits after dot. (optional) +ordering = yes # Is ordering defined for timestamps? + # (optional, default: no) +tsa_name = yes # Must the TSA name be included in the reply? + # (optional, default: no) +ess_cert_id_chain = no # Must the ESS cert id chain be included? + # (optional, default: no) +ess_cert_id_alg = sha1 # algorithm to compute certificate + # identifier (optional, default: sha1) diff --git a/keys/server.csr b/keys/server.csr new file mode 100644 index 0000000..f4ff1d3 --- /dev/null +++ b/keys/server.csr @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICzjCCAbYCAQAwTjELMAkGA1UEBhMCQ04xCzAJBgNVBAsMAklUMQ8wDQYDVQQK +DAZHbG9iYWwxDjAMBgNVBAMMBXBybzJkMREwDwYDVQQHDAhaaGVKaWFuZzCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANd6QZzSWnpQN74TzcN8WoUYwutx +mSQB2x8h17VBlVJepFpog1ujWoZUl1xQ7lgPr2DhMHM1qNkroahdI/AZGj2juuC2 +1vg2WZ4Wa/8vsICGPvTTqEd7VSpY66ybk0kd7rWFp7naXLBGFVf7mi3RPDW9Y3mO +cyTR7Iwtm1iBhMDS5uczUOzrZ63yd0FA62iizKqckfwXVsYFUJqdG0uUUt88whnt +qAPRKrkuU+Y6I+jo+C6gf7i7RTLz6aI01QYLRMENmJI5NqFcJ4cNKWsLIWY3sDz0 +XoyueWl3tHrjiX4TmZM28OZAHl/rKd0lQpQEB0UiHe7At/8xZHLDol6ip4MCAwEA +AaA7MDkGCSqGSIb3DQEJDjEsMCowCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwEAYD +VR0RBAkwB4IFcHJvMmQwDQYJKoZIhvcNAQELBQADggEBAKytMdGU/yLmC5uUUdWd +0dnqloVaCiyPCjWBsv44H2jiVq2UT5nQeiTWJ2hAt6RIsIUyymrY6Flg6ZpCfKaa +yqYNDBzDwGAJAWTHicNyQT/Uxb5rn+6R4qfyBOkFGaPlF9dxCgKRTqaSX5WmWFE6 +FzsAiwYcc8fb+ioljnN3NJ7MZLz0n6RU52PCwYDbgC941t3yFa5R1wHgGoK1/93B +2/+IUNWaS8XRGfRe3SUZ2rSTuCgr8J9jfsvsx3qga3KWTpyAxOe3vexKpnhO9Xw0 +wDVRApMMmlPVrLrKMNGSCXNaBT0JdTpFn9CJFheJs9jqv+q77T8qpqln9leMgtvF +ql8= +-----END CERTIFICATE REQUEST----- diff --git a/keys/server.key b/keys/server.key new file mode 100644 index 0000000..7c918fa --- /dev/null +++ b/keys/server.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDXekGc0lp6UDe+ +E83DfFqFGMLrcZkkAdsfIde1QZVSXqRaaINbo1qGVJdcUO5YD69g4TBzNajZK6Go +XSPwGRo9o7rgttb4NlmeFmv/L7CAhj7006hHe1UqWOusm5NJHe61hae52lywRhVX ++5ot0Tw1vWN5jnMk0eyMLZtYgYTA0ubnM1Ds62et8ndBQOtoosyqnJH8F1bGBVCa +nRtLlFLfPMIZ7agD0Sq5LlPmOiPo6PguoH+4u0Uy8+miNNUGC0TBDZiSOTahXCeH +DSlrCyFmN7A89F6Mrnlpd7R644l+E5mTNvDmQB5f6yndJUKUBAdFIh3uwLf/MWRy +w6JeoqeDAgMBAAECggEAecQ5zdBFlvc7+OsiDUV5tdsfU4PXgbSWykoKpwBPzMN0 +5y5GhQOUBXNKMb3+Yr9CYWIASirZpxfz+7vesjDNVmXvFkvcwVmdXSvYjdW6TXcP +nrT5VKPKpeqoC9vC6L/EhMnp1aojVO3V4+ln4FpsRwYmb6vjP7xti22+as6OYZQC +ygC0f0hCWO4t67BrH7lmA+l5KHmfQtl0t7iJ3yXLXz1EMtbVKwoOuNxBnfxTdPuE +a2ke5G8S8nN5ZCe2FpaN+BxQQ4NpRnc0aK5O02EibA5Ix2ItLnXs+MluNC91veVS +WRAbEbvFBwZx624u0NEe5oAIFhS2m4VeKVUmqfdxwQKBgQD/fuE13vXtSV30I4Sj +lZJfr9r+T/gGA6wIna0RhfaXnKDS9SjzFgF6MS2QSRKYzjPCzfGQIxq368NLrEdu +lCLNQF9Z06lVNeuJT84VPYm4P/wheIG7LhNmBHsnkTzYnupFrlB22TnmStDSfuGp +dhlyAUGN91pg/mP/nO1ZrTPpowKBgQDX5ycPD8dOUz2ACoKCGEf37hbcfqBmKd7a +JGYOWaBXPOGZ26KboWoClrStHow2VCnqEx9pewA6+4m0cv4JXiCXa1/uoY9XxHRI +Tz3BSycqAOFTGhz9Z+Nq8Rc9PIFYBHzjyVgrsXiO86TKK33uE7GAqXZGB+MeDOf0 +FSb8a8vooQKBgDkR715oKkjRnZH+KQ+dRm/nSSSLWlyFj3TxO4pxgQ6GpwnYR0hd +PwE7YPEc0XGehcNa2z2WCc7Rc/NATUhvAIMWgPYAqI9nFvC6Cc+Gym+Eo14am+fi +t+SO1a+V6qB8htn/wOt7REqjpZePTfrbbX2guDLs8Jw/1rhvJjlkzfa/AoGBAJ+/ +RbQsPZDjoE6b+CKgKqf0v2+YNcBB3MVVRzn48N17i4VW8ILstM6Did3KC36rWXP7 +gDOAshPyR9p/dx2hSsYeyZV8bt5G2q8iCpR5sdmvWwks+iQ5eRiImGRT33Qrpei4 +8ocpwgUrm1OHSJ8ebSjAumVospBqhjmgaP8+F1rhAoGBAIaDv/yhFtEQaldOkK8X +YQACUmt3YflHxWmdlmulVqAOCDH8nV3YYHGFIEatBx2w0OBvxoLtw5HTvEq1pFcF +4cL8ulNQeozLTsGfNeLgIe7NOb6T54QZFVg1+dgePtBIsab59sZE3817j5zmkr0A +DywcIXZFRNuOpQgL2I4JF7PX +-----END PRIVATE KEY----- diff --git a/keys/server.pem b/keys/server.pem new file mode 100644 index 0000000..13b643b --- /dev/null +++ b/keys/server.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDgzCCAmugAwIBAgIJANTnFdQbb5QkMA0GCSqGSIb3DQEBBQUAMIGFMQswCQYD +VQQGEwJDTjERMA8GA1UECAwIWmhlSmlhbmcxETAPBgNVBAcMCFpoZUppYW5nMQ8w +DQYDVQQKDAZHbG9iYWwxFzAVBgNVBAMMDnBybzJkIFNlY3VyaXR5MRYwFAYDVQQL +DA1JVCBEZXBhcnRtZW50MQ4wDAYDVQQDDAVwcm8yZDAeFw0yMjAyMjIwNjA3MjNa +Fw0yMzAyMjIwNjA3MjNaME4xCzAJBgNVBAYTAkNOMQswCQYDVQQLDAJJVDEPMA0G +A1UECgwGR2xvYmFsMQ4wDAYDVQQDDAVwcm8yZDERMA8GA1UEBwwIWmhlSmlhbmcw +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXekGc0lp6UDe+E83DfFqF +GMLrcZkkAdsfIde1QZVSXqRaaINbo1qGVJdcUO5YD69g4TBzNajZK6GoXSPwGRo9 +o7rgttb4NlmeFmv/L7CAhj7006hHe1UqWOusm5NJHe61hae52lywRhVX+5ot0Tw1 +vWN5jnMk0eyMLZtYgYTA0ubnM1Ds62et8ndBQOtoosyqnJH8F1bGBVCanRtLlFLf +PMIZ7agD0Sq5LlPmOiPo6PguoH+4u0Uy8+miNNUGC0TBDZiSOTahXCeHDSlrCyFm +N7A89F6Mrnlpd7R644l+E5mTNvDmQB5f6yndJUKUBAdFIh3uwLf/MWRyw6JeoqeD +AgMBAAGjLDAqMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgXgMBAGA1UdEQQJMAeCBXBy +bzJkMA0GCSqGSIb3DQEBBQUAA4IBAQBmCfF8okV2lCH7KBA4gKjKh7dCKdLiTBWP +q5qHNt2dYOmZAi3CFlgvAqgg30/Ql9pILN+0XJTL7TnJRhvvCZ/eObtCJbmZD/jP +SzmowtCyydPtj/DGmxY+UQZk4KqtRuDGD5LQRU2VYzHJvrf9yEse2uIf+uUetx7b +r2dklvP+H33rMB1k3hswHg2/EmhJxtfvQCLQX8+Ofur/wW8uYKFj3hTabzYfcew3 +Uw1/5a+rLHBLAA1SYoviwnoNgiVBxkWkfEH7tsheFapVULltz3vll013Q69RBXVw +K7QloFM0LgoJKM+X65ymUGPGL3F4WvewSOiWyFLQdW43wRlUUNkq +-----END CERTIFICATE----- diff --git a/test/client.go b/test/client.go index 6fb3082..a7bbbf9 100644 --- a/test/client.go +++ b/test/client.go @@ -6,6 +6,7 @@ import ( "context" "fmt" "google.golang.org/grpc" + "google.golang.org/grpc/credentials" _ "pro2d/conf" "pro2d/protos/pb" "pro2d/utils" @@ -31,7 +32,20 @@ func Register(c pb.LoginClient, phone, password string) error { func Login(loginUri, token, uid string) { var opts []grpc.DialOption // 指定自定义认证 - opts = append(opts, grpc.WithPerRPCCredentials(&utils.AuthToken{Token: token}), grpc.WithInsecure()) + opts = append(opts, grpc.WithPerRPCCredentials(&utils.AuthToken{Token: token})) + if TLS { + // TLS连接 + creds, err := credentials.NewClientTLSFromFile("keys/server.pem", ServerName) + if err != nil { + utils.Sugar.Fatalf("Failed to create TLS credentials %v", err) + return + } + opts = append(opts, grpc.WithTransportCredentials(creds)) + + }else{ + opts = append(opts, grpc.WithInsecure()) + } + gameConn, err := grpc.Dial(loginUri, opts...) if err != nil { utils.Sugar.Errorf("game conn err: %v", err) @@ -66,15 +80,35 @@ func Login(loginUri, token, uid string) { utils.Sugar.Debugf("login successful role: %v", role) } +const ( + TLS = true + ServerName = "pro2d" +) + func main() { - conn, err := grpc.Dial("localhost:8848", grpc.WithInsecure()) + + var opts []grpc.DialOption + if TLS { + // TLS连接 + creds, err := credentials.NewClientTLSFromFile("keys/server.pem", ServerName) + if err != nil { + utils.Sugar.Fatalf("Failed to create TLS credentials %v", err) + return + } + opts = append(opts, grpc.WithTransportCredentials(creds)) + + }else{ + opts = append(opts, grpc.WithInsecure()) + } + + conn, err := grpc.Dial("localhost:8848", opts...) if err != nil { utils.Sugar.Errorf("conn err: %v", err) return } defer conn.Close() c := pb.NewLoginClient(conn) - err = Register(c,"17683852936", "123456") + //err = Register(c,"17683852936", "123456") //if err != nil { // utils.Sugar.Errorf("register err: %v", err) // return @@ -97,4 +131,4 @@ func main() { if len(rsp.GameService) >0 { Login(rsp.GameService[0].Address, rsp.Token, rsp.Uid) } -} +} \ No newline at end of file -- libgit2 0.21.2