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