credentials.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. "github.com/golang/protobuf/proto"
  32. "golang.org/x/net/context"
  33. )
  34. // alpnProtoStr are the specified application level protocols for gRPC.
  35. var alpnProtoStr = []string{"h2"}
  36. // PerRPCCredentials defines the common interface for the credentials which need to
  37. // attach security information to every RPC (e.g., oauth2).
  38. type PerRPCCredentials interface {
  39. // GetRequestMetadata gets the current request metadata, refreshing
  40. // tokens if required. This should be called by the transport layer on
  41. // each request, and the data should be populated in headers or other
  42. // context. If a status code is returned, it will be used as the status
  43. // for the RPC. uri is the URI of the entry point for the request.
  44. // When 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. // ErrConnDispatched indicates that rawConn has been dispatched out of gRPC
  70. // and the caller should not close rawConn.
  71. var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC")
  72. // TransportCredentials defines the common interface for all the live gRPC wire
  73. // protocols and supported transport security protocols (e.g., TLS, SSL).
  74. type TransportCredentials interface {
  75. // ClientHandshake does the authentication handshake specified by the corresponding
  76. // authentication protocol on rawConn for clients. It returns the authenticated
  77. // connection and the corresponding auth information about the connection.
  78. // Implementations must use the provided context to implement timely cancellation.
  79. // gRPC will try to reconnect if the error returned is a temporary error
  80. // (io.EOF, context.DeadlineExceeded or err.Temporary() == true).
  81. // If the returned error is a wrapper error, implementations should make sure that
  82. // the error implements Temporary() to have the correct retry behaviors.
  83. //
  84. // If the returned net.Conn is closed, it MUST close the net.Conn provided.
  85. ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)
  86. // ServerHandshake does the authentication handshake for servers. It returns
  87. // the authenticated connection and the corresponding auth information about
  88. // the connection.
  89. //
  90. // If the returned net.Conn is closed, it MUST close the net.Conn provided.
  91. ServerHandshake(net.Conn) (net.Conn, AuthInfo, error)
  92. // Info provides the ProtocolInfo of this TransportCredentials.
  93. Info() ProtocolInfo
  94. // Clone makes a copy of this TransportCredentials.
  95. Clone() TransportCredentials
  96. // OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server.
  97. // gRPC internals also use it to override the virtual hosting name if it is set.
  98. // It must be called before dialing. Currently, this is only used by grpclb.
  99. OverrideServerName(string) error
  100. }
  101. // Bundle is a combination of TransportCredentials and PerRPCCredentials.
  102. //
  103. // It also contains a mode switching method, so it can be used as a combination
  104. // of different credential policies.
  105. //
  106. // Bundle cannot be used together with individual TransportCredentials.
  107. // PerRPCCredentials from Bundle will be appended to other PerRPCCredentials.
  108. //
  109. // This API is experimental.
  110. type Bundle interface {
  111. TransportCredentials() TransportCredentials
  112. PerRPCCredentials() PerRPCCredentials
  113. // NewWithMode should make a copy of Bundle, and switch mode. Modifying the
  114. // existing Bundle may cause races.
  115. //
  116. // NewWithMode returns nil if the requested mode is not supported.
  117. NewWithMode(mode string) (Bundle, error)
  118. }
  119. // TLSInfo contains the auth information for a TLS authenticated connection.
  120. // It implements the AuthInfo interface.
  121. type TLSInfo struct {
  122. State tls.ConnectionState
  123. }
  124. // AuthType returns the type of TLSInfo as a string.
  125. func (t TLSInfo) AuthType() string {
  126. return "tls"
  127. }
  128. // GetChannelzSecurityValue returns security info requested by channelz.
  129. func (t TLSInfo) GetChannelzSecurityValue() ChannelzSecurityValue {
  130. v := &TLSChannelzSecurityValue{
  131. StandardName: cipherSuiteLookup[t.State.CipherSuite],
  132. }
  133. // Currently there's no way to get LocalCertificate info from tls package.
  134. if len(t.State.PeerCertificates) > 0 {
  135. v.RemoteCertificate = t.State.PeerCertificates[0].Raw
  136. }
  137. return v
  138. }
  139. // tlsCreds is the credentials required for authenticating a connection using TLS.
  140. type tlsCreds struct {
  141. // TLS configuration
  142. config *tls.Config
  143. }
  144. func (c tlsCreds) Info() ProtocolInfo {
  145. return ProtocolInfo{
  146. SecurityProtocol: "tls",
  147. SecurityVersion: "1.2",
  148. ServerName: c.config.ServerName,
  149. }
  150. }
  151. func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {
  152. // use local cfg to avoid clobbering ServerName if using multiple endpoints
  153. cfg := cloneTLSConfig(c.config)
  154. if cfg.ServerName == "" {
  155. colonPos := strings.LastIndex(authority, ":")
  156. if colonPos == -1 {
  157. colonPos = len(authority)
  158. }
  159. cfg.ServerName = authority[:colonPos]
  160. }
  161. conn := tls.Client(rawConn, cfg)
  162. errChannel := make(chan error, 1)
  163. go func() {
  164. errChannel <- conn.Handshake()
  165. }()
  166. select {
  167. case err := <-errChannel:
  168. if err != nil {
  169. return nil, nil, err
  170. }
  171. case <-ctx.Done():
  172. return nil, nil, ctx.Err()
  173. }
  174. return tlsConn{Conn: conn, rawConn: rawConn}, TLSInfo{conn.ConnectionState()}, nil
  175. }
  176. func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
  177. conn := tls.Server(rawConn, c.config)
  178. if err := conn.Handshake(); err != nil {
  179. return nil, nil, err
  180. }
  181. return tlsConn{Conn: conn, rawConn: rawConn}, TLSInfo{conn.ConnectionState()}, nil
  182. }
  183. func (c *tlsCreds) Clone() TransportCredentials {
  184. return NewTLS(c.config)
  185. }
  186. func (c *tlsCreds) OverrideServerName(serverNameOverride string) error {
  187. c.config.ServerName = serverNameOverride
  188. return nil
  189. }
  190. // NewTLS uses c to construct a TransportCredentials based on TLS.
  191. func NewTLS(c *tls.Config) TransportCredentials {
  192. tc := &tlsCreds{cloneTLSConfig(c)}
  193. tc.config.NextProtos = alpnProtoStr
  194. return tc
  195. }
  196. // NewClientTLSFromCert constructs TLS credentials from the input certificate for client.
  197. // serverNameOverride is for testing only. If set to a non empty string,
  198. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
  199. func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
  200. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
  201. }
  202. // NewClientTLSFromFile constructs TLS credentials from the input certificate file for client.
  203. // serverNameOverride is for testing only. If set to a non empty string,
  204. // it will override the virtual host name of authority (e.g. :authority header field) in requests.
  205. func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {
  206. b, err := ioutil.ReadFile(certFile)
  207. if err != nil {
  208. return nil, err
  209. }
  210. cp := x509.NewCertPool()
  211. if !cp.AppendCertsFromPEM(b) {
  212. return nil, fmt.Errorf("credentials: failed to append certificates")
  213. }
  214. return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil
  215. }
  216. // NewServerTLSFromCert constructs TLS credentials from the input certificate for server.
  217. func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
  218. return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
  219. }
  220. // NewServerTLSFromFile constructs TLS credentials from the input certificate file and key
  221. // file for server.
  222. func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
  223. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  224. if err != nil {
  225. return nil, err
  226. }
  227. return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
  228. }
  229. // ChannelzSecurityInfo defines the interface that security protocols should implement
  230. // in order to provide security info to channelz.
  231. type ChannelzSecurityInfo interface {
  232. GetSecurityValue() ChannelzSecurityValue
  233. }
  234. // ChannelzSecurityValue defines the interface that GetSecurityValue() return value
  235. // should satisfy. This interface should only be satisfied by *TLSChannelzSecurityValue
  236. // and *OtherChannelzSecurityValue.
  237. type ChannelzSecurityValue interface {
  238. isChannelzSecurityValue()
  239. }
  240. // TLSChannelzSecurityValue defines the struct that TLS protocol should return
  241. // from GetSecurityValue(), containing security info like cipher and certificate used.
  242. type TLSChannelzSecurityValue struct {
  243. StandardName string
  244. LocalCertificate []byte
  245. RemoteCertificate []byte
  246. }
  247. func (*TLSChannelzSecurityValue) isChannelzSecurityValue() {}
  248. // OtherChannelzSecurityValue defines the struct that non-TLS protocol should return
  249. // from GetSecurityValue(), which contains protocol specific security info. Note
  250. // the Value field will be sent to users of channelz requesting channel info, and
  251. // thus sensitive info should better be avoided.
  252. type OtherChannelzSecurityValue struct {
  253. Name string
  254. Value proto.Message
  255. }
  256. func (*OtherChannelzSecurityValue) isChannelzSecurityValue() {}
  257. type tlsConn struct {
  258. *tls.Conn
  259. rawConn net.Conn
  260. }
  261. var cipherSuiteLookup = map[uint16]string{
  262. tls.TLS_RSA_WITH_RC4_128_SHA: "TLS_RSA_WITH_RC4_128_SHA",
  263. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
  264. tls.TLS_RSA_WITH_AES_128_CBC_SHA: "TLS_RSA_WITH_AES_128_CBC_SHA",
  265. tls.TLS_RSA_WITH_AES_256_CBC_SHA: "TLS_RSA_WITH_AES_256_CBC_SHA",
  266. tls.TLS_RSA_WITH_AES_128_GCM_SHA256: "TLS_RSA_WITH_AES_128_GCM_SHA256",
  267. tls.TLS_RSA_WITH_AES_256_GCM_SHA384: "TLS_RSA_WITH_AES_256_GCM_SHA384",
  268. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
  269. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  270. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  271. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
  272. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
  273. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  274. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  275. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  276. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  277. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  278. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  279. tls.TLS_FALLBACK_SCSV: "TLS_FALLBACK_SCSV",
  280. }