credentials.go 13 KB

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