credentials.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. "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. // PerRPCCredentials defines the common interface for the credentials which need to
  53. // attach security information to every RPC (e.g., oauth2).
  54. type PerRPCCredentials 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 credentials 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. // TransportCredentials defines the common interface for all the live gRPC wire
  83. // protocols and supported transport security protocols (e.g., TLS, SSL).
  84. type TransportCredentials 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 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. 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. // use local cfg to avoid clobbering ServerName if using multiple endpoints
  138. cfg := *c.config
  139. if c.config.ServerName == "" {
  140. colonPos := strings.LastIndex(addr, ":")
  141. if colonPos == -1 {
  142. colonPos = len(addr)
  143. }
  144. cfg.ServerName = addr[:colonPos]
  145. }
  146. conn := tls.Client(rawConn, &cfg)
  147. if timeout == 0 {
  148. err = conn.Handshake()
  149. } else {
  150. go func() {
  151. errChannel <- conn.Handshake()
  152. }()
  153. err = <-errChannel
  154. }
  155. if err != nil {
  156. rawConn.Close()
  157. return nil, nil, err
  158. }
  159. // TODO(zhaoq): Omit the auth info for client now. It is more for
  160. // information than anything else.
  161. return conn, nil, nil
  162. }
  163. func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
  164. conn := tls.Server(rawConn, c.config)
  165. if err := conn.Handshake(); err != nil {
  166. rawConn.Close()
  167. return nil, nil, err
  168. }
  169. return conn, TLSInfo{conn.ConnectionState()}, nil
  170. }
  171. // NewTLS uses c to construct a TransportCredentials based on TLS.
  172. func NewTLS(c *tls.Config) TransportCredentials {
  173. tc := &tlsCreds{c}
  174. tc.config.NextProtos = alpnProtoStr
  175. return tc
  176. }
  177. // NewClientTLSFromCert constructs a TLS from the input certificate for client.
  178. func NewClientTLSFromCert(cp *x509.CertPool, serverName string) TransportCredentials {
  179. return NewTLS(&tls.Config{ServerName: serverName, RootCAs: cp})
  180. }
  181. // NewClientTLSFromFile constructs a TLS from the input certificate file for client.
  182. func NewClientTLSFromFile(certFile, serverName string) (TransportCredentials, error) {
  183. b, err := ioutil.ReadFile(certFile)
  184. if err != nil {
  185. return nil, err
  186. }
  187. cp := x509.NewCertPool()
  188. if !cp.AppendCertsFromPEM(b) {
  189. return nil, fmt.Errorf("credentials: failed to append certificates")
  190. }
  191. return NewTLS(&tls.Config{ServerName: serverName, RootCAs: cp}), nil
  192. }
  193. // NewServerTLSFromCert constructs a TLS from the input certificate for server.
  194. func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
  195. return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
  196. }
  197. // NewServerTLSFromFile constructs a TLS from the input certificate file and key
  198. // file for server.
  199. func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
  200. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  201. if err != nil {
  202. return nil, err
  203. }
  204. return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
  205. }