credentials.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. /*
  2. *
  3. * Copyright 2014, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. // Package credentials implements various credentials supported by gRPC library,
  34. // which encapsulate all the state needed by a client to authenticate with a
  35. // server and make various assertions, e.g., about the client's identity, role,
  36. // or whether it is authorized to make a particular call.
  37. package credentials
  38. import (
  39. "crypto/tls"
  40. "crypto/x509"
  41. "fmt"
  42. "io/ioutil"
  43. "net"
  44. "strings"
  45. "golang.org/x/net/context"
  46. )
  47. var (
  48. // alpnProtoStr are the specified application level protocols for gRPC.
  49. alpnProtoStr = []string{"h2"}
  50. )
  51. // PerRPCCredentials defines the common interface for the credentials which need to
  52. // attach security information to every RPC (e.g., oauth2).
  53. type PerRPCCredentials interface {
  54. // GetRequestMetadata gets the current request metadata, refreshing
  55. // tokens if required. This should be called by the transport layer on
  56. // each request, and the data should be populated in headers or other
  57. // context. uri is the URI of the entry point for the request. When
  58. // supported by the underlying implementation, ctx can be used for
  59. // timeout and cancellation.
  60. // TODO(zhaoq): Define the set of the qualified keys instead of leaving
  61. // it as an arbitrary string.
  62. GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
  63. // RequireTransportSecurity indicates whether the credentials requires
  64. // transport security.
  65. RequireTransportSecurity() bool
  66. }
  67. // ProtocolInfo provides information regarding the gRPC wire protocol version,
  68. // security protocol, security protocol version in use, etc.
  69. type ProtocolInfo struct {
  70. // ProtocolVersion is the gRPC wire protocol version.
  71. ProtocolVersion string
  72. // SecurityProtocol is the security protocol in use.
  73. SecurityProtocol string
  74. // SecurityVersion is the security protocol version.
  75. SecurityVersion string
  76. }
  77. // AuthInfo defines the common interface for the auth information the users are interested in.
  78. type AuthInfo interface {
  79. AuthType() string
  80. }
  81. // TransportCredentials defines the common interface for all the live gRPC wire
  82. // protocols and supported transport security protocols (e.g., TLS, SSL).
  83. type TransportCredentials interface {
  84. // ClientHandshake does the authentication handshake specified by the corresponding
  85. // authentication protocol on rawConn for clients. It returns the authenticated
  86. // connection and the corresponding auth information about the connection.
  87. // Implementations must use the provided context to implement timely cancellation.
  88. ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)
  89. // ServerHandshake does the authentication handshake for servers. It returns
  90. // the authenticated connection and the corresponding auth information about
  91. // the connection.
  92. ServerHandshake(net.Conn) (net.Conn, AuthInfo, error)
  93. // Info provides the ProtocolInfo of this TransportCredentials.
  94. Info() ProtocolInfo
  95. }
  96. // TLSInfo contains the auth information for a TLS authenticated connection.
  97. // It implements the AuthInfo interface.
  98. type TLSInfo struct {
  99. State tls.ConnectionState
  100. }
  101. // AuthType returns the type of TLSInfo as a string.
  102. func (t TLSInfo) AuthType() string {
  103. return "tls"
  104. }
  105. // tlsCreds is the credentials required for authenticating a connection using TLS.
  106. type tlsCreds struct {
  107. // TLS configuration
  108. config *tls.Config
  109. }
  110. func (c tlsCreds) Info() ProtocolInfo {
  111. return ProtocolInfo{
  112. SecurityProtocol: "tls",
  113. SecurityVersion: "1.2",
  114. }
  115. }
  116. // GetRequestMetadata returns nil, nil since TLS credentials does not have
  117. // metadata.
  118. func (c *tlsCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  119. return nil, nil
  120. }
  121. func (c *tlsCreds) RequireTransportSecurity() bool {
  122. return true
  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. // TODO(zhaoq): Omit the auth info for client now. It is more for
  148. // information than anything else.
  149. return conn, nil, nil
  150. }
  151. func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
  152. conn := tls.Server(rawConn, c.config)
  153. if err := conn.Handshake(); err != nil {
  154. return nil, nil, err
  155. }
  156. return conn, TLSInfo{conn.ConnectionState()}, nil
  157. }
  158. // NewTLS uses c to construct a TransportCredentials based on TLS.
  159. func NewTLS(c *tls.Config) TransportCredentials {
  160. tc := &tlsCreds{cloneTLSConfig(c)}
  161. tc.config.NextProtos = alpnProtoStr
  162. return tc
  163. }
  164. // NewClientTLSFromCert constructs a TLS from the input certificate for client.
  165. func NewClientTLSFromCert(cp *x509.CertPool, serverName string) TransportCredentials {
  166. return NewTLS(&tls.Config{ServerName: serverName, RootCAs: cp})
  167. }
  168. // NewClientTLSFromFile constructs a TLS from the input certificate file for client.
  169. func NewClientTLSFromFile(certFile, serverName string) (TransportCredentials, error) {
  170. b, err := ioutil.ReadFile(certFile)
  171. if err != nil {
  172. return nil, err
  173. }
  174. cp := x509.NewCertPool()
  175. if !cp.AppendCertsFromPEM(b) {
  176. return nil, fmt.Errorf("credentials: failed to append certificates")
  177. }
  178. return NewTLS(&tls.Config{ServerName: serverName, RootCAs: cp}), nil
  179. }
  180. // NewServerTLSFromCert constructs a TLS from the input certificate for server.
  181. func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
  182. return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
  183. }
  184. // NewServerTLSFromFile constructs a TLS from the input certificate file and key
  185. // file for server.
  186. func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
  187. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  188. if err != nil {
  189. return nil, err
  190. }
  191. return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
  192. }