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