| 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 |
|
| 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. |
| 23 |
package credentials // import "google.golang.org/grpc/credentials" |
| 24 |
|
| 25 |
import ( |
| 26 |
"crypto/tls" |
| 27 |
"crypto/x509" |
| 28 |
"errors" |
| 29 |
"fmt" |
| 30 |
"io/ioutil" |
| 31 |
"net" |
| 32 |
"strings" |
| 33 |
|
| 34 |
"golang.org/x/net/context" |
| 35 |
) |
| 36 |
|
| 37 |
var ( |
| 38 |
// alpnProtoStr are the specified application level protocols for gRPC. |
| 39 |
alpnProtoStr = []string{"h2"} |
| 40 |
) |
| 41 |
|
| 42 |
// PerRPCCredentials defines the common interface for the credentials which need to |
| 43 |
// attach security information to every RPC (e.g., oauth2). |
| 44 |
type 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. uri is the URI of the entry point for the request. When |
| 49 |
// 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. |
| 61 |
type 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. |
| 73 |
type AuthInfo interface { |
| 74 |
AuthType() string |
| 75 |
} |
| 76 |
|
| 77 |
var ( |
| 78 |
// ErrConnDispatched indicates that rawConn has been dispatched out of gRPC |
| 79 |
// and the caller should not close rawConn. |
| 80 |
ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC") |
| 81 |
) |
| 82 |
|
| 83 |
// TransportCredentials defines the common interface for all the live gRPC wire |
| 84 |
// protocols and supported transport security protocols (e.g., TLS, SSL). |
| 85 |
type TransportCredentials interface { |
| 86 |
// ClientHandshake does the authentication handshake specified by the corresponding |
| 87 |
// authentication protocol on rawConn for clients. It returns the authenticated |
| 88 |
// connection and the corresponding auth information about the connection. |
| 89 |
// Implementations must use the provided context to implement timely cancellation. |
| 90 |
// gRPC will try to reconnect if the error returned is a temporary error |
| 91 |
// (io.EOF, context.DeadlineExceeded or err.Temporary() == true). |
| 92 |
// If the returned error is a wrapper error, implementations should make sure that |
| 93 |
// the error implements Temporary() to have the correct retry behaviors. |
| 94 |
// |
| 95 |
// If the returned net.Conn is closed, it MUST close the net.Conn provided. |
| 96 |
ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error) |
| 97 |
// ServerHandshake does the authentication handshake for servers. It returns |
| 98 |
// the authenticated connection and the corresponding auth information about |
| 99 |
// the connection. |
| 100 |
// |
| 101 |
// If the returned net.Conn is closed, it MUST close the net.Conn provided. |
| 102 |
ServerHandshake(net.Conn) (net.Conn, AuthInfo, error) |
| 103 |
// Info provides the ProtocolInfo of this TransportCredentials. |
| 104 |
Info() ProtocolInfo |
| 105 |
// Clone makes a copy of this TransportCredentials. |
| 106 |
Clone() TransportCredentials |
| 107 |
// OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server. |
| 108 |
// gRPC internals also use it to override the virtual hosting name if it is set. |
| 109 |
// It must be called before dialing. Currently, this is only used by grpclb. |
| 110 |
OverrideServerName(string) error |
| 111 |
} |
| 112 |
|
| 113 |
// TLSInfo contains the auth information for a TLS authenticated connection. |
| 114 |
// It implements the AuthInfo interface. |
| 115 |
type TLSInfo struct { |
| 116 |
State tls.ConnectionState |
| 117 |
} |
| 118 |
|
| 119 |
// AuthType returns the type of TLSInfo as a string. |
| 120 |
func (t TLSInfo) AuthType() string { |
| 121 |
return "tls" |
| 122 |
} |
| 123 |
|
| 124 |
// tlsCreds is the credentials required for authenticating a connection using TLS. |
| 125 |
type tlsCreds struct { |
| 126 |
// TLS configuration |
| 127 |
config *tls.Config |
| 128 |
} |
| 129 |
|
| 130 |
func (c tlsCreds) Info() ProtocolInfo { |
| 131 |
return ProtocolInfo{ |
| 132 |
SecurityProtocol: "tls", |
| 133 |
SecurityVersion: "1.2", |
| 134 |
ServerName: c.config.ServerName, |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
func (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { |
| 139 |
// use local cfg to avoid clobbering ServerName if using multiple endpoints |
| 140 |
cfg := cloneTLSConfig(c.config) |
| 141 |
if cfg.ServerName == "" { |
| 142 |
colonPos := strings.LastIndex(addr, ":") |
| 143 |
if colonPos == -1 { |
| 144 |
colonPos = len(addr) |
| 145 |
} |
| 146 |
cfg.ServerName = addr[:colonPos] |
| 147 |
} |
| 148 |
conn := tls.Client(rawConn, cfg) |
| 149 |
errChannel := make(chan error, 1) |
| 150 |
go func() { |
| 151 |
errChannel <- conn.Handshake() |
| 152 |
}() |
| 153 |
select { |
| 154 |
case err := <-errChannel: |
| 155 |
if err != nil { |
| 156 |
return nil, nil, err |
| 157 |
} |
| 158 |
case <-ctx.Done(): |
| 159 |
return nil, nil, ctx.Err() |
| 160 |
} |
| 161 |
return conn, TLSInfo{conn.ConnectionState()}, nil |
| 162 |
} |
| 163 |
|
| 164 |
func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) { |
| 165 |
conn := tls.Server(rawConn, c.config) |
| 166 |
if err := conn.Handshake(); err != nil { |
| 167 |
return nil, nil, err |
| 168 |
} |
| 169 |
return conn, TLSInfo{conn.ConnectionState()}, nil |
| 170 |
} |
| 171 |
|
| 172 |
func (c *tlsCreds) Clone() TransportCredentials { |
| 173 |
return NewTLS(c.config) |
| 174 |
} |
| 175 |
|
| 176 |
func (c *tlsCreds) OverrideServerName(serverNameOverride string) error { |
| 177 |
c.config.ServerName = serverNameOverride |
| 178 |
return nil |
| 179 |
} |
| 180 |
|
| 181 |
// NewTLS uses c to construct a TransportCredentials based on TLS. |
| 182 |
func NewTLS(c *tls.Config) TransportCredentials { |
| 183 |
tc := &tlsCreds{cloneTLSConfig(c)} |
| 184 |
tc.config.NextProtos = alpnProtoStr |
| 185 |
return tc |
| 186 |
} |
| 187 |
|
| 188 |
// NewClientTLSFromCert constructs TLS credentials from the input certificate for client. |
| 189 |
// serverNameOverride is for testing only. If set to a non empty string, |
| 190 |
// it will override the virtual host name of authority (e.g. :authority header field) in requests. |
| 191 |
func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials { |
| 192 |
return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}) |
| 193 |
} |
| 194 |
|
| 195 |
// NewClientTLSFromFile constructs TLS credentials from the input certificate file for client. |
| 196 |
// serverNameOverride is for testing only. If set to a non empty string, |
| 197 |
// it will override the virtual host name of authority (e.g. :authority header field) in requests. |
| 198 |
func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) { |
| 199 |
b, err := ioutil.ReadFile(certFile) |
| 200 |
if err != nil { |
| 201 |
return nil, err |
| 202 |
} |
| 203 |
cp := x509.NewCertPool() |
| 204 |
if !cp.AppendCertsFromPEM(b) { |
| 205 |
return nil, fmt.Errorf("credentials: failed to append certificates") |
| 206 |
} |
| 207 |
return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil |
| 208 |
} |
| 209 |
|
| 210 |
// NewServerTLSFromCert constructs TLS credentials from the input certificate for server. |
| 211 |
func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials { |
| 212 |
return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}}) |
| 213 |
} |
| 214 |
|
| 215 |
// NewServerTLSFromFile constructs TLS credentials from the input certificate file and key |
| 216 |
// file for server. |
| 217 |
func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) { |
| 218 |
cert, err := tls.LoadX509KeyPair(certFile, keyFile) |
| 219 |
if err != nil { |
| 220 |
return nil, err |
| 221 |
} |
| 222 |
return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil |
| 223 |
} |