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. 23package credentials 24 25import ( 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 37var ( 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). 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. 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. 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 77var ( 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). 85type 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 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 ServerHandshake(net.Conn) (net.Conn, AuthInfo, error) 99 // Info provides the ProtocolInfo of this TransportCredentials. 100 Info() ProtocolInfo 101 // Clone makes a copy of this TransportCredentials. 102 Clone() TransportCredentials 103 // OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server. 104 // gRPC internals also use it to override the virtual hosting name if it is set. 105 // It must be called before dialing. Currently, this is only used by grpclb. 106 OverrideServerName(string) error 107} 108 109// TLSInfo contains the auth information for a TLS authenticated connection. 110// It implements the AuthInfo interface. 111type TLSInfo struct { 112 State tls.ConnectionState 113} 114 115// AuthType returns the type of TLSInfo as a string. 116func (t TLSInfo) AuthType() string { 117 return "tls" 118} 119 120// tlsCreds is the credentials required for authenticating a connection using TLS. 121type tlsCreds struct { 122 // TLS configuration 123 config *tls.Config 124} 125 126func (c tlsCreds) Info() ProtocolInfo { 127 return ProtocolInfo{ 128 SecurityProtocol: "tls", 129 SecurityVersion: "1.2", 130 ServerName: c.config.ServerName, 131 } 132} 133 134func (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { 135 // use local cfg to avoid clobbering ServerName if using multiple endpoints 136 cfg := cloneTLSConfig(c.config) 137 if cfg.ServerName == "" { 138 colonPos := strings.LastIndex(addr, ":") 139 if colonPos == -1 { 140 colonPos = len(addr) 141 } 142 cfg.ServerName = addr[:colonPos] 143 } 144 conn := tls.Client(rawConn, cfg) 145 errChannel := make(chan error, 1) 146 go func() { 147 errChannel <- conn.Handshake() 148 }() 149 select { 150 case err := <-errChannel: 151 if err != nil { 152 return nil, nil, err 153 } 154 case <-ctx.Done(): 155 return nil, nil, ctx.Err() 156 } 157 return conn, TLSInfo{conn.ConnectionState()}, nil 158} 159 160func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) { 161 conn := tls.Server(rawConn, c.config) 162 if err := conn.Handshake(); err != nil { 163 return nil, nil, err 164 } 165 return conn, TLSInfo{conn.ConnectionState()}, nil 166} 167 168func (c *tlsCreds) Clone() TransportCredentials { 169 return NewTLS(c.config) 170} 171 172func (c *tlsCreds) OverrideServerName(serverNameOverride string) error { 173 c.config.ServerName = serverNameOverride 174 return nil 175} 176 177// NewTLS uses c to construct a TransportCredentials based on TLS. 178func NewTLS(c *tls.Config) TransportCredentials { 179 tc := &tlsCreds{cloneTLSConfig(c)} 180 tc.config.NextProtos = alpnProtoStr 181 return tc 182} 183 184// NewClientTLSFromCert constructs TLS credentials from the input certificate for client. 185// serverNameOverride is for testing only. If set to a non empty string, 186// it will override the virtual host name of authority (e.g. :authority header field) in requests. 187func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials { 188 return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}) 189} 190 191// NewClientTLSFromFile constructs TLS credentials from the input certificate file for client. 192// serverNameOverride is for testing only. If set to a non empty string, 193// it will override the virtual host name of authority (e.g. :authority header field) in requests. 194func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) { 195 b, err := ioutil.ReadFile(certFile) 196 if err != nil { 197 return nil, err 198 } 199 cp := x509.NewCertPool() 200 if !cp.AppendCertsFromPEM(b) { 201 return nil, fmt.Errorf("credentials: failed to append certificates") 202 } 203 return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil 204} 205 206// NewServerTLSFromCert constructs TLS credentials from the input certificate for server. 207func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials { 208 return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}}) 209} 210 211// NewServerTLSFromFile constructs TLS credentials from the input certificate file and key 212// file for server. 213func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) { 214 cert, err := tls.LoadX509KeyPair(certFile, keyFile) 215 if err != nil { 216 return nil, err 217 } 218 return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil 219} 220