tls.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package credentials
  19. import (
  20. "context"
  21. "crypto/tls"
  22. "crypto/x509"
  23. "fmt"
  24. "io/ioutil"
  25. "net"
  26. "google.golang.org/grpc/credentials/internal"
  27. )
  28. // TLSInfo contains the auth information for a TLS authenticated connection.
  29. // It implements the AuthInfo interface.
  30. type TLSInfo struct {
  31. State tls.ConnectionState
  32. CommonAuthInfo
  33. }
  34. // AuthType returns the type of TLSInfo as a string.
  35. func (t TLSInfo) AuthType() string {
  36. return "tls"
  37. }
  38. // GetSecurityValue returns security info requested by channelz.
  39. func (t TLSInfo) GetSecurityValue() ChannelzSecurityValue {
  40. v := &TLSChannelzSecurityValue{
  41. StandardName: cipherSuiteLookup[t.State.CipherSuite],
  42. }
  43. // Currently there's no way to get LocalCertificate info from tls package.
  44. if len(t.State.PeerCertificates) > 0 {
  45. v.RemoteCertificate = t.State.PeerCertificates[0].Raw
  46. }
  47. return v
  48. }
  49. // tlsCreds is the credentials required for authenticating a connection using TLS.
  50. type tlsCreds struct {
  51. // TLS configuration
  52. config *tls.Config
  53. }
  54. func (c tlsCreds) Info() ProtocolInfo {
  55. return ProtocolInfo{
  56. SecurityProtocol: "tls",
  57. SecurityVersion: "1.2",
  58. ServerName: c.config.ServerName,
  59. }
  60. }
  61. func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {
  62. // use local cfg to avoid clobbering ServerName if using multiple endpoints
  63. cfg := cloneTLSConfig(c.config)
  64. if cfg.ServerName == "" {
  65. serverName, _, err := net.SplitHostPort(authority)
  66. if err != nil {
  67. // If the authority had no host port or if the authority cannot be parsed, use it as-is.
  68. serverName = authority
  69. }
  70. cfg.ServerName = serverName
  71. }
  72. conn := tls.Client(rawConn, cfg)
  73. errChannel := make(chan error, 1)
  74. go func() {
  75. errChannel <- conn.Handshake()
  76. close(errChannel)
  77. }()
  78. select {
  79. case err := <-errChannel:
  80. if err != nil {
  81. conn.Close()
  82. return nil, nil, err
  83. }
  84. case <-ctx.Done():
  85. conn.Close()
  86. return nil, nil, ctx.Err()
  87. }
  88. return internal.WrapSyscallConn(rawConn, conn), TLSInfo{conn.ConnectionState(), CommonAuthInfo{PrivacyAndIntegrity}}, nil
  89. }
  90. func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
  91. conn := tls.Server(rawConn, c.config)
  92. if err := conn.Handshake(); err != nil {
  93. conn.Close()
  94. return nil, nil, err
  95. }
  96. return internal.WrapSyscallConn(rawConn, conn), TLSInfo{conn.ConnectionState(), CommonAuthInfo{PrivacyAndIntegrity}}, nil
  97. }
  98. func (c *tlsCreds) Clone() TransportCredentials {
  99. return NewTLS(c.config)
  100. }
  101. func (c *tlsCreds) OverrideServerName(serverNameOverride string) error {
  102. c.config.ServerName = serverNameOverride
  103. return nil
  104. }
  105. const alpnProtoStrH2 = "h2"
  106. func appendH2ToNextProtos(ps []string) []string {
  107. for _, p := range ps {
  108. if p == alpnProtoStrH2 {
  109. return ps
  110. }
  111. }
  112. ret := make([]string, 0, len(ps)+1)
  113. ret = append(ret, ps...)
  114. return append(ret, alpnProtoStrH2)
  115. }
  116. // NewTLS uses c to construct a TransportCredentials based on TLS.
  117. func NewTLS(c *tls.Config) TransportCredentials {
  118. tc := &tlsCreds{cloneTLSConfig(c)}
  119. tc.config.NextProtos = appendH2ToNextProtos(tc.config.NextProtos)
  120. return tc
  121. }
  122. // NewClientTLSFromCert constructs TLS credentials from the input certificate for client.
  123. // serverNameOverride is for testing only. If set to a non empty string,
  124. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
  125. func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
  126. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
  127. }
  128. // NewClientTLSFromFile constructs TLS credentials from the input certificate file for client.
  129. // serverNameOverride is for testing only. If set to a non empty string,
  130. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
  131. func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {
  132. b, err := ioutil.ReadFile(certFile)
  133. if err != nil {
  134. return nil, err
  135. }
  136. cp := x509.NewCertPool()
  137. if !cp.AppendCertsFromPEM(b) {
  138. return nil, fmt.Errorf("credentials: failed to append certificates")
  139. }
  140. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil
  141. }
  142. // NewServerTLSFromCert constructs TLS credentials from the input certificate for server.
  143. func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
  144. return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
  145. }
  146. // NewServerTLSFromFile constructs TLS credentials from the input certificate file and key
  147. // file for server.
  148. func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
  149. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  150. if err != nil {
  151. return nil, err
  152. }
  153. return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
  154. }
  155. // TLSChannelzSecurityValue defines the struct that TLS protocol should return
  156. // from GetSecurityValue(), containing security info like cipher and certificate used.
  157. //
  158. // This API is EXPERIMENTAL.
  159. type TLSChannelzSecurityValue struct {
  160. ChannelzSecurityValue
  161. StandardName string
  162. LocalCertificate []byte
  163. RemoteCertificate []byte
  164. }
  165. var cipherSuiteLookup = map[uint16]string{
  166. tls.TLS_RSA_WITH_RC4_128_SHA: "TLS_RSA_WITH_RC4_128_SHA",
  167. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
  168. tls.TLS_RSA_WITH_AES_128_CBC_SHA: "TLS_RSA_WITH_AES_128_CBC_SHA",
  169. tls.TLS_RSA_WITH_AES_256_CBC_SHA: "TLS_RSA_WITH_AES_256_CBC_SHA",
  170. tls.TLS_RSA_WITH_AES_128_GCM_SHA256: "TLS_RSA_WITH_AES_128_GCM_SHA256",
  171. tls.TLS_RSA_WITH_AES_256_GCM_SHA384: "TLS_RSA_WITH_AES_256_GCM_SHA384",
  172. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
  173. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  174. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  175. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
  176. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
  177. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  178. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  179. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  180. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  181. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  182. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  183. tls.TLS_FALLBACK_SCSV: "TLS_FALLBACK_SCSV",
  184. tls.TLS_RSA_WITH_AES_128_CBC_SHA256: "TLS_RSA_WITH_AES_128_CBC_SHA256",
  185. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
  186. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
  187. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
  188. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
  189. }
  190. // cloneTLSConfig returns a shallow clone of the exported
  191. // fields of cfg, ignoring the unexported sync.Once, which
  192. // contains a mutex and must not be copied.
  193. //
  194. // If cfg is nil, a new zero tls.Config is returned.
  195. //
  196. // TODO: inline this function if possible.
  197. func cloneTLSConfig(cfg *tls.Config) *tls.Config {
  198. if cfg == nil {
  199. return &tls.Config{}
  200. }
  201. return cfg.Clone()
  202. }