This commit is contained in:
Yao
2024-12-20 17:49:45 +08:00
parent 86b0363ce1
commit 654d456c7d
7011 changed files with 1705926 additions and 7 deletions

View File

@@ -0,0 +1,44 @@
//
//
// Copyright 2023 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_SECURITY_AUDIT_LOGGING_H
#define GRPCPP_SECURITY_AUDIT_LOGGING_H
#include <memory>
#include <string>
#include <utility>
#include "absl/status/statusor.h"
#include <grpc/grpc_audit_logging.h>
#include <grpcpp/support/string_ref.h>
namespace grpc {
namespace experimental {
using grpc_core::experimental::AuditContext; // NOLINT(misc-unused-using-decls)
using grpc_core::experimental::AuditLogger; // NOLINT(misc-unused-using-decls)
using grpc_core::experimental::
AuditLoggerFactory; // NOLINT(misc-unused-using-decls)
using grpc_core::experimental::
RegisterAuditLoggerFactory; // NOLINT(misc-unused-using-decls)
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_AUDIT_LOGGING_H

View File

@@ -0,0 +1,99 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_SECURITY_AUTH_CONTEXT_H
#define GRPCPP_SECURITY_AUTH_CONTEXT_H
#include <iterator>
#include <vector>
#include <grpcpp/support/config.h>
#include <grpcpp/support/string_ref.h>
struct grpc_auth_context;
struct grpc_auth_property;
struct grpc_auth_property_iterator;
namespace grpc {
class SecureAuthContext;
typedef std::pair<string_ref, string_ref> AuthProperty;
class AuthPropertyIterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = const AuthProperty;
using pointer = void;
using reference = void;
using difference_type = std::ptrdiff_t;
~AuthPropertyIterator();
AuthPropertyIterator& operator++();
AuthPropertyIterator operator++(int);
bool operator==(const AuthPropertyIterator& rhs) const;
bool operator!=(const AuthPropertyIterator& rhs) const;
AuthProperty operator*();
protected:
AuthPropertyIterator();
AuthPropertyIterator(const grpc_auth_property* property,
const grpc_auth_property_iterator* iter);
private:
friend class SecureAuthContext;
const grpc_auth_property* property_;
// The following items form a grpc_auth_property_iterator.
const grpc_auth_context* ctx_;
size_t index_;
const char* name_;
};
/// Class encapsulating the Authentication Information.
///
/// It includes the secure identity of the peer, the type of secure transport
/// used as well as any other properties required by the authorization layer.
class AuthContext {
public:
virtual ~AuthContext() {}
/// Returns true if the peer is authenticated.
virtual bool IsPeerAuthenticated() const = 0;
/// A peer identity.
///
/// It is, in general, comprised of one or more properties (in which case they
/// have the same name).
virtual std::vector<grpc::string_ref> GetPeerIdentity() const = 0;
virtual std::string GetPeerIdentityPropertyName() const = 0;
/// Returns all the property values with the given name.
virtual std::vector<grpc::string_ref> FindPropertyValues(
const std::string& name) const = 0;
/// Iteration over all the properties.
virtual AuthPropertyIterator begin() const = 0;
virtual AuthPropertyIterator end() const = 0;
/// Mutation functions: should only be used by an AuthMetadataProcessor.
virtual void AddProperty(const std::string& key, const string_ref& value) = 0;
virtual bool SetPeerIdentityPropertyName(const std::string& name) = 0;
};
} // namespace grpc
#endif // GRPCPP_SECURITY_AUTH_CONTEXT_H

View File

@@ -0,0 +1,73 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_SECURITY_AUTH_METADATA_PROCESSOR_H
#define GRPCPP_SECURITY_AUTH_METADATA_PROCESSOR_H
#include <map>
#include <grpcpp/security/auth_context.h>
#include <grpcpp/support/status.h>
#include <grpcpp/support/string_ref.h>
namespace grpc {
/// Interface allowing custom server-side authorization based on credentials
/// encoded in metadata. Objects of this type can be passed to
/// \a ServerCredentials::SetAuthMetadataProcessor().
/// Please also check out \a grpc::experimental::Interceptor for another way to
/// do customized operations on the information provided by a specific call.
class AuthMetadataProcessor {
public:
typedef std::multimap<grpc::string_ref, grpc::string_ref> InputMetadata;
typedef std::multimap<std::string, std::string> OutputMetadata;
virtual ~AuthMetadataProcessor() {}
/// If this method returns true, the \a Process function will be scheduled in
/// a different thread from the one processing the call.
virtual bool IsBlocking() const { return true; }
/// Processes a Call associated with a connection.
/// auth_metadata: the authentication metadata associated with the particular
/// call
/// context: contains the connection-level info, e.g. the peer identity. This
/// parameter is readable and writable. Note that since the information is
/// shared for all calls associated with the connection, if the
/// implementation updates the info in a specific call, all the subsequent
/// calls will see the updates. A typical usage of context is to use
/// |auth_metadata| to infer the peer identity, and augment it with
/// properties.
/// consumed_auth_metadata: contains the metadata that the implementation
/// wants to remove from the current call, so that the server application is
/// no longer able to see it anymore. A typical usage would be to do token
/// authentication in the first call, and then remove the token information
/// for all subsequent calls.
/// response_metadata(CURRENTLY NOT SUPPORTED): the metadata that will be sent
/// as part of the response.
/// return: if the return value is not Status::OK, the rpc call will be
/// aborted with the error code and error message sent back to the client.
virtual grpc::Status Process(const InputMetadata& auth_metadata,
grpc::AuthContext* context,
OutputMetadata* consumed_auth_metadata,
OutputMetadata* response_metadata) = 0;
};
} // namespace grpc
#endif // GRPCPP_SECURITY_AUTH_METADATA_PROCESSOR_H

View File

@@ -0,0 +1,88 @@
// Copyright 2021 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GRPCPP_SECURITY_AUTHORIZATION_POLICY_PROVIDER_H
#define GRPCPP_SECURITY_AUTHORIZATION_POLICY_PROVIDER_H
#include <memory>
#include <grpc/grpc_security.h>
#include <grpc/status.h>
#include <grpcpp/impl/codegen/status.h>
namespace grpc {
namespace experimental {
// Wrapper around C-core grpc_authorization_policy_provider. Internally, it
// handles creating and updating authorization engine objects, using SDK
// authorization policy.
class AuthorizationPolicyProviderInterface {
public:
virtual ~AuthorizationPolicyProviderInterface() = default;
virtual grpc_authorization_policy_provider* c_provider() = 0;
};
// Implementation obtains authorization policy from static string. This provider
// will always return the same authorization engines.
class StaticDataAuthorizationPolicyProvider
: public AuthorizationPolicyProviderInterface {
public:
static std::shared_ptr<StaticDataAuthorizationPolicyProvider> Create(
const std::string& authz_policy, grpc::Status* status);
// Use factory method "Create" to create an instance of
// StaticDataAuthorizationPolicyProvider.
explicit StaticDataAuthorizationPolicyProvider(
grpc_authorization_policy_provider* provider)
: c_provider_(provider) {}
~StaticDataAuthorizationPolicyProvider() override;
grpc_authorization_policy_provider* c_provider() override {
return c_provider_;
}
private:
grpc_authorization_policy_provider* c_provider_ = nullptr;
};
// Implementation obtains authorization policy by watching for changes in
// filesystem.
class FileWatcherAuthorizationPolicyProvider
: public AuthorizationPolicyProviderInterface {
public:
static std::shared_ptr<FileWatcherAuthorizationPolicyProvider> Create(
const std::string& authz_policy_path, unsigned int refresh_interval_sec,
grpc::Status* status);
// Use factory method "Create" to create an instance of
// FileWatcherAuthorizationPolicyProvider.
explicit FileWatcherAuthorizationPolicyProvider(
grpc_authorization_policy_provider* provider)
: c_provider_(provider) {}
~FileWatcherAuthorizationPolicyProvider() override;
grpc_authorization_policy_provider* c_provider() override {
return c_provider_;
}
private:
grpc_authorization_policy_provider* c_provider_ = nullptr;
};
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_AUTHORIZATION_POLICY_PROVIDER_H

View File

@@ -0,0 +1,43 @@
// Copyright 2021 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GRPCPP_SECURITY_BINDER_CREDENTIALS_H
#define GRPCPP_SECURITY_BINDER_CREDENTIALS_H
#include <memory>
#include <grpcpp/security/binder_security_policy.h>
#include <grpcpp/security/server_credentials.h>
namespace grpc {
class ChannelCredentials;
namespace experimental {
/// EXPERIMENTAL Builds Binder ServerCredentials.
///
/// This should be used along with `binder:` URI scheme. The path in the URI can
/// later be used to access the server's endpoint binder.
/// Note that calling \a ServerBuilder::AddListeningPort() with Binder
/// ServerCredentials in a non-supported environment will make the subsequent
/// call to \a ServerBuilder::BuildAndStart() return a null pointer.
std::shared_ptr<grpc::ServerCredentials> BinderServerCredentials(
std::shared_ptr<grpc::experimental::binder::SecurityPolicy>
security_policy);
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_BINDER_CREDENTIALS_H

View File

@@ -0,0 +1,82 @@
// Copyright 2021 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GRPCPP_SECURITY_BINDER_SECURITY_POLICY_H
#define GRPCPP_SECURITY_BINDER_SECURITY_POLICY_H
#include <memory>
#ifdef GPR_ANDROID
#include <jni.h>
#endif
namespace grpc {
namespace experimental {
namespace binder {
// EXPERIMENTAL Determinines if a connection is allowed to be
// established on Android. See https://source.android.com/security/app-sandbox
// for more info about UID.
class SecurityPolicy {
public:
virtual ~SecurityPolicy() = default;
// Returns true if the UID is authorized to connect.
// Must return the same value for the same inputs so callers can safely cache
// the result.
virtual bool IsAuthorized(int uid) = 0;
};
// EXPERIMENTAL Allows all connection. Anything on the Android device will be
// able to connect, use with caution!
class UntrustedSecurityPolicy : public SecurityPolicy {
public:
UntrustedSecurityPolicy();
~UntrustedSecurityPolicy() override;
bool IsAuthorized(int uid) override;
};
// EXPERIMENTAL Only allows the connections from processes with the same UID. In
// most cases this means "from the same APK".
class InternalOnlySecurityPolicy : public SecurityPolicy {
public:
InternalOnlySecurityPolicy();
~InternalOnlySecurityPolicy() override;
bool IsAuthorized(int uid) override;
};
#ifdef GPR_ANDROID
// EXPERIMENTAL Only allows the connections from the APK that have the same
// signature.
class SameSignatureSecurityPolicy : public SecurityPolicy {
public:
// `context` is required for getting PackageManager Java class
SameSignatureSecurityPolicy(JavaVM* jvm, jobject context);
~SameSignatureSecurityPolicy() override;
bool IsAuthorized(int uid) override;
private:
JavaVM* jvm_;
jobject context_;
};
#endif
} // namespace binder
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_BINDER_SECURITY_POLICY_H

View File

@@ -0,0 +1,337 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_SECURITY_CREDENTIALS_H
#define GRPCPP_SECURITY_CREDENTIALS_H
#include <map>
#include <memory>
#include <vector>
#include <grpc/grpc_security_constants.h>
#include <grpcpp/channel.h>
#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/security/auth_context.h>
#include <grpcpp/security/tls_credentials_options.h>
#include <grpcpp/support/channel_arguments.h>
#include <grpcpp/support/client_interceptor.h>
#include <grpcpp/support/status.h>
#include <grpcpp/support/string_ref.h>
struct grpc_call;
namespace grpc {
class CallCredentials;
class SecureCallCredentials;
class SecureChannelCredentials;
class ChannelCredentials;
std::shared_ptr<Channel> CreateCustomChannel(
const grpc::string& target,
const std::shared_ptr<grpc::ChannelCredentials>& creds,
const grpc::ChannelArguments& args);
namespace experimental {
std::shared_ptr<grpc::Channel> CreateCustomChannelWithInterceptors(
const grpc::string& target,
const std::shared_ptr<grpc::ChannelCredentials>& creds,
const grpc::ChannelArguments& args,
std::vector<
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
} // namespace experimental
/// Builds XDS Credentials.
std::shared_ptr<ChannelCredentials> XdsCredentials(
const std::shared_ptr<ChannelCredentials>& fallback_creds);
/// A channel credentials object encapsulates all the state needed by a client
/// to authenticate with a server for a given channel.
/// It can make various assertions, e.g., about the clients identity, role
/// for all the calls on that channel.
///
/// \see https://grpc.io/docs/guides/auth.html
class ChannelCredentials : private grpc::internal::GrpcLibrary {
public:
protected:
friend std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
const std::shared_ptr<ChannelCredentials>& channel_creds,
const std::shared_ptr<CallCredentials>& call_creds);
// TODO(yashykt): We need this friend declaration mainly for access to
// AsSecureCredentials(). Once we are able to remove insecure builds from gRPC
// (and also internal dependencies on the indirect method of creating a
// channel through credentials), we would be able to remove this.
friend std::shared_ptr<ChannelCredentials> grpc::XdsCredentials(
const std::shared_ptr<ChannelCredentials>& fallback_creds);
virtual SecureChannelCredentials* AsSecureCredentials() = 0;
private:
friend std::shared_ptr<grpc::Channel> CreateCustomChannel(
const grpc::string& target,
const std::shared_ptr<grpc::ChannelCredentials>& creds,
const grpc::ChannelArguments& args);
friend std::shared_ptr<grpc::Channel>
grpc::experimental::CreateCustomChannelWithInterceptors(
const grpc::string& target,
const std::shared_ptr<grpc::ChannelCredentials>& creds,
const grpc::ChannelArguments& args,
std::vector<std::unique_ptr<
grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
virtual std::shared_ptr<Channel> CreateChannelImpl(
const grpc::string& target, const ChannelArguments& args) = 0;
// This function should have been a pure virtual function, but it is
// implemented as a virtual function so that it does not break API.
virtual std::shared_ptr<Channel> CreateChannelWithInterceptors(
const grpc::string& /*target*/, const ChannelArguments& /*args*/,
std::vector<std::unique_ptr<
grpc::experimental::ClientInterceptorFactoryInterface>>
/*interceptor_creators*/) {
return nullptr;
}
// TODO(yashkt): This is a hack that is needed since InsecureCredentials can
// not use grpc_channel_credentials internally and should be removed after
// insecure builds are removed from gRPC.
virtual bool IsInsecure() const { return false; }
};
/// A call credentials object encapsulates the state needed by a client to
/// authenticate with a server for a given call on a channel.
///
/// \see https://grpc.io/docs/guides/auth.html
class CallCredentials : private grpc::internal::GrpcLibrary {
public:
/// Apply this instance's credentials to \a call.
virtual bool ApplyToCall(grpc_call* call) = 0;
virtual grpc::string DebugString() {
return "CallCredentials did not provide a debug string";
}
protected:
friend std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
const std::shared_ptr<ChannelCredentials>& channel_creds,
const std::shared_ptr<CallCredentials>& call_creds);
friend std::shared_ptr<CallCredentials> CompositeCallCredentials(
const std::shared_ptr<CallCredentials>& creds1,
const std::shared_ptr<CallCredentials>& creds2);
virtual SecureCallCredentials* AsSecureCredentials() = 0;
};
/// Options used to build SslCredentials.
struct SslCredentialsOptions {
/// The buffer containing the PEM encoding of the server root certificates. If
/// this parameter is empty, the default roots will be used. The default
/// roots can be overridden using the \a GRPC_DEFAULT_SSL_ROOTS_FILE_PATH
/// environment variable pointing to a file on the file system containing the
/// roots.
grpc::string pem_root_certs;
/// The buffer containing the PEM encoding of the client's private key. This
/// parameter can be empty if the client does not have a private key.
grpc::string pem_private_key;
/// The buffer containing the PEM encoding of the client's certificate chain.
/// This parameter can be empty if the client does not have a certificate
/// chain.
grpc::string pem_cert_chain;
};
// Factories for building different types of Credentials The functions may
// return empty shared_ptr when credentials cannot be created. If a
// Credentials pointer is returned, it can still be invalid when used to create
// a channel. A lame channel will be created then and all rpcs will fail on it.
/// Builds credentials with reasonable defaults.
///
/// \warning Only use these credentials when connecting to a Google endpoint.
/// Using these credentials to connect to any other service may result in this
/// service being able to impersonate your client for requests to Google
/// services.
std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials();
/// Builds SSL Credentials given SSL specific options
std::shared_ptr<ChannelCredentials> SslCredentials(
const SslCredentialsOptions& options);
/// Builds credentials for use when running in GCE
///
/// \warning Only use these credentials when connecting to a Google endpoint.
/// Using these credentials to connect to any other service may result in this
/// service being able to impersonate your client for requests to Google
/// services.
std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials();
constexpr long kMaxAuthTokenLifetimeSecs = 3600;
/// Builds Service Account JWT Access credentials.
/// json_key is the JSON key string containing the client's private key.
/// token_lifetime_seconds is the lifetime in seconds of each Json Web Token
/// (JWT) created with this credentials. It should not exceed
/// \a kMaxAuthTokenLifetimeSecs or will be cropped to this value.
std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
const grpc::string& json_key,
long token_lifetime_seconds = kMaxAuthTokenLifetimeSecs);
/// Builds refresh token credentials.
/// json_refresh_token is the JSON string containing the refresh token along
/// with a client_id and client_secret.
///
/// \warning Only use these credentials when connecting to a Google endpoint.
/// Using these credentials to connect to any other service may result in this
/// service being able to impersonate your client for requests to Google
/// services.
std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
const grpc::string& json_refresh_token);
/// Builds access token credentials.
/// access_token is an oauth2 access token that was fetched using an out of band
/// mechanism.
///
/// \warning Only use these credentials when connecting to a Google endpoint.
/// Using these credentials to connect to any other service may result in this
/// service being able to impersonate your client for requests to Google
/// services.
std::shared_ptr<CallCredentials> AccessTokenCredentials(
const grpc::string& access_token);
/// Builds IAM credentials.
///
/// \warning Only use these credentials when connecting to a Google endpoint.
/// Using these credentials to connect to any other service may result in this
/// service being able to impersonate your client for requests to Google
/// services.
std::shared_ptr<CallCredentials> GoogleIAMCredentials(
const grpc::string& authorization_token,
const grpc::string& authority_selector);
/// Combines a channel credentials and a call credentials into a composite
/// channel credentials.
std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
const std::shared_ptr<ChannelCredentials>& channel_creds,
const std::shared_ptr<CallCredentials>& call_creds);
/// Combines two call credentials objects into a composite call credentials.
std::shared_ptr<CallCredentials> CompositeCallCredentials(
const std::shared_ptr<CallCredentials>& creds1,
const std::shared_ptr<CallCredentials>& creds2);
/// Credentials for an unencrypted, unauthenticated channel
std::shared_ptr<ChannelCredentials> InsecureChannelCredentials();
/// User defined metadata credentials.
class MetadataCredentialsPlugin {
public:
virtual ~MetadataCredentialsPlugin() {}
/// If this method returns true, the Process function will be scheduled in
/// a different thread from the one processing the call.
virtual bool IsBlocking() const { return true; }
/// Type of credentials this plugin is implementing.
virtual const char* GetType() const { return ""; }
/// Gets the auth metatada produced by this plugin.
/// The fully qualified method name is:
/// service_url + "/" + method_name.
/// The channel_auth_context contains (among other things), the identity of
/// the server.
virtual grpc::Status GetMetadata(
grpc::string_ref service_url, grpc::string_ref method_name,
const grpc::AuthContext& channel_auth_context,
std::multimap<grpc::string, grpc::string>* metadata) = 0;
virtual grpc::string DebugString() {
return "MetadataCredentialsPlugin did not provide a debug string";
}
};
std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
std::unique_ptr<MetadataCredentialsPlugin> plugin);
/// Builds External Account credentials.
/// json_string is the JSON string containing the credentials options.
/// scopes contains the scopes to be binded with the credentials.
std::shared_ptr<CallCredentials> ExternalAccountCredentials(
const grpc::string& json_string, const std::vector<grpc::string>& scopes);
namespace experimental {
/// Options for creating STS Oauth Token Exchange credentials following the IETF
/// draft https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16.
/// Optional fields may be set to empty string. It is the responsibility of the
/// caller to ensure that the subject and actor tokens are refreshed on disk at
/// the specified paths.
struct StsCredentialsOptions {
grpc::string token_exchange_service_uri; // Required.
grpc::string resource; // Optional.
grpc::string audience; // Optional.
grpc::string scope; // Optional.
grpc::string requested_token_type; // Optional.
grpc::string subject_token_path; // Required.
grpc::string subject_token_type; // Required.
grpc::string actor_token_path; // Optional.
grpc::string actor_token_type; // Optional.
};
grpc::Status StsCredentialsOptionsFromJson(const std::string& json_string,
StsCredentialsOptions* options);
/// Creates STS credentials options from the $STS_CREDENTIALS environment
/// variable. This environment variable points to the path of a JSON file
/// comforming to the schema described above.
grpc::Status StsCredentialsOptionsFromEnv(StsCredentialsOptions* options);
std::shared_ptr<CallCredentials> StsCredentials(
const StsCredentialsOptions& options);
std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
std::unique_ptr<MetadataCredentialsPlugin> plugin,
grpc_security_level min_security_level);
/// Options used to build AltsCredentials.
struct AltsCredentialsOptions {
/// service accounts of target endpoint that will be acceptable
/// by the client. If service accounts are provided and none of them matches
/// that of the server, authentication will fail.
std::vector<grpc::string> target_service_accounts;
};
/// Builds ALTS Credentials given ALTS specific options
std::shared_ptr<ChannelCredentials> AltsCredentials(
const AltsCredentialsOptions& options);
/// Builds Local Credentials.
std::shared_ptr<ChannelCredentials> LocalCredentials(
grpc_local_connect_type type);
/// Builds TLS Credentials given TLS options.
std::shared_ptr<ChannelCredentials> TlsCredentials(
const TlsChannelCredentialsOptions& options);
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_CREDENTIALS_H

View File

@@ -0,0 +1,135 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_SECURITY_SERVER_CREDENTIALS_H
#define GRPCPP_SECURITY_SERVER_CREDENTIALS_H
#include <memory>
#include <vector>
#include <grpc/grpc_security_constants.h>
#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/security/auth_metadata_processor.h>
#include <grpcpp/security/tls_credentials_options.h>
#include <grpcpp/support/config.h>
struct grpc_server;
namespace grpc {
class Server;
class ServerCredentials;
class SecureServerCredentials;
/// Options to create ServerCredentials with SSL
struct SslServerCredentialsOptions {
/// \warning Deprecated
SslServerCredentialsOptions()
: force_client_auth(false),
client_certificate_request(GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE) {}
explicit SslServerCredentialsOptions(
grpc_ssl_client_certificate_request_type request_type)
: force_client_auth(false), client_certificate_request(request_type) {}
struct PemKeyCertPair {
std::string private_key;
std::string cert_chain;
};
std::string pem_root_certs;
std::vector<PemKeyCertPair> pem_key_cert_pairs;
/// \warning Deprecated
bool force_client_auth;
/// If both \a force_client_auth and \a client_certificate_request
/// fields are set, \a force_client_auth takes effect, i.e.
/// \a REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
/// will be enforced.
grpc_ssl_client_certificate_request_type client_certificate_request;
};
/// Builds Xds ServerCredentials given fallback credentials
std::shared_ptr<ServerCredentials> XdsServerCredentials(
const std::shared_ptr<ServerCredentials>& fallback_credentials);
/// Wrapper around \a grpc_server_credentials, a way to authenticate a server.
class ServerCredentials : private grpc::internal::GrpcLibrary {
public:
/// This method is not thread-safe and has to be called before the server is
/// started. The last call to this function wins.
virtual void SetAuthMetadataProcessor(
const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) = 0;
private:
friend class Server;
// We need this friend declaration for access to Insecure() and
// AsSecureServerCredentials(). When these two functions are no longer
// necessary, this friend declaration can be removed too.
friend std::shared_ptr<ServerCredentials> grpc::XdsServerCredentials(
const std::shared_ptr<ServerCredentials>& fallback_credentials);
/// Tries to bind \a server to the given \a addr (eg, localhost:1234,
/// 192.168.1.1:31416, [::1]:27182, etc.)
///
/// \return bound port number on success, 0 on failure.
// TODO(dgq): the "port" part seems to be a misnomer.
virtual int AddPortToServer(const std::string& addr, grpc_server* server) = 0;
// TODO(yashykt): This is a hack since InsecureServerCredentials() cannot use
// grpc_insecure_server_credentials_create() and should be removed after
// insecure builds are removed from gRPC.
virtual bool IsInsecure() const { return false; }
// TODO(yashkt): This is a hack that should be removed once we remove insecure
// builds and the indirect method of adding ports to a server.
virtual SecureServerCredentials* AsSecureServerCredentials() {
return nullptr;
}
};
/// Builds SSL ServerCredentials given SSL specific options
std::shared_ptr<ServerCredentials> SslServerCredentials(
const grpc::SslServerCredentialsOptions& options);
std::shared_ptr<ServerCredentials> InsecureServerCredentials();
namespace experimental {
/// Options to create ServerCredentials with ALTS
struct AltsServerCredentialsOptions {
/// Add fields if needed.
};
/// Builds ALTS ServerCredentials given ALTS specific options
std::shared_ptr<ServerCredentials> AltsServerCredentials(
const AltsServerCredentialsOptions& options);
/// Builds Local ServerCredentials.
std::shared_ptr<ServerCredentials> AltsServerCredentials(
const AltsServerCredentialsOptions& options);
std::shared_ptr<ServerCredentials> LocalServerCredentials(
grpc_local_connect_type type);
/// Builds TLS ServerCredentials given TLS options.
std::shared_ptr<ServerCredentials> TlsServerCredentials(
const experimental::TlsServerCredentialsOptions& options);
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_SERVER_CREDENTIALS_H

View File

@@ -0,0 +1,127 @@
//
// Copyright 2020 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPCPP_SECURITY_TLS_CERTIFICATE_PROVIDER_H
#define GRPCPP_SECURITY_TLS_CERTIFICATE_PROVIDER_H
#include <memory>
#include <vector>
#include <grpc/grpc_security.h>
#include <grpc/grpc_security_constants.h>
#include <grpc/status.h>
#include <grpc/support/log.h>
#include <grpcpp/support/config.h>
namespace grpc {
namespace experimental {
// Interface for a class that handles the process to fetch credential data.
// Implementations should be a wrapper class of an internal provider
// implementation.
class GRPCXX_DLL CertificateProviderInterface {
public:
virtual ~CertificateProviderInterface() = default;
virtual grpc_tls_certificate_provider* c_provider() = 0;
};
// A struct that stores the credential data presented to the peer in handshake
// to show local identity. The private_key and certificate_chain should always
// match.
struct GRPCXX_DLL IdentityKeyCertPair {
std::string private_key;
std::string certificate_chain;
};
// A basic CertificateProviderInterface implementation that will load credential
// data from static string during initialization. This provider will always
// return the same cert data for all cert names, and reloading is not supported.
class GRPCXX_DLL StaticDataCertificateProvider
: public CertificateProviderInterface {
public:
StaticDataCertificateProvider(
const std::string& root_certificate,
const std::vector<IdentityKeyCertPair>& identity_key_cert_pairs);
explicit StaticDataCertificateProvider(const std::string& root_certificate)
: StaticDataCertificateProvider(root_certificate, {}) {}
explicit StaticDataCertificateProvider(
const std::vector<IdentityKeyCertPair>& identity_key_cert_pairs)
: StaticDataCertificateProvider("", identity_key_cert_pairs) {}
~StaticDataCertificateProvider() override;
grpc_tls_certificate_provider* c_provider() override { return c_provider_; }
private:
grpc_tls_certificate_provider* c_provider_ = nullptr;
};
// A CertificateProviderInterface implementation that will watch the credential
// changes on the file system. This provider will always return the up-to-date
// cert data for all the cert names callers set through |TlsCredentialsOptions|.
// Several things to note:
// 1. This API only supports one key-cert file and hence one set of identity
// key-cert pair, so SNI(Server Name Indication) is not supported.
// 2. The private key and identity certificate should always match. This API
// guarantees atomic read, and it is the callers' responsibility to do atomic
// updates. There are many ways to atomically update the key and certs in the
// file system. To name a few:
// 1) creating a new directory, renaming the old directory to a new name, and
// then renaming the new directory to the original name of the old directory.
// 2) using a symlink for the directory. When need to change, put new
// credential data in a new directory, and change symlink.
class GRPCXX_DLL FileWatcherCertificateProvider final
: public CertificateProviderInterface {
public:
// Constructor to get credential updates from root and identity file paths.
//
// @param private_key_path is the file path of the private key.
// @param identity_certificate_path is the file path of the identity
// certificate chain.
// @param root_cert_path is the file path to the root certificate bundle.
// @param refresh_interval_sec is the refreshing interval that we will check
// the files for updates.
FileWatcherCertificateProvider(const std::string& private_key_path,
const std::string& identity_certificate_path,
const std::string& root_cert_path,
unsigned int refresh_interval_sec);
// Constructor to get credential updates from identity file paths only.
FileWatcherCertificateProvider(const std::string& private_key_path,
const std::string& identity_certificate_path,
unsigned int refresh_interval_sec)
: FileWatcherCertificateProvider(private_key_path,
identity_certificate_path, "",
refresh_interval_sec) {}
// Constructor to get credential updates from root file path only.
FileWatcherCertificateProvider(const std::string& root_cert_path,
unsigned int refresh_interval_sec)
: FileWatcherCertificateProvider("", "", root_cert_path,
refresh_interval_sec) {}
~FileWatcherCertificateProvider() override;
grpc_tls_certificate_provider* c_provider() override { return c_provider_; }
private:
grpc_tls_certificate_provider* c_provider_ = nullptr;
};
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_TLS_CERTIFICATE_PROVIDER_H

View File

@@ -0,0 +1,243 @@
//
// Copyright 2021 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPCPP_SECURITY_TLS_CERTIFICATE_VERIFIER_H
#define GRPCPP_SECURITY_TLS_CERTIFICATE_VERIFIER_H
#include <functional>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include <grpc/grpc_security_constants.h>
#include <grpc/status.h>
#include <grpc/support/log.h>
#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/impl/sync.h>
#include <grpcpp/support/config.h>
#include <grpcpp/support/status.h>
#include <grpcpp/support/string_ref.h>
// TODO(yihuazhang): remove the forward declaration here and include
// <grpc/grpc_security.h> directly once the insecure builds are cleaned up.
typedef struct grpc_tls_custom_verification_check_request
grpc_tls_custom_verification_check_request;
typedef struct grpc_tls_certificate_verifier grpc_tls_certificate_verifier;
typedef struct grpc_tls_certificate_verifier_external
grpc_tls_certificate_verifier_external;
typedef void (*grpc_tls_on_custom_verification_check_done_cb)(
grpc_tls_custom_verification_check_request* request, void* callback_arg,
grpc_status_code status, const char* error_details);
extern "C" grpc_tls_certificate_verifier*
grpc_tls_certificate_verifier_external_create(
grpc_tls_certificate_verifier_external* external_verifier);
namespace grpc {
namespace experimental {
// Contains the verification-related information associated with a connection
// request. Users should not directly create or destroy this request object, but
// shall interact with it through CertificateVerifier's Verify() and Cancel().
class TlsCustomVerificationCheckRequest {
public:
explicit TlsCustomVerificationCheckRequest(
grpc_tls_custom_verification_check_request* request);
~TlsCustomVerificationCheckRequest() {}
grpc::string_ref target_name() const;
grpc::string_ref peer_cert() const;
grpc::string_ref peer_cert_full_chain() const;
grpc::string_ref common_name() const;
// The subject name of the root certificate used to verify the peer chain
// If verification fails or the peer cert is self-signed, this will be an
// empty string. If verification is successful, it is a comma-separated list,
// where the entries are of the form "FIELD_ABBREVIATION=string"
// ex: "CN=testca,O=Internet Widgits Pty Ltd,ST=Some-State,C=AU"
// ex: "CN=GTS Root R1,O=Google Trust Services LLC,C=US"
grpc::string_ref verified_root_cert_subject() const;
std::vector<grpc::string_ref> uri_names() const;
std::vector<grpc::string_ref> dns_names() const;
std::vector<grpc::string_ref> email_names() const;
std::vector<grpc::string_ref> ip_names() const;
grpc_tls_custom_verification_check_request* c_request() { return c_request_; }
private:
grpc_tls_custom_verification_check_request* c_request_ = nullptr;
};
// The base class of all internal verifier implementations, and the ultimate
// class that all external verifiers will eventually be transformed into.
// To implement a custom verifier, do not extend this class; instead,
// implement a subclass of ExternalCertificateVerifier. Note that custom
// verifier implementations can compose their functionality with existing
// implementations of this interface, such as HostnameVerifier, by delegating
// to an instance of that class.
class CertificateVerifier {
public:
explicit CertificateVerifier(grpc_tls_certificate_verifier* v);
~CertificateVerifier();
// Verifies a connection request, based on the logic specified in an internal
// verifier. The check on each internal verifier could be either synchronous
// or asynchronous, and we will need to use return value to know.
//
// request: the verification information associated with this request
// callback: This will only take effect if the verifier is asynchronous.
// The function that gRPC will invoke when the verifier has already
// completed its asynchronous check. Callers can use this function
// to perform any additional checks. The input parameter of the
// std::function indicates the status of the verifier check.
// sync_status: This will only be useful if the verifier is synchronous.
// The status of the verifier as it has already done it's
// synchronous check.
// return: return true if executed synchronously, otherwise return false
bool Verify(TlsCustomVerificationCheckRequest* request,
std::function<void(grpc::Status)> callback,
grpc::Status* sync_status);
// Cancels a verification request previously started via Verify().
// Used when the connection attempt times out or is cancelled while an async
// verification request is pending.
//
// request: the verification information associated with this request
void Cancel(TlsCustomVerificationCheckRequest* request);
// Gets the core verifier used internally.
grpc_tls_certificate_verifier* c_verifier() { return verifier_; }
private:
static void AsyncCheckDone(
grpc_tls_custom_verification_check_request* request, void* callback_arg,
grpc_status_code status, const char* error_details);
grpc_tls_certificate_verifier* verifier_ = nullptr;
grpc::internal::Mutex mu_;
std::map<grpc_tls_custom_verification_check_request*,
std::function<void(grpc::Status)>>
request_map_ ABSL_GUARDED_BY(mu_);
};
// The base class of all external, user-specified verifiers. Users should
// inherit this class to implement a custom verifier.
// Note that while implementing the custom verifier that extends this class, it
// is possible to compose an existing ExternalCertificateVerifier or
// CertificateVerifier, inside the Verify() and Cancel() function of the new
// custom verifier.
class ExternalCertificateVerifier {
public:
// A factory method for creating a |CertificateVerifier| from this class. All
// the user-implemented verifiers should use this function to be converted to
// verifiers compatible with |TlsCredentialsOptions|.
// The resulting CertificateVerifier takes ownership of the newly instantiated
// Subclass.
template <typename Subclass, typename... Args>
static std::shared_ptr<CertificateVerifier> Create(Args&&... args) {
auto* external_verifier = new Subclass(std::forward<Args>(args)...);
return std::make_shared<CertificateVerifier>(
grpc_tls_certificate_verifier_external_create(
external_verifier->base_));
}
// The verification logic that will be performed after the TLS handshake
// completes. Implementers can choose to do their checks synchronously or
// asynchronously.
//
// request: the verification information associated with this request
// callback: This should only be used if your check is done asynchronously.
// When the asynchronous work is done, invoke this callback function
// with the proper status, indicating the success or the failure of
// the check. The implementer MUST NOT invoke this |callback| in the
// same thread before Verify() returns, otherwise it can lead to
// deadlocks.
// sync_status: This should only be used if your check is done synchronously.
// Modifies this value to indicate the success or the failure of
// the check.
// return: return true if your check is done synchronously, otherwise return
// false
virtual bool Verify(TlsCustomVerificationCheckRequest* request,
std::function<void(grpc::Status)> callback,
grpc::Status* sync_status) = 0;
// Cancels a verification request previously started via Verify().
// Used when the connection attempt times out or is cancelled while an async
// verification request is pending. The implementation should abort whatever
// async operation it is waiting for and quickly invoke the callback that was
// passed to Verify() with a status indicating the cancellation.
//
// request: the verification information associated with this request
virtual void Cancel(TlsCustomVerificationCheckRequest* request) = 0;
protected:
ExternalCertificateVerifier();
virtual ~ExternalCertificateVerifier();
private:
struct AsyncRequestState {
AsyncRequestState(grpc_tls_on_custom_verification_check_done_cb cb,
void* arg,
grpc_tls_custom_verification_check_request* request)
: callback(cb), callback_arg(arg), cpp_request(request) {}
grpc_tls_on_custom_verification_check_done_cb callback;
void* callback_arg;
TlsCustomVerificationCheckRequest cpp_request;
};
static int VerifyInCoreExternalVerifier(
void* user_data, grpc_tls_custom_verification_check_request* request,
grpc_tls_on_custom_verification_check_done_cb callback,
void* callback_arg, grpc_status_code* sync_status,
char** sync_error_details);
static void CancelInCoreExternalVerifier(
void* user_data, grpc_tls_custom_verification_check_request* request);
static void DestructInCoreExternalVerifier(void* user_data);
// TODO(yihuazhang): after the insecure build is removed, make this an object
// member instead of a pointer.
grpc_tls_certificate_verifier_external* base_ = nullptr;
grpc::internal::Mutex mu_;
std::map<grpc_tls_custom_verification_check_request*, AsyncRequestState>
request_map_ ABSL_GUARDED_BY(mu_);
};
// A CertificateVerifier that doesn't perform any additional checks other than
// certificate verification, if specified.
// Note: using this solely without any other authentication mechanisms on the
// peer identity will leave your applications to the MITM(Man-In-The-Middle)
// attacks. Users should avoid doing so in production environments.
class NoOpCertificateVerifier : public CertificateVerifier {
public:
NoOpCertificateVerifier();
};
// A CertificateVerifier that will perform hostname verification, to see if the
// target name set from the client side matches the identity information
// specified on the server's certificate.
class HostNameCertificateVerifier : public CertificateVerifier {
public:
HostNameCertificateVerifier();
};
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_TLS_CERTIFICATE_VERIFIER_H

View File

@@ -0,0 +1,195 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H
#define GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H
#include <memory>
#include <vector>
#include <grpc/grpc_security.h>
#include <grpc/grpc_security_constants.h>
#include <grpc/status.h>
#include <grpc/support/log.h>
#include <grpcpp/security/tls_certificate_provider.h>
#include <grpcpp/security/tls_certificate_verifier.h>
#include <grpcpp/security/tls_crl_provider.h>
#include <grpcpp/support/config.h>
namespace grpc {
namespace experimental {
// Base class of configurable options specified by users to configure their
// certain security features supported in TLS. It is used for experimental
// purposes for now and it is subject to change.
class TlsCredentialsOptions {
public:
// Constructor for base class TlsCredentialsOptions.
//
// @param certificate_provider the provider which fetches TLS credentials that
// will be used in the TLS handshake
TlsCredentialsOptions();
~TlsCredentialsOptions();
// Copy constructor does a deep copy of the underlying pointer. No assignment
// permitted
TlsCredentialsOptions(const TlsCredentialsOptions& other);
TlsCredentialsOptions& operator=(const TlsCredentialsOptions& other) = delete;
// ---- Setters for member fields ----
// Sets the certificate provider used to store root certs and identity certs.
void set_certificate_provider(
std::shared_ptr<CertificateProviderInterface> certificate_provider);
// Watches the updates of root certificates with name |root_cert_name|.
// If used in TLS credentials, setting this field is optional for both the
// client side and the server side.
// If this is not set on the client side, we will use the root certificates
// stored in the default system location, since client side must provide root
// certificates in TLS(no matter single-side TLS or mutual TLS).
// If this is not set on the server side, we will not watch any root
// certificate updates, and assume no root certificates needed for the server
// (in the one-side TLS scenario, the server is not required to provide root
// certs). We don't support default root certs on server side.
void watch_root_certs();
// Sets the name of root certificates being watched, if |watch_root_certs| is
// called. If not set, an empty string will be used as the name.
//
// @param root_cert_name the name of root certs being set.
void set_root_cert_name(const std::string& root_cert_name);
// Watches the updates of identity key-cert pairs with name
// |identity_cert_name|. If used in TLS credentials, it is required to be set
// on the server side, and optional for the client side(in the one-side
// TLS scenario, the client is not required to provide identity certs).
void watch_identity_key_cert_pairs();
// Sets the name of identity key-cert pairs being watched, if
// |watch_identity_key_cert_pairs| is called. If not set, an empty string will
// be used as the name.
//
// @param identity_cert_name the name of identity key-cert pairs being set.
void set_identity_cert_name(const std::string& identity_cert_name);
// Sets the Tls session key logging configuration. If not set, tls
// session key logging is disabled. Note that this should be used only for
// debugging purposes. It should never be used in a production environment
// due to security concerns.
//
// @param tls_session_key_log_file_path: Path where tls session keys would
// be logged.
void set_tls_session_key_log_file_path(
const std::string& tls_session_key_log_file_path);
// Sets the certificate verifier used to perform post-handshake peer identity
// checks.
void set_certificate_verifier(
std::shared_ptr<CertificateVerifier> certificate_verifier);
// Sets the options of whether to check the hostname of the peer on a per-call
// basis. This is usually used in a combination with virtual hosting at the
// client side, where each individual call on a channel can have a different
// host associated with it.
// This check is intended to verify that the host specified for the individual
// call is covered by the cert that the peer presented.
// We will perform such checks by default. This should be disabled if
// verifiers other than the host name verifier is used.
void set_check_call_host(bool check_call_host);
// Deprecated in favor of set_crl_provider. The
// crl provider interface provides a significantly more flexible approach to
// using CRLs. See gRFC A69 for details.
// If set, gRPC will read all hashed x.509 CRL files in the directory and
// enforce the CRL files on all TLS handshakes. Only supported for OpenSSL
// version > 1.1.
void set_crl_directory(const std::string& path);
void set_crl_provider(std::shared_ptr<CrlProvider> crl_provider);
// Sets the minimum TLS version that will be negotiated during the TLS
// handshake. If not set, the underlying SSL library will use TLS v1.2.
// @param tls_version: The minimum TLS version.
void set_min_tls_version(grpc_tls_version tls_version);
// Sets the maximum TLS version that will be negotiated during the TLS
// handshake. If not set, the underlying SSL library will use TLS v1.3.
// @param tls_version: The maximum TLS version.
void set_max_tls_version(grpc_tls_version tls_version);
// ----- Getters for member fields ----
// Returns a deep copy of the internal c options. The caller takes ownership
// of the returned pointer. This function shall be used only internally.
grpc_tls_credentials_options* c_credentials_options() const;
protected:
// Returns the internal c options. The caller does not take ownership of the
// returned pointer.
grpc_tls_credentials_options* mutable_c_credentials_options() {
return c_credentials_options_;
}
private:
std::shared_ptr<CertificateProviderInterface> certificate_provider_;
std::shared_ptr<CertificateVerifier> certificate_verifier_;
grpc_tls_credentials_options* c_credentials_options_ = nullptr;
};
// Contains configurable options on the client side.
// Client side doesn't need to always use certificate provider. When the
// certificate provider is not set, we will use the root certificates stored
// in the system default locations, and assume client won't provide any
// identity certificates(single side TLS).
// It is used for experimental purposes for now and it is subject to change.
class TlsChannelCredentialsOptions final : public TlsCredentialsOptions {
public:
// Sets the decision of whether to do a crypto check on the server certs.
// The default is true.
void set_verify_server_certs(bool verify_server_certs);
private:
};
// Contains configurable options on the server side.
// It is used for experimental purposes for now and it is subject to change.
class TlsServerCredentialsOptions final : public TlsCredentialsOptions {
public:
// Server side is required to use a provider, because server always needs to
// use identity certs.
explicit TlsServerCredentialsOptions(
std::shared_ptr<CertificateProviderInterface> certificate_provider)
: TlsCredentialsOptions() {
set_certificate_provider(certificate_provider);
}
// Sets option to request the certificates from the client.
// The default is GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE.
void set_cert_request_type(
grpc_ssl_client_certificate_request_type cert_request_type);
// Sets whether or not a TLS server should send a list of CA names in the
// ServerHello. This list of CA names is read from the server's trust bundle,
// so that the client can use this list as a hint to know which certificate it
// should send to the server.
//
// By default, this option is turned off.
//
// WARNING: This API is extremely dangerous and should not be used. If the
// server's trust bundle is too large, then the TLS server will be unable to
// form a ServerHello, and hence will be unusable.
void set_send_client_ca_list(bool send_client_ca_list);
private:
};
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_TLS_CREDENTIALS_OPTIONS_H

View File

@@ -0,0 +1,39 @@
//
//
// Copyright 2023 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_SECURITY_TLS_CRL_PROVIDER_H
#define GRPCPP_SECURITY_TLS_CRL_PROVIDER_H
#include <grpc/grpc_crl_provider.h>
#include <grpcpp/impl/sync.h>
#include <grpcpp/support/string_ref.h>
namespace grpc {
namespace experimental {
using grpc_core::experimental::
CertificateInfo; // NOLINT(misc-unused-using-decls)
using grpc_core::experimental::
CreateStaticCrlProvider; // NOLINT(misc-unused-using-decls)
using grpc_core::experimental::Crl; // NOLINT(misc-unused-using-decls)
using grpc_core::experimental::CrlProvider; // NOLINT(misc-unused-using-decls)
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_SECURITY_TLS_CRL_PROVIDER_H