tls.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. "net"
  25. "net/url"
  26. "os"
  27. credinternal "google.golang.org/grpc/internal/credentials"
  28. )
  29. // TLSInfo contains the auth information for a TLS authenticated connection.
  30. // It implements the AuthInfo interface.
  31. type TLSInfo struct {
  32. State tls.ConnectionState
  33. CommonAuthInfo
  34. // This API is experimental.
  35. SPIFFEID *url.URL
  36. }
  37. // AuthType returns the type of TLSInfo as a string.
  38. func (t TLSInfo) AuthType() string {
  39. return "tls"
  40. }
  41. // GetSecurityValue returns security info requested by channelz.
  42. func (t TLSInfo) GetSecurityValue() ChannelzSecurityValue {
  43. v := &TLSChannelzSecurityValue{
  44. StandardName: cipherSuiteLookup[t.State.CipherSuite],
  45. }
  46. // Currently there's no way to get LocalCertificate info from tls package.
  47. if len(t.State.PeerCertificates) > 0 {
  48. v.RemoteCertificate = t.State.PeerCertificates[0].Raw
  49. }
  50. return v
  51. }
  52. // tlsCreds is the credentials required for authenticating a connection using TLS.
  53. type tlsCreds struct {
  54. // TLS configuration
  55. config *tls.Config
  56. }
  57. func (c tlsCreds) Info() ProtocolInfo {
  58. return ProtocolInfo{
  59. SecurityProtocol: "tls",
  60. SecurityVersion: "1.2",
  61. ServerName: c.config.ServerName,
  62. }
  63. }
  64. func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {
  65. // use local cfg to avoid clobbering ServerName if using multiple endpoints
  66. cfg := credinternal.CloneTLSConfig(c.config)
  67. if cfg.ServerName == "" {
  68. serverName, _, err := net.SplitHostPort(authority)
  69. if err != nil {
  70. // If the authority had no host port or if the authority cannot be parsed, use it as-is.
  71. serverName = authority
  72. }
  73. cfg.ServerName = serverName
  74. }
  75. conn := tls.Client(rawConn, cfg)
  76. errChannel := make(chan error, 1)
  77. go func() {
  78. errChannel <- conn.Handshake()
  79. close(errChannel)
  80. }()
  81. select {
  82. case err := <-errChannel:
  83. if err != nil {
  84. conn.Close()
  85. return nil, nil, err
  86. }
  87. case <-ctx.Done():
  88. conn.Close()
  89. return nil, nil, ctx.Err()
  90. }
  91. tlsInfo := TLSInfo{
  92. State: conn.ConnectionState(),
  93. CommonAuthInfo: CommonAuthInfo{
  94. SecurityLevel: PrivacyAndIntegrity,
  95. },
  96. }
  97. id := credinternal.SPIFFEIDFromState(conn.ConnectionState())
  98. if id != nil {
  99. tlsInfo.SPIFFEID = id
  100. }
  101. return credinternal.WrapSyscallConn(rawConn, conn), tlsInfo, nil
  102. }
  103. func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
  104. conn := tls.Server(rawConn, c.config)
  105. if err := conn.Handshake(); err != nil {
  106. conn.Close()
  107. return nil, nil, err
  108. }
  109. tlsInfo := TLSInfo{
  110. State: conn.ConnectionState(),
  111. CommonAuthInfo: CommonAuthInfo{
  112. SecurityLevel: PrivacyAndIntegrity,
  113. },
  114. }
  115. id := credinternal.SPIFFEIDFromState(conn.ConnectionState())
  116. if id != nil {
  117. tlsInfo.SPIFFEID = id
  118. }
  119. return credinternal.WrapSyscallConn(rawConn, conn), tlsInfo, nil
  120. }
  121. func (c *tlsCreds) Clone() TransportCredentials {
  122. return NewTLS(c.config)
  123. }
  124. func (c *tlsCreds) OverrideServerName(serverNameOverride string) error {
  125. c.config.ServerName = serverNameOverride
  126. return nil
  127. }
  128. // NewTLS uses c to construct a TransportCredentials based on TLS.
  129. func NewTLS(c *tls.Config) TransportCredentials {
  130. tc := &tlsCreds{credinternal.CloneTLSConfig(c)}
  131. tc.config.NextProtos = credinternal.AppendH2ToNextProtos(tc.config.NextProtos)
  132. return tc
  133. }
  134. // NewClientTLSFromCert constructs TLS credentials from the provided root
  135. // certificate authority certificate(s) to validate server connections. If
  136. // certificates to establish the identity of the client need to be included in
  137. // the credentials (eg: for mTLS), use NewTLS instead, where a complete
  138. // tls.Config can be specified.
  139. // serverNameOverride is for testing only. If set to a non empty string,
  140. // it will override the virtual host name of authority (e.g. :authority header
  141. // field) in requests.
  142. func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
  143. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
  144. }
  145. // NewClientTLSFromFile constructs TLS credentials from the provided root
  146. // certificate authority certificate file(s) to validate server connections. If
  147. // certificates to establish the identity of the client need to be included in
  148. // the credentials (eg: for mTLS), use NewTLS instead, where a complete
  149. // tls.Config can be specified.
  150. // serverNameOverride is for testing only. If set to a non empty string,
  151. // it will override the virtual host name of authority (e.g. :authority header
  152. // field) in requests.
  153. func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {
  154. b, err := os.ReadFile(certFile)
  155. if err != nil {
  156. return nil, err
  157. }
  158. cp := x509.NewCertPool()
  159. if !cp.AppendCertsFromPEM(b) {
  160. return nil, fmt.Errorf("credentials: failed to append certificates")
  161. }
  162. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil
  163. }
  164. // NewServerTLSFromCert constructs TLS credentials from the input certificate for server.
  165. func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
  166. return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
  167. }
  168. // NewServerTLSFromFile constructs TLS credentials from the input certificate file and key
  169. // file for server.
  170. func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
  171. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  172. if err != nil {
  173. return nil, err
  174. }
  175. return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
  176. }
  177. // TLSChannelzSecurityValue defines the struct that TLS protocol should return
  178. // from GetSecurityValue(), containing security info like cipher and certificate used.
  179. //
  180. // # Experimental
  181. //
  182. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  183. // later release.
  184. type TLSChannelzSecurityValue struct {
  185. ChannelzSecurityValue
  186. StandardName string
  187. LocalCertificate []byte
  188. RemoteCertificate []byte
  189. }
  190. var cipherSuiteLookup = map[uint16]string{
  191. tls.TLS_RSA_WITH_RC4_128_SHA: "TLS_RSA_WITH_RC4_128_SHA",
  192. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
  193. tls.TLS_RSA_WITH_AES_128_CBC_SHA: "TLS_RSA_WITH_AES_128_CBC_SHA",
  194. tls.TLS_RSA_WITH_AES_256_CBC_SHA: "TLS_RSA_WITH_AES_256_CBC_SHA",
  195. tls.TLS_RSA_WITH_AES_128_GCM_SHA256: "TLS_RSA_WITH_AES_128_GCM_SHA256",
  196. tls.TLS_RSA_WITH_AES_256_GCM_SHA384: "TLS_RSA_WITH_AES_256_GCM_SHA384",
  197. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
  198. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  199. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  200. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
  201. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
  202. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  203. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  204. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  205. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  206. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  207. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  208. tls.TLS_FALLBACK_SCSV: "TLS_FALLBACK_SCSV",
  209. tls.TLS_RSA_WITH_AES_128_CBC_SHA256: "TLS_RSA_WITH_AES_128_CBC_SHA256",
  210. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
  211. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
  212. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
  213. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
  214. tls.TLS_AES_128_GCM_SHA256: "TLS_AES_128_GCM_SHA256",
  215. tls.TLS_AES_256_GCM_SHA384: "TLS_AES_256_GCM_SHA384",
  216. tls.TLS_CHACHA20_POLY1305_SHA256: "TLS_CHACHA20_POLY1305_SHA256",
  217. }