tls.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. }
  33. // AuthType returns the type of TLSInfo as a string.
  34. func (t TLSInfo) AuthType() string {
  35. return "tls"
  36. }
  37. // GetSecurityValue returns security info requested by channelz.
  38. func (t TLSInfo) GetSecurityValue() ChannelzSecurityValue {
  39. v := &TLSChannelzSecurityValue{
  40. StandardName: cipherSuiteLookup[t.State.CipherSuite],
  41. }
  42. // Currently there's no way to get LocalCertificate info from tls package.
  43. if len(t.State.PeerCertificates) > 0 {
  44. v.RemoteCertificate = t.State.PeerCertificates[0].Raw
  45. }
  46. return v
  47. }
  48. // tlsCreds is the credentials required for authenticating a connection using TLS.
  49. type tlsCreds struct {
  50. // TLS configuration
  51. config *tls.Config
  52. }
  53. func (c tlsCreds) Info() ProtocolInfo {
  54. return ProtocolInfo{
  55. SecurityProtocol: "tls",
  56. SecurityVersion: "1.2",
  57. ServerName: c.config.ServerName,
  58. }
  59. }
  60. func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {
  61. // use local cfg to avoid clobbering ServerName if using multiple endpoints
  62. cfg := cloneTLSConfig(c.config)
  63. if cfg.ServerName == "" {
  64. serverName, _, err := net.SplitHostPort(authority)
  65. if err != nil {
  66. // If the authority had no host port or if the authority cannot be parsed, use it as-is.
  67. serverName = authority
  68. }
  69. cfg.ServerName = serverName
  70. }
  71. conn := tls.Client(rawConn, cfg)
  72. errChannel := make(chan error, 1)
  73. go func() {
  74. errChannel <- conn.Handshake()
  75. }()
  76. select {
  77. case err := <-errChannel:
  78. if err != nil {
  79. return nil, nil, err
  80. }
  81. case <-ctx.Done():
  82. return nil, nil, ctx.Err()
  83. }
  84. return internal.WrapSyscallConn(rawConn, conn), TLSInfo{conn.ConnectionState()}, nil
  85. }
  86. func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
  87. conn := tls.Server(rawConn, c.config)
  88. if err := conn.Handshake(); err != nil {
  89. return nil, nil, err
  90. }
  91. return internal.WrapSyscallConn(rawConn, conn), TLSInfo{conn.ConnectionState()}, nil
  92. }
  93. func (c *tlsCreds) Clone() TransportCredentials {
  94. return NewTLS(c.config)
  95. }
  96. func (c *tlsCreds) OverrideServerName(serverNameOverride string) error {
  97. c.config.ServerName = serverNameOverride
  98. return nil
  99. }
  100. const alpnProtoStrH2 = "h2"
  101. func appendH2ToNextProtos(ps []string) []string {
  102. for _, p := range ps {
  103. if p == alpnProtoStrH2 {
  104. return ps
  105. }
  106. }
  107. ret := make([]string, 0, len(ps)+1)
  108. ret = append(ret, ps...)
  109. return append(ret, alpnProtoStrH2)
  110. }
  111. // NewTLS uses c to construct a TransportCredentials based on TLS.
  112. func NewTLS(c *tls.Config) TransportCredentials {
  113. tc := &tlsCreds{cloneTLSConfig(c)}
  114. tc.config.NextProtos = appendH2ToNextProtos(tc.config.NextProtos)
  115. return tc
  116. }
  117. // NewClientTLSFromCert constructs TLS credentials from the input certificate for client.
  118. // serverNameOverride is for testing only. If set to a non empty string,
  119. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
  120. func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
  121. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
  122. }
  123. // NewClientTLSFromFile constructs TLS credentials from the input certificate file for client.
  124. // serverNameOverride is for testing only. If set to a non empty string,
  125. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
  126. func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {
  127. b, err := ioutil.ReadFile(certFile)
  128. if err != nil {
  129. return nil, err
  130. }
  131. cp := x509.NewCertPool()
  132. if !cp.AppendCertsFromPEM(b) {
  133. return nil, fmt.Errorf("credentials: failed to append certificates")
  134. }
  135. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil
  136. }
  137. // NewServerTLSFromCert constructs TLS credentials from the input certificate for server.
  138. func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
  139. return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
  140. }
  141. // NewServerTLSFromFile constructs TLS credentials from the input certificate file and key
  142. // file for server.
  143. func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
  144. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  145. if err != nil {
  146. return nil, err
  147. }
  148. return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
  149. }
  150. // TLSChannelzSecurityValue defines the struct that TLS protocol should return
  151. // from GetSecurityValue(), containing security info like cipher and certificate used.
  152. //
  153. // This API is EXPERIMENTAL.
  154. type TLSChannelzSecurityValue struct {
  155. ChannelzSecurityValue
  156. StandardName string
  157. LocalCertificate []byte
  158. RemoteCertificate []byte
  159. }
  160. var cipherSuiteLookup = map[uint16]string{
  161. tls.TLS_RSA_WITH_RC4_128_SHA: "TLS_RSA_WITH_RC4_128_SHA",
  162. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
  163. tls.TLS_RSA_WITH_AES_128_CBC_SHA: "TLS_RSA_WITH_AES_128_CBC_SHA",
  164. tls.TLS_RSA_WITH_AES_256_CBC_SHA: "TLS_RSA_WITH_AES_256_CBC_SHA",
  165. tls.TLS_RSA_WITH_AES_128_GCM_SHA256: "TLS_RSA_WITH_AES_128_GCM_SHA256",
  166. tls.TLS_RSA_WITH_AES_256_GCM_SHA384: "TLS_RSA_WITH_AES_256_GCM_SHA384",
  167. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
  168. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  169. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  170. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
  171. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
  172. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  173. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  174. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  175. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  176. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  177. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  178. tls.TLS_FALLBACK_SCSV: "TLS_FALLBACK_SCSV",
  179. tls.TLS_RSA_WITH_AES_128_CBC_SHA256: "TLS_RSA_WITH_AES_128_CBC_SHA256",
  180. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
  181. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
  182. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
  183. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
  184. }
  185. // cloneTLSConfig returns a shallow clone of the exported
  186. // fields of cfg, ignoring the unexported sync.Once, which
  187. // contains a mutex and must not be copied.
  188. //
  189. // If cfg is nil, a new zero tls.Config is returned.
  190. //
  191. // TODO: inline this function if possible.
  192. func cloneTLSConfig(cfg *tls.Config) *tls.Config {
  193. if cfg == nil {
  194. return &tls.Config{}
  195. }
  196. return cfg.Clone()
  197. }