credentials.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 implements various credentials supported by gRPC library,
  19. // which encapsulate all the state needed by a client to authenticate with a
  20. // server and make various assertions, e.g., about the client's identity, role,
  21. // or whether it is authorized to make a particular call.
  22. package credentials // import "google.golang.org/grpc/credentials"
  23. import (
  24. "crypto/tls"
  25. "crypto/x509"
  26. "errors"
  27. "fmt"
  28. "io/ioutil"
  29. "net"
  30. "strings"
  31. "golang.org/x/net/context"
  32. )
  33. var (
  34. // alpnProtoStr are the specified application level protocols for gRPC.
  35. alpnProtoStr = []string{"h2"}
  36. )
  37. // PerRPCCredentials defines the common interface for the credentials which need to
  38. // attach security information to every RPC (e.g., oauth2).
  39. type PerRPCCredentials interface {
  40. // GetRequestMetadata gets the current request metadata, refreshing
  41. // tokens if required. This should be called by the transport layer on
  42. // each request, and the data should be populated in headers or other
  43. // context. uri is the URI of the entry point for the request. When
  44. // supported by the underlying implementation, ctx can be used for
  45. // timeout and cancellation.
  46. // TODO(zhaoq): Define the set of the qualified keys instead of leaving
  47. // it as an arbitrary string.
  48. GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
  49. // RequireTransportSecurity indicates whether the credentials requires
  50. // transport security.
  51. RequireTransportSecurity() bool
  52. }
  53. // ProtocolInfo provides information regarding the gRPC wire protocol version,
  54. // security protocol, security protocol version in use, server name, etc.
  55. type ProtocolInfo struct {
  56. // ProtocolVersion is the gRPC wire protocol version.
  57. ProtocolVersion string
  58. // SecurityProtocol is the security protocol in use.
  59. SecurityProtocol string
  60. // SecurityVersion is the security protocol version.
  61. SecurityVersion string
  62. // ServerName is the user-configured server name.
  63. ServerName string
  64. }
  65. // AuthInfo defines the common interface for the auth information the users are interested in.
  66. type AuthInfo interface {
  67. AuthType() string
  68. }
  69. var (
  70. // ErrConnDispatched indicates that rawConn has been dispatched out of gRPC
  71. // and the caller should not close rawConn.
  72. ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC")
  73. )
  74. // TransportCredentials defines the common interface for all the live gRPC wire
  75. // protocols and supported transport security protocols (e.g., TLS, SSL).
  76. type TransportCredentials interface {
  77. // ClientHandshake does the authentication handshake specified by the corresponding
  78. // authentication protocol on rawConn for clients. It returns the authenticated
  79. // connection and the corresponding auth information about the connection.
  80. // Implementations must use the provided context to implement timely cancellation.
  81. // gRPC will try to reconnect if the error returned is a temporary error
  82. // (io.EOF, context.DeadlineExceeded or err.Temporary() == true).
  83. // If the returned error is a wrapper error, implementations should make sure that
  84. // the error implements Temporary() to have the correct retry behaviors.
  85. //
  86. // If the returned net.Conn is closed, it MUST close the net.Conn provided.
  87. ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)
  88. // ServerHandshake does the authentication handshake for servers. It returns
  89. // the authenticated connection and the corresponding auth information about
  90. // the connection.
  91. //
  92. // If the returned net.Conn is closed, it MUST close the net.Conn provided.
  93. ServerHandshake(net.Conn) (net.Conn, AuthInfo, error)
  94. // Info provides the ProtocolInfo of this TransportCredentials.
  95. Info() ProtocolInfo
  96. // Clone makes a copy of this TransportCredentials.
  97. Clone() TransportCredentials
  98. // OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server.
  99. // gRPC internals also use it to override the virtual hosting name if it is set.
  100. // It must be called before dialing. Currently, this is only used by grpclb.
  101. OverrideServerName(string) error
  102. }
  103. // TLSInfo contains the auth information for a TLS authenticated connection.
  104. // It implements the AuthInfo interface.
  105. type TLSInfo struct {
  106. State tls.ConnectionState
  107. }
  108. // AuthType returns the type of TLSInfo as a string.
  109. func (t TLSInfo) AuthType() string {
  110. return "tls"
  111. }
  112. // tlsCreds is the credentials required for authenticating a connection using TLS.
  113. type tlsCreds struct {
  114. // TLS configuration
  115. config *tls.Config
  116. }
  117. func (c tlsCreds) Info() ProtocolInfo {
  118. return ProtocolInfo{
  119. SecurityProtocol: "tls",
  120. SecurityVersion: "1.2",
  121. ServerName: c.config.ServerName,
  122. }
  123. }
  124. func (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {
  125. // use local cfg to avoid clobbering ServerName if using multiple endpoints
  126. cfg := cloneTLSConfig(c.config)
  127. if cfg.ServerName == "" {
  128. colonPos := strings.LastIndex(addr, ":")
  129. if colonPos == -1 {
  130. colonPos = len(addr)
  131. }
  132. cfg.ServerName = addr[:colonPos]
  133. }
  134. conn := tls.Client(rawConn, cfg)
  135. errChannel := make(chan error, 1)
  136. go func() {
  137. errChannel <- conn.Handshake()
  138. }()
  139. select {
  140. case err := <-errChannel:
  141. if err != nil {
  142. return nil, nil, err
  143. }
  144. case <-ctx.Done():
  145. return nil, nil, ctx.Err()
  146. }
  147. return conn, TLSInfo{conn.ConnectionState()}, nil
  148. }
  149. func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
  150. conn := tls.Server(rawConn, c.config)
  151. if err := conn.Handshake(); err != nil {
  152. return nil, nil, err
  153. }
  154. return conn, TLSInfo{conn.ConnectionState()}, nil
  155. }
  156. func (c *tlsCreds) Clone() TransportCredentials {
  157. return NewTLS(c.config)
  158. }
  159. func (c *tlsCreds) OverrideServerName(serverNameOverride string) error {
  160. c.config.ServerName = serverNameOverride
  161. return nil
  162. }
  163. // NewTLS uses c to construct a TransportCredentials based on TLS.
  164. func NewTLS(c *tls.Config) TransportCredentials {
  165. tc := &tlsCreds{cloneTLSConfig(c)}
  166. tc.config.NextProtos = alpnProtoStr
  167. return tc
  168. }
  169. // NewClientTLSFromCert constructs TLS credentials from the input certificate for client.
  170. // serverNameOverride is for testing only. If set to a non empty string,
  171. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
  172. func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
  173. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
  174. }
  175. // NewClientTLSFromFile constructs TLS credentials from the input certificate file for client.
  176. // serverNameOverride is for testing only. If set to a non empty string,
  177. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
  178. func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {
  179. b, err := ioutil.ReadFile(certFile)
  180. if err != nil {
  181. return nil, err
  182. }
  183. cp := x509.NewCertPool()
  184. if !cp.AppendCertsFromPEM(b) {
  185. return nil, fmt.Errorf("credentials: failed to append certificates")
  186. }
  187. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil
  188. }
  189. // NewServerTLSFromCert constructs TLS credentials from the input certificate for server.
  190. func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
  191. return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
  192. }
  193. // NewServerTLSFromFile constructs TLS credentials from the input certificate file and key
  194. // file for server.
  195. func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
  196. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
  201. }