credentials.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 // import "google.golang.org/grpc/credentials"
  38. import (
  39. "crypto/tls"
  40. "crypto/x509"
  41. "fmt"
  42. "io/ioutil"
  43. "net"
  44. "strings"
  45. "time"
  46. "golang.org/x/net/context"
  47. )
  48. var (
  49. // alpnProtoStr are the specified application level protocols for gRPC.
  50. alpnProtoStr = []string{"h2"}
  51. )
  52. // Credentials defines the common interface all supported credentials must
  53. // implement.
  54. type Credentials interface {
  55. // GetRequestMetadata gets the current request metadata, refreshing
  56. // tokens if required. This should be called by the transport layer on
  57. // each request, and the data should be populated in headers or other
  58. // context. uri is the URI of the entry point for the request. When
  59. // supported by the underlying implementation, ctx can be used for
  60. // timeout and cancellation.
  61. // TODO(zhaoq): Define the set of the qualified keys instead of leaving
  62. // it as an arbitrary string.
  63. GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
  64. // RequireTransportSecurity indicates whether the credentails requires
  65. // transport security.
  66. RequireTransportSecurity() bool
  67. }
  68. // ProtocolInfo provides information regarding the gRPC wire protocol version,
  69. // security protocol, security protocol version in use, etc.
  70. type ProtocolInfo struct {
  71. // ProtocolVersion is the gRPC wire protocol version.
  72. ProtocolVersion string
  73. // SecurityProtocol is the security protocol in use.
  74. SecurityProtocol string
  75. // SecurityVersion is the security protocol version.
  76. SecurityVersion string
  77. }
  78. // AuthInfo defines the common interface for the auth information the users are interested in.
  79. type AuthInfo interface {
  80. AuthType() string
  81. }
  82. // TransportAuthenticator defines the common interface for all the live gRPC wire
  83. // protocols and supported transport security protocols (e.g., TLS, SSL).
  84. type TransportAuthenticator interface {
  85. // ClientHandshake does the authentication handshake specified by the corresponding
  86. // authentication protocol on rawConn for clients. It returns the authenticated
  87. // connection and the corresponding auth information about the connection.
  88. ClientHandshake(addr string, rawConn net.Conn, timeout time.Duration) (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(rawConn net.Conn) (net.Conn, AuthInfo, error)
  93. // Info provides the ProtocolInfo of this TransportAuthenticator.
  94. Info() ProtocolInfo
  95. Credentials
  96. }
  97. // TLSInfo contains the auth information for a TLS authenticated connection.
  98. // It implements the AuthInfo interface.
  99. type TLSInfo struct {
  100. State tls.ConnectionState
  101. }
  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. type timeoutError struct{}
  125. func (timeoutError) Error() string { return "credentials: Dial timed out" }
  126. func (timeoutError) Timeout() bool { return true }
  127. func (timeoutError) Temporary() bool { return true }
  128. func (c *tlsCreds) ClientHandshake(addr string, rawConn net.Conn, timeout time.Duration) (_ net.Conn, _ AuthInfo, err error) {
  129. // borrow some code from tls.DialWithDialer
  130. var errChannel chan error
  131. if timeout != 0 {
  132. errChannel = make(chan error, 2)
  133. time.AfterFunc(timeout, func() {
  134. errChannel <- timeoutError{}
  135. })
  136. }
  137. if c.config.ServerName == "" {
  138. colonPos := strings.LastIndex(addr, ":")
  139. if colonPos == -1 {
  140. colonPos = len(addr)
  141. }
  142. c.config.ServerName = addr[:colonPos]
  143. }
  144. conn := tls.Client(rawConn, &c.config)
  145. if timeout == 0 {
  146. err = conn.Handshake()
  147. } else {
  148. go func() {
  149. errChannel <- conn.Handshake()
  150. }()
  151. err = <-errChannel
  152. }
  153. if err != nil {
  154. rawConn.Close()
  155. return nil, nil, err
  156. }
  157. // TODO(zhaoq): Omit the auth info for client now. It is more for
  158. // information than anything else.
  159. return conn, nil, nil
  160. }
  161. func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
  162. conn := tls.Server(rawConn, &c.config)
  163. if err := conn.Handshake(); err != nil {
  164. rawConn.Close()
  165. return nil, nil, err
  166. }
  167. return conn, TLSInfo{conn.ConnectionState()}, nil
  168. }
  169. // NewTLS uses c to construct a TransportAuthenticator based on TLS.
  170. func NewTLS(c *tls.Config) TransportAuthenticator {
  171. tc := &tlsCreds{*c}
  172. tc.config.NextProtos = alpnProtoStr
  173. return tc
  174. }
  175. // NewClientTLSFromCert constructs a TLS from the input certificate for client.
  176. func NewClientTLSFromCert(cp *x509.CertPool, serverName string) TransportAuthenticator {
  177. return NewTLS(&tls.Config{ServerName: serverName, RootCAs: cp})
  178. }
  179. // NewClientTLSFromFile constructs a TLS from the input certificate file for client.
  180. func NewClientTLSFromFile(certFile, serverName string) (TransportAuthenticator, error) {
  181. b, err := ioutil.ReadFile(certFile)
  182. if err != nil {
  183. return nil, err
  184. }
  185. cp := x509.NewCertPool()
  186. if !cp.AppendCertsFromPEM(b) {
  187. return nil, fmt.Errorf("credentials: failed to append certificates")
  188. }
  189. return NewTLS(&tls.Config{ServerName: serverName, RootCAs: cp}), nil
  190. }
  191. // NewServerTLSFromCert constructs a TLS from the input certificate for server.
  192. func NewServerTLSFromCert(cert *tls.Certificate) TransportAuthenticator {
  193. return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
  194. }
  195. // NewServerTLSFromFile constructs a TLS from the input certificate file and key
  196. // file for server.
  197. func NewServerTLSFromFile(certFile, keyFile string) (TransportAuthenticator, error) {
  198. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  199. if err != nil {
  200. return nil, err
  201. }
  202. return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
  203. }