Commit bc2ee55f authored by Lutz Justen's avatar Lutz Justen Committed by Commit Bot

Refactor CloudPolicyValidator

Refactored CloudPolicyValidator so that the base class doesn't expect
the policy_value() to be a protobuf. This is a preparation for the
support of extension policy for Active Directory managed devices, where
the policy_value() is a JSON blob.

Also removed the static Create methods. There's no reason to have them
as one can use the constructor directly. The rest is clang format.

BUG=chromium:735100
TEST=Trybots

Change-Id: Ic952c2cd00e945910f62d0ad08839282818d1d1e
Reviewed-on: https://chromium-review.googlesource.com/1002654Reviewed-by: default avatarBartosz Fabianowski <bartfab@chromium.org>
Reviewed-by: default avatarMaksim Ivanov <emaxx@chromium.org>
Commit-Queue: Lutz Justen <ljusten@chromium.org>
Cr-Commit-Position: refs/heads/master@{#550169}
parent b2a2ee99
...@@ -114,10 +114,9 @@ void DeviceCloudPolicyStoreChromeOS::OnDeviceSettingsServiceShutdown() { ...@@ -114,10 +114,9 @@ void DeviceCloudPolicyStoreChromeOS::OnDeviceSettingsServiceShutdown() {
std::unique_ptr<DeviceCloudPolicyValidator> std::unique_ptr<DeviceCloudPolicyValidator>
DeviceCloudPolicyStoreChromeOS::CreateValidator( DeviceCloudPolicyStoreChromeOS::CreateValidator(
const em::PolicyFetchResponse& policy) { const em::PolicyFetchResponse& policy) {
std::unique_ptr<DeviceCloudPolicyValidator> validator( auto validator = std::make_unique<DeviceCloudPolicyValidator>(
DeviceCloudPolicyValidator::Create(
std::make_unique<em::PolicyFetchResponse>(policy), std::make_unique<em::PolicyFetchResponse>(policy),
background_task_runner_)); background_task_runner_);
validator->ValidateDomain(install_attributes_->GetDomain()); validator->ValidateDomain(install_attributes_->GetDomain());
validator->ValidatePolicyType(dm_protocol::kChromeDevicePolicyType); validator->ValidatePolicyType(dm_protocol::kChromeDevicePolicyType);
validator->ValidatePayload(); validator->ValidatePayload();
......
...@@ -137,8 +137,7 @@ void DeviceLocalAccountPolicyStore::StoreValidatedPolicy( ...@@ -137,8 +137,7 @@ void DeviceLocalAccountPolicyStore::StoreValidatedPolicy(
} }
session_manager_client_->StoreDeviceLocalAccountPolicy( session_manager_client_->StoreDeviceLocalAccountPolicy(
account_id_, account_id_, policy_blob,
policy_blob,
base::Bind(&DeviceLocalAccountPolicyStore::HandleStoreResult, base::Bind(&DeviceLocalAccountPolicyStore::HandleStoreResult,
weak_factory_.GetWeakPtr())); weak_factory_.GetWeakPtr()));
} }
...@@ -191,9 +190,8 @@ void DeviceLocalAccountPolicyStore::Validate( ...@@ -191,9 +190,8 @@ void DeviceLocalAccountPolicyStore::Validate(
return; return;
} }
std::unique_ptr<UserCloudPolicyValidator> validator( auto validator = std::make_unique<UserCloudPolicyValidator>(
UserCloudPolicyValidator::Create(std::move(policy_response), std::move(policy_response), background_task_runner());
background_task_runner()));
validator->ValidateUsername(account_id_, false); validator->ValidateUsername(account_id_, false);
validator->ValidatePolicyType(dm_protocol::kChromePublicAccountPolicyType); validator->ValidatePolicyType(dm_protocol::kChromePublicAccountPolicyType);
// The timestamp is verified when storing a new policy downloaded from the // The timestamp is verified when storing a new policy downloaded from the
......
...@@ -242,15 +242,14 @@ void EnrollmentHandlerChromeOS::OnPolicyFetched(CloudPolicyClient* client) { ...@@ -242,15 +242,14 @@ void EnrollmentHandlerChromeOS::OnPolicyFetched(CloudPolicyClient* client) {
const em::PolicyFetchResponse* policy = client_->GetPolicyFor( const em::PolicyFetchResponse* policy = client_->GetPolicyFor(
dm_protocol::kChromeDevicePolicyType, std::string()); dm_protocol::kChromeDevicePolicyType, std::string());
if (!policy) { if (!policy) {
ReportResult(EnrollmentStatus::ForFetchError( ReportResult(
DM_STATUS_RESPONSE_DECODING_ERROR)); EnrollmentStatus::ForFetchError(DM_STATUS_RESPONSE_DECODING_ERROR));
return; return;
} }
std::unique_ptr<DeviceCloudPolicyValidator> validator( auto validator = std::make_unique<DeviceCloudPolicyValidator>(
DeviceCloudPolicyValidator::Create(
std::make_unique<em::PolicyFetchResponse>(*policy), std::make_unique<em::PolicyFetchResponse>(*policy),
background_task_runner_)); background_task_runner_);
validator->ValidateTimestamp(base::Time(), validator->ValidateTimestamp(base::Time(),
CloudPolicyValidatorBase::TIMESTAMP_VALIDATED); CloudPolicyValidatorBase::TIMESTAMP_VALIDATED);
...@@ -312,8 +311,7 @@ void EnrollmentHandlerChromeOS::OnClientError(CloudPolicyClient* client) { ...@@ -312,8 +311,7 @@ void EnrollmentHandlerChromeOS::OnClientError(CloudPolicyClient* client) {
DCHECK_EQ(client_.get(), client); DCHECK_EQ(client_.get(), client);
if (enrollment_step_ == STEP_ROBOT_AUTH_FETCH) { if (enrollment_step_ == STEP_ROBOT_AUTH_FETCH) {
LOG(ERROR) << "API authentication code fetch failed: " LOG(ERROR) << "API authentication code fetch failed: " << client_->status();
<< client_->status();
ReportResult(EnrollmentStatus::ForRobotAuthFetchError(client_->status())); ReportResult(EnrollmentStatus::ForRobotAuthFetchError(client_->status()));
} else if (enrollment_step_ < STEP_POLICY_FETCH) { } else if (enrollment_step_ < STEP_POLICY_FETCH) {
ReportResult(EnrollmentStatus::ForRegistrationError(client_->status())); ReportResult(EnrollmentStatus::ForRegistrationError(client_->status()));
...@@ -452,12 +450,10 @@ void EnrollmentHandlerChromeOS::OnRobotAuthCodesFetched( ...@@ -452,12 +450,10 @@ void EnrollmentHandlerChromeOS::OnRobotAuthCodesFetched(
client_info.redirect_uri = "oob"; client_info.redirect_uri = "oob";
// Use the system request context to avoid sending user cookies. // Use the system request context to avoid sending user cookies.
gaia_oauth_client_.reset(new gaia::GaiaOAuthClient( gaia_oauth_client_.reset(
g_browser_process->system_request_context())); new gaia::GaiaOAuthClient(g_browser_process->system_request_context()));
gaia_oauth_client_->GetTokensFromAuthCode(client_info, gaia_oauth_client_->GetTokensFromAuthCode(
client->robot_api_auth_code(), client_info, client->robot_api_auth_code(), 0 /* max_retries */, this);
0 /* max_retries */,
this);
} }
// GaiaOAuthClient::Delegate callback for OAuth2 refresh token fetched. // GaiaOAuthClient::Delegate callback for OAuth2 refresh token fetched.
...@@ -528,8 +524,7 @@ void EnrollmentHandlerChromeOS::OnNetworkError(int response_code) { ...@@ -528,8 +524,7 @@ void EnrollmentHandlerChromeOS::OnNetworkError(int response_code) {
CHECK_EQ(STEP_ROBOT_AUTH_REFRESH, enrollment_step_); CHECK_EQ(STEP_ROBOT_AUTH_REFRESH, enrollment_step_);
LOG(ERROR) << "Network error while fetching API refresh token: " LOG(ERROR) << "Network error while fetching API refresh token: "
<< response_code; << response_code;
ReportResult( ReportResult(EnrollmentStatus::ForRobotRefreshFetchError(response_code));
EnrollmentStatus::ForRobotRefreshFetchError(response_code));
} }
void EnrollmentHandlerChromeOS::StartJoinAdDomain() { void EnrollmentHandlerChromeOS::StartJoinAdDomain() {
......
...@@ -295,8 +295,8 @@ void PreSigninPolicyFetcher::NotifyCallback( ...@@ -295,8 +295,8 @@ void PreSigninPolicyFetcher::NotifyCallback(
std::unique_ptr<UserCloudPolicyValidator> std::unique_ptr<UserCloudPolicyValidator>
PreSigninPolicyFetcher::CreateValidatorForCachedPolicy( PreSigninPolicyFetcher::CreateValidatorForCachedPolicy(
std::unique_ptr<em::PolicyFetchResponse> policy) { std::unique_ptr<em::PolicyFetchResponse> policy) {
std::unique_ptr<UserCloudPolicyValidator> validator = auto validator = std::make_unique<UserCloudPolicyValidator>(std::move(policy),
UserCloudPolicyValidator::Create(std::move(policy), task_runner_); task_runner_);
validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType); validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType);
validator->ValidatePayload(); validator->ValidatePayload();
...@@ -314,8 +314,8 @@ std::unique_ptr<UserCloudPolicyValidator> ...@@ -314,8 +314,8 @@ std::unique_ptr<UserCloudPolicyValidator>
PreSigninPolicyFetcher::CreateValidatorForFetchedPolicy( PreSigninPolicyFetcher::CreateValidatorForFetchedPolicy(
std::unique_ptr<em::PolicyFetchResponse> policy) { std::unique_ptr<em::PolicyFetchResponse> policy) {
// Configure the validator to validate based on cached policy. // Configure the validator to validate based on cached policy.
std::unique_ptr<UserCloudPolicyValidator> validator = auto validator = std::make_unique<UserCloudPolicyValidator>(std::move(policy),
UserCloudPolicyValidator::Create(std::move(policy), task_runner_); task_runner_);
validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType); validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType);
validator->ValidateAgainstCurrentPolicy( validator->ValidateAgainstCurrentPolicy(
......
...@@ -167,8 +167,8 @@ void SessionManagerOperation::ValidateDeviceSettings( ...@@ -167,8 +167,8 @@ void SessionManagerOperation::ValidateDeviceSettings(
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
std::unique_ptr<policy::DeviceCloudPolicyValidator> validator = std::unique_ptr<policy::DeviceCloudPolicyValidator> validator =
policy::DeviceCloudPolicyValidator::Create(std::move(policy), std::make_unique<policy::DeviceCloudPolicyValidator>(
background_task_runner); std::move(policy), background_task_runner);
if (cloud_validations_) { if (cloud_validations_) {
// Policy auto-generated by session manager doesn't include a timestamp, so // Policy auto-generated by session manager doesn't include a timestamp, so
......
...@@ -128,7 +128,6 @@ void CloudPolicyValidatorBase::ValidatePayload() { ...@@ -128,7 +128,6 @@ void CloudPolicyValidatorBase::ValidatePayload() {
validation_flags_ |= VALIDATE_PAYLOAD; validation_flags_ |= VALIDATE_PAYLOAD;
} }
void CloudPolicyValidatorBase::ValidateCachedKey( void CloudPolicyValidatorBase::ValidateCachedKey(
const std::string& cached_key, const std::string& cached_key,
const std::string& cached_key_signature, const std::string& cached_key_signature,
...@@ -181,11 +180,9 @@ void CloudPolicyValidatorBase::ValidateAgainstCurrentPolicy( ...@@ -181,11 +180,9 @@ void CloudPolicyValidatorBase::ValidateAgainstCurrentPolicy(
CloudPolicyValidatorBase::CloudPolicyValidatorBase( CloudPolicyValidatorBase::CloudPolicyValidatorBase(
std::unique_ptr<em::PolicyFetchResponse> policy_response, std::unique_ptr<em::PolicyFetchResponse> policy_response,
google::protobuf::MessageLite* payload,
scoped_refptr<base::SequencedTaskRunner> background_task_runner) scoped_refptr<base::SequencedTaskRunner> background_task_runner)
: status_(VALIDATION_OK), : status_(VALIDATION_OK),
policy_(std::move(policy_response)), policy_(std::move(policy_response)),
payload_(payload),
validation_flags_(0), validation_flags_(0),
timestamp_not_before_(0), timestamp_not_before_(0),
timestamp_option_(TIMESTAMP_VALIDATED), timestamp_option_(TIMESTAMP_VALIDATED),
...@@ -236,6 +233,18 @@ void CloudPolicyValidatorBase::RunValidation() { ...@@ -236,6 +233,18 @@ void CloudPolicyValidatorBase::RunValidation() {
RunChecks(); RunChecks();
} }
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckProtoPayload(
google::protobuf::MessageLite* payload) {
DCHECK(payload);
if (!policy_data_ || !policy_data_->has_policy_value() ||
!payload->ParseFromString(policy_data_->policy_value()) ||
!payload->IsInitialized()) {
LOG(ERROR) << "Failed to decode policy payload protobuf";
return VALIDATION_POLICY_PARSE_ERROR;
}
return VALIDATION_OK;
}
void CloudPolicyValidatorBase::RunChecks() { void CloudPolicyValidatorBase::RunChecks() {
status_ = VALIDATION_OK; status_ = VALIDATION_OK;
if ((policy_->has_error_code() && policy_->error_code() != 200) || if ((policy_->has_error_code() && policy_->error_code() != 200) ||
...@@ -259,19 +268,19 @@ void CloudPolicyValidatorBase::RunChecks() { ...@@ -259,19 +268,19 @@ void CloudPolicyValidatorBase::RunChecks() {
// error, s.t. the most severe check will determine the validation status. // error, s.t. the most severe check will determine the validation status.
static const struct { static const struct {
int flag; int flag;
Status (CloudPolicyValidatorBase::* checkFunction)(); Status (CloudPolicyValidatorBase::*checkFunction)();
} kCheckFunctions[] = { } kCheckFunctions[] = {
{ VALIDATE_SIGNATURE, &CloudPolicyValidatorBase::CheckSignature }, {VALIDATE_SIGNATURE, &CloudPolicyValidatorBase::CheckSignature},
{ VALIDATE_INITIAL_KEY, &CloudPolicyValidatorBase::CheckInitialKey }, {VALIDATE_INITIAL_KEY, &CloudPolicyValidatorBase::CheckInitialKey},
{ VALIDATE_CACHED_KEY, &CloudPolicyValidatorBase::CheckCachedKey }, {VALIDATE_CACHED_KEY, &CloudPolicyValidatorBase::CheckCachedKey},
{ VALIDATE_POLICY_TYPE, &CloudPolicyValidatorBase::CheckPolicyType }, {VALIDATE_POLICY_TYPE, &CloudPolicyValidatorBase::CheckPolicyType},
{ VALIDATE_ENTITY_ID, &CloudPolicyValidatorBase::CheckEntityId }, {VALIDATE_ENTITY_ID, &CloudPolicyValidatorBase::CheckEntityId},
{ VALIDATE_DM_TOKEN, &CloudPolicyValidatorBase::CheckDMToken }, {VALIDATE_DM_TOKEN, &CloudPolicyValidatorBase::CheckDMToken},
{ VALIDATE_DEVICE_ID, &CloudPolicyValidatorBase::CheckDeviceId }, {VALIDATE_DEVICE_ID, &CloudPolicyValidatorBase::CheckDeviceId},
{ VALIDATE_USER, &CloudPolicyValidatorBase::CheckUser }, {VALIDATE_USER, &CloudPolicyValidatorBase::CheckUser},
{ VALIDATE_DOMAIN, &CloudPolicyValidatorBase::CheckDomain }, {VALIDATE_DOMAIN, &CloudPolicyValidatorBase::CheckDomain},
{ VALIDATE_TIMESTAMP, &CloudPolicyValidatorBase::CheckTimestamp }, {VALIDATE_TIMESTAMP, &CloudPolicyValidatorBase::CheckTimestamp},
{ VALIDATE_PAYLOAD, &CloudPolicyValidatorBase::CheckPayload }, {VALIDATE_PAYLOAD, &CloudPolicyValidatorBase::CheckPayload},
}; };
for (size_t i = 0; i < arraysize(kCheckFunctions); ++i) { for (size_t i = 0; i < arraysize(kCheckFunctions); ++i) {
...@@ -296,8 +305,7 @@ bool CloudPolicyValidatorBase::CheckNewPublicKeyVerificationSignature() { ...@@ -296,8 +305,7 @@ bool CloudPolicyValidatorBase::CheckNewPublicKeyVerificationSignature() {
} }
if (!CheckVerificationKeySignature( if (!CheckVerificationKeySignature(
policy_->new_public_key(), policy_->new_public_key(), verification_key_,
verification_key_,
policy_->new_public_key_verification_signature_deprecated())) { policy_->new_public_key_verification_signature_deprecated())) {
LOG(ERROR) << "Signature verification failed"; LOG(ERROR) << "Signature verification failed";
UMA_HISTOGRAM_ENUMERATION(kMetricPolicyKeyVerification, UMA_HISTOGRAM_ENUMERATION(kMetricPolicyKeyVerification,
...@@ -324,8 +332,8 @@ bool CloudPolicyValidatorBase::CheckVerificationKeySignature( ...@@ -324,8 +332,8 @@ bool CloudPolicyValidatorBase::CheckVerificationKeySignature(
// If no owning_domain_ supplied, try extracting the domain from the policy // If no owning_domain_ supplied, try extracting the domain from the policy
// itself (this happens on certain platforms during startup, when we validate // itself (this happens on certain platforms during startup, when we validate
// cached policy before prefs are loaded). // cached policy before prefs are loaded).
std::string domain = owning_domain_.empty() ? std::string domain =
ExtractDomainFromPolicy() : owning_domain_; owning_domain_.empty() ? ExtractDomainFromPolicy() : owning_domain_;
if (domain.empty()) { if (domain.empty()) {
LOG(ERROR) << "Policy does not contain a domain"; LOG(ERROR) << "Policy does not contain a domain";
return false; return false;
...@@ -344,8 +352,7 @@ std::string CloudPolicyValidatorBase::ExtractDomainFromPolicy() { ...@@ -344,8 +352,7 @@ std::string CloudPolicyValidatorBase::ExtractDomainFromPolicy() {
std::string domain; std::string domain;
if (policy_data_->has_username()) { if (policy_data_->has_username()) {
domain = gaia::ExtractDomainName( domain = gaia::ExtractDomainName(
gaia::CanonicalizeEmail( gaia::CanonicalizeEmail(gaia::SanitizeEmail(policy_data_->username())));
gaia::SanitizeEmail(policy_data_->username())));
} }
return domain; return domain;
} }
...@@ -385,8 +392,7 @@ CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckSignature() { ...@@ -385,8 +392,7 @@ CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckSignature() {
} }
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckInitialKey() { CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckInitialKey() {
if (!policy_->has_new_public_key() || if (!policy_->has_new_public_key() || !policy_->has_policy_data_signature() ||
!policy_->has_policy_data_signature() ||
!VerifySignature(policy_->policy_data(), policy_->new_public_key(), !VerifySignature(policy_->policy_data(), policy_->new_public_key(),
policy_->policy_data_signature(), SHA1)) { policy_->policy_data_signature(), SHA1)) {
LOG(ERROR) << "Initial policy signature validation failed"; LOG(ERROR) << "Initial policy signature validation failed";
...@@ -468,8 +474,7 @@ CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDMToken() { ...@@ -468,8 +474,7 @@ CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDMToken() {
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDeviceId() { CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDeviceId() {
if (device_id_option_ == DEVICE_ID_REQUIRED && if (device_id_option_ == DEVICE_ID_REQUIRED &&
(!policy_data_->has_device_id() || (!policy_data_->has_device_id() || policy_data_->device_id().empty())) {
policy_data_->device_id().empty())) {
LOG(ERROR) << "Empty device id encountered - expected: " << device_id_; LOG(ERROR) << "Empty device id encountered - expected: " << device_id_;
return VALIDATION_BAD_DEVICE_ID; return VALIDATION_BAD_DEVICE_ID;
} }
...@@ -545,17 +550,6 @@ CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDomain() { ...@@ -545,17 +550,6 @@ CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckDomain() {
return VALIDATION_OK; return VALIDATION_OK;
} }
CloudPolicyValidatorBase::Status CloudPolicyValidatorBase::CheckPayload() {
if (!policy_data_->has_policy_value() ||
!payload_->ParseFromString(policy_data_->policy_value()) ||
!payload_->IsInitialized()) {
LOG(ERROR) << "Failed to decode policy payload protobuf";
return VALIDATION_POLICY_PARSE_ERROR;
}
return VALIDATION_OK;
}
// static // static
bool CloudPolicyValidatorBase::VerifySignature(const std::string& data, bool CloudPolicyValidatorBase::VerifySignature(const std::string& data,
const std::string& key, const std::string& key,
......
...@@ -36,12 +36,12 @@ namespace google { ...@@ -36,12 +36,12 @@ namespace google {
namespace protobuf { namespace protobuf {
class MessageLite; class MessageLite;
} }
} } // namespace google
namespace enterprise_management { namespace enterprise_management {
class PolicyData; class PolicyData;
class PolicyFetchResponse; class PolicyFetchResponse;
} } // namespace enterprise_management
namespace policy { namespace policy {
...@@ -225,13 +225,10 @@ class POLICY_EXPORT CloudPolicyValidatorBase { ...@@ -225,13 +225,10 @@ class POLICY_EXPORT CloudPolicyValidatorBase {
void RunValidation(); void RunValidation();
protected: protected:
// Create a new validator that checks |policy_response|. |payload| is the // Create a new validator that checks |policy_response|.
// message that the policy payload will be parsed to, and it needs to stay
// valid for the lifetime of the validator.
CloudPolicyValidatorBase( CloudPolicyValidatorBase(
std::unique_ptr<enterprise_management::PolicyFetchResponse> std::unique_ptr<enterprise_management::PolicyFetchResponse>
policy_response, policy_response,
google::protobuf::MessageLite* payload,
scoped_refptr<base::SequencedTaskRunner> background_task_runner); scoped_refptr<base::SequencedTaskRunner> background_task_runner);
// Posts an asynchronous call to PerformValidation of the passed |validator|, // Posts an asynchronous call to PerformValidation of the passed |validator|,
...@@ -240,6 +237,11 @@ class POLICY_EXPORT CloudPolicyValidatorBase { ...@@ -240,6 +237,11 @@ class POLICY_EXPORT CloudPolicyValidatorBase {
std::unique_ptr<CloudPolicyValidatorBase> validator, std::unique_ptr<CloudPolicyValidatorBase> validator,
const base::Closure& completion_callback); const base::Closure& completion_callback);
// Helper to check MessageLite-type payloads. It exists so the implementation
// can be moved to the .cc (PolicyValidators with protobuf payloads are
// templated).
Status CheckProtoPayload(google::protobuf::MessageLite* payload);
private: private:
// Internal flags indicating what to check. // Internal flags indicating what to check.
enum ValidationFlags { enum ValidationFlags {
...@@ -256,10 +258,7 @@ class POLICY_EXPORT CloudPolicyValidatorBase { ...@@ -256,10 +258,7 @@ class POLICY_EXPORT CloudPolicyValidatorBase {
VALIDATE_DEVICE_ID = 1 << 10, VALIDATE_DEVICE_ID = 1 << 10,
}; };
enum SignatureType { enum SignatureType { SHA1, SHA256 };
SHA1,
SHA256
};
// Performs validation, called on a background thread. // Performs validation, called on a background thread.
static void PerformValidation( static void PerformValidation(
...@@ -301,11 +300,13 @@ class POLICY_EXPORT CloudPolicyValidatorBase { ...@@ -301,11 +300,13 @@ class POLICY_EXPORT CloudPolicyValidatorBase {
Status CheckDeviceId(); Status CheckDeviceId();
Status CheckPolicyType(); Status CheckPolicyType();
Status CheckEntityId(); Status CheckEntityId();
Status CheckPayload();
Status CheckSignature(); Status CheckSignature();
Status CheckInitialKey(); Status CheckInitialKey();
Status CheckCachedKey(); Status CheckCachedKey();
// Payload type depends on the validator, checking is part of derived classes.
virtual Status CheckPayload() = 0;
// Verifies the SHA1/ or SHA256/RSA |signature| on |data| against |key|. // Verifies the SHA1/ or SHA256/RSA |signature| on |data| against |key|.
// |signature_type| specifies the type of signature (SHA1 or SHA256). // |signature_type| specifies the type of signature (SHA1 or SHA256).
static bool VerifySignature(const std::string& data, static bool VerifySignature(const std::string& data,
...@@ -316,7 +317,6 @@ class POLICY_EXPORT CloudPolicyValidatorBase { ...@@ -316,7 +317,6 @@ class POLICY_EXPORT CloudPolicyValidatorBase {
Status status_; Status status_;
std::unique_ptr<enterprise_management::PolicyFetchResponse> policy_; std::unique_ptr<enterprise_management::PolicyFetchResponse> policy_;
std::unique_ptr<enterprise_management::PolicyData> policy_data_; std::unique_ptr<enterprise_management::PolicyData> policy_data_;
google::protobuf::MessageLite* payload_;
int validation_flags_; int validation_flags_;
int64_t timestamp_not_before_; int64_t timestamp_not_before_;
...@@ -343,24 +343,21 @@ class POLICY_EXPORT CloudPolicyValidatorBase { ...@@ -343,24 +343,21 @@ class POLICY_EXPORT CloudPolicyValidatorBase {
// A simple type-parameterized extension of CloudPolicyValidator that // A simple type-parameterized extension of CloudPolicyValidator that
// facilitates working with the actual protobuf payload type. // facilitates working with the actual protobuf payload type.
template<typename PayloadProto> template <typename PayloadProto>
class POLICY_EXPORT CloudPolicyValidator : public CloudPolicyValidatorBase { class POLICY_EXPORT CloudPolicyValidator final
: public CloudPolicyValidatorBase {
public: public:
using CompletionCallback = base::Callback<void(CloudPolicyValidator*)>; using CompletionCallback = base::Callback<void(CloudPolicyValidator*)>;
virtual ~CloudPolicyValidator() {}
// Creates a new validator. // Creates a new validator.
// |background_task_runner| is optional; if RunValidation() is used directly // |background_task_runner| is optional; if RunValidation() is used directly
// and StartValidation() is not used then it can be nullptr. // and StartValidation() is not used then it can be nullptr.
static std::unique_ptr<CloudPolicyValidator> Create( CloudPolicyValidator(
std::unique_ptr<enterprise_management::PolicyFetchResponse> std::unique_ptr<enterprise_management::PolicyFetchResponse>
policy_response, policy_response,
scoped_refptr<base::SequencedTaskRunner> background_task_runner) { scoped_refptr<base::SequencedTaskRunner> background_task_runner)
return base::WrapUnique<CloudPolicyValidator>(new CloudPolicyValidator( : CloudPolicyValidatorBase(std::move(policy_response),
std::move(policy_response), std::make_unique<PayloadProto>(), background_task_runner) {}
background_task_runner));
}
std::unique_ptr<PayloadProto>& payload() { return payload_; } std::unique_ptr<PayloadProto>& payload() { return payload_; }
...@@ -375,17 +372,10 @@ class POLICY_EXPORT CloudPolicyValidator : public CloudPolicyValidatorBase { ...@@ -375,17 +372,10 @@ class POLICY_EXPORT CloudPolicyValidator : public CloudPolicyValidatorBase {
} }
private: private:
CloudPolicyValidator( // CloudPolicyValidatorBase:
std::unique_ptr<enterprise_management::PolicyFetchResponse> Status CheckPayload() override { return CheckProtoPayload(payload_.get()); }
policy_response,
std::unique_ptr<PayloadProto> payload,
scoped_refptr<base::SequencedTaskRunner> background_task_runner)
: CloudPolicyValidatorBase(std::move(policy_response),
payload.get(),
background_task_runner),
payload_(std::move(payload)) {}
std::unique_ptr<PayloadProto> payload_; std::unique_ptr<PayloadProto> payload_ = std::make_unique<PayloadProto>();
DISALLOW_COPY_AND_ASSIGN(CloudPolicyValidator); DISALLOW_COPY_AND_ASSIGN(CloudPolicyValidator);
}; };
......
...@@ -70,8 +70,8 @@ class CloudPolicyValidatorTest : public testing::Test { ...@@ -70,8 +70,8 @@ class CloudPolicyValidatorTest : public testing::Test {
CreateValidator(std::move(policy_response)); CreateValidator(std::move(policy_response));
// Run validation and check the result. // Run validation and check the result.
EXPECT_CALL(*this, ValidationCompletion(validator.get())).WillOnce( EXPECT_CALL(*this, ValidationCompletion(validator.get()))
check_action); .WillOnce(check_action);
UserCloudPolicyValidator::StartValidation( UserCloudPolicyValidator::StartValidation(
std::move(validator), std::move(validator),
base::Bind(&CloudPolicyValidatorTest::ValidationCompletion, base::Bind(&CloudPolicyValidatorTest::ValidationCompletion,
...@@ -85,9 +85,8 @@ class CloudPolicyValidatorTest : public testing::Test { ...@@ -85,9 +85,8 @@ class CloudPolicyValidatorTest : public testing::Test {
std::string public_key = PolicyBuilder::GetPublicTestKeyAsString(); std::string public_key = PolicyBuilder::GetPublicTestKeyAsString();
EXPECT_FALSE(public_key.empty()); EXPECT_FALSE(public_key.empty());
std::unique_ptr<UserCloudPolicyValidator> validator = auto validator = std::make_unique<UserCloudPolicyValidator>(
UserCloudPolicyValidator::Create(std::move(policy_response), std::move(policy_response), base::ThreadTaskRunnerHandle::Get());
base::ThreadTaskRunnerHandle::Get());
validator->ValidateTimestamp(timestamp_, timestamp_option_); validator->ValidateTimestamp(timestamp_, timestamp_option_);
if (validate_by_gaia_id_) { if (validate_by_gaia_id_) {
validator->ValidateUser( validator->ValidateUser(
...@@ -101,8 +100,7 @@ class CloudPolicyValidatorTest : public testing::Test { ...@@ -101,8 +100,7 @@ class CloudPolicyValidatorTest : public testing::Test {
validator->ValidateDeviceId(existing_device_id_, device_id_option_); validator->ValidateDeviceId(existing_device_id_, device_id_option_);
validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType); validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType);
validator->ValidatePayload(); validator->ValidatePayload();
validator->ValidateCachedKey(public_key, validator->ValidateCachedKey(public_key, cached_key_signature_,
cached_key_signature_,
owning_domain_); owning_domain_);
if (allow_key_rotation_) { if (allow_key_rotation_) {
validator->ValidateSignatureAllowingRotation(public_key, owning_domain_); validator->ValidateSignatureAllowingRotation(public_key, owning_domain_);
...@@ -113,7 +111,6 @@ class CloudPolicyValidatorTest : public testing::Test { ...@@ -113,7 +111,6 @@ class CloudPolicyValidatorTest : public testing::Test {
return validator; return validator;
} }
void CheckSuccessfulValidation(UserCloudPolicyValidator* validator) { void CheckSuccessfulValidation(UserCloudPolicyValidator* validator) {
EXPECT_TRUE(validator->success()); EXPECT_TRUE(validator->success());
EXPECT_EQ(policy_.policy().SerializeAsString(), EXPECT_EQ(policy_.policy().SerializeAsString(),
...@@ -378,7 +375,8 @@ TEST_F(CloudPolicyValidatorTest, ErrorInvalidPublicKeyVerificationSignature) { ...@@ -378,7 +375,8 @@ TEST_F(CloudPolicyValidatorTest, ErrorInvalidPublicKeyVerificationSignature) {
policy_.Build(); policy_.Build();
policy_.policy().set_new_public_key_verification_signature_deprecated( policy_.policy().set_new_public_key_verification_signature_deprecated(
"invalid"); "invalid");
ValidatePolicy(CheckStatus( ValidatePolicy(
CheckStatus(
CloudPolicyValidatorBase::VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE), CloudPolicyValidatorBase::VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE),
policy_.GetCopy()); policy_.GetCopy());
} }
...@@ -388,7 +386,8 @@ TEST_F(CloudPolicyValidatorTest, ErrorDomainMismatchForKeyVerification) { ...@@ -388,7 +386,8 @@ TEST_F(CloudPolicyValidatorTest, ErrorDomainMismatchForKeyVerification) {
// Generate a non-matching owning_domain, which should cause a validation // Generate a non-matching owning_domain, which should cause a validation
// failure. // failure.
owning_domain_ = "invalid.com"; owning_domain_ = "invalid.com";
ValidatePolicy(CheckStatus( ValidatePolicy(
CheckStatus(
CloudPolicyValidatorBase::VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE), CloudPolicyValidatorBase::VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE),
policy_.GetCopy()); policy_.GetCopy());
} }
...@@ -401,7 +400,8 @@ TEST_F(CloudPolicyValidatorTest, ErrorDomainExtractedFromUsernameMismatch) { ...@@ -401,7 +400,8 @@ TEST_F(CloudPolicyValidatorTest, ErrorDomainExtractedFromUsernameMismatch) {
// Pass an empty domain to tell validator to extract the domain from the // Pass an empty domain to tell validator to extract the domain from the
// policy's |username| field. // policy's |username| field.
owning_domain_ = ""; owning_domain_ = "";
ValidatePolicy(CheckStatus( ValidatePolicy(
CheckStatus(
CloudPolicyValidatorBase::VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE), CloudPolicyValidatorBase::VALIDATION_BAD_KEY_VERIFICATION_SIGNATURE),
policy_.GetCopy()); policy_.GetCopy());
} }
......
...@@ -261,8 +261,7 @@ void ComponentCloudPolicyStore::Purge( ...@@ -261,8 +261,7 @@ void ComponentCloudPolicyStore::Purge(
bool purged_current_policies = false; bool purged_current_policies = false;
for (PolicyBundle::const_iterator it = policy_bundle_.begin(); for (PolicyBundle::const_iterator it = policy_bundle_.begin();
it != policy_bundle_.end(); ++it) { it != policy_bundle_.end(); ++it) {
if (it->first.domain == domain && if (it->first.domain == domain && filter.Run(it->first.component_id) &&
filter.Run(it->first.component_id) &&
!policy_bundle_.Get(it->first).empty()) { !policy_bundle_.Get(it->first).empty()) {
policy_bundle_.Get(it->first).Clear(); policy_bundle_.Get(it->first).Clear();
purged_current_policies = true; purged_current_policies = true;
...@@ -334,9 +333,8 @@ bool ComponentCloudPolicyStore::ValidatePolicy( ...@@ -334,9 +333,8 @@ bool ComponentCloudPolicyStore::ValidatePolicy(
if (stored_policy_times_iter != stored_policy_times_.end()) if (stored_policy_times_iter != stored_policy_times_.end())
time_not_before = stored_policy_times_iter->second; time_not_before = stored_policy_times_iter->second;
std::unique_ptr<ComponentCloudPolicyValidator> validator( auto validator = std::make_unique<ComponentCloudPolicyValidator>(
ComponentCloudPolicyValidator::Create( std::move(proto), scoped_refptr<base::SequencedTaskRunner>());
std::move(proto), scoped_refptr<base::SequencedTaskRunner>()));
validator->ValidateTimestamp(time_not_before, validator->ValidateTimestamp(time_not_before,
CloudPolicyValidatorBase::TIMESTAMP_VALIDATED); CloudPolicyValidatorBase::TIMESTAMP_VALIDATED);
validator->ValidateUser(account_id_); validator->ValidateUser(account_id_);
...@@ -388,8 +386,7 @@ bool ComponentCloudPolicyStore::ValidatePolicy( ...@@ -388,8 +386,7 @@ bool ComponentCloudPolicyStore::ValidatePolicy(
return true; return true;
} }
bool ComponentCloudPolicyStore::ValidateData( bool ComponentCloudPolicyStore::ValidateData(const std::string& data,
const std::string& data,
const std::string& secure_hash, const std::string& secure_hash,
PolicyMap* policy) { PolicyMap* policy) {
if (crypto::SHA256HashString(data) != secure_hash) { if (crypto::SHA256HashString(data) != secure_hash) {
......
...@@ -71,9 +71,8 @@ std::unique_ptr<UserCloudPolicyValidator> ...@@ -71,9 +71,8 @@ std::unique_ptr<UserCloudPolicyValidator>
MachineLevelUserCloudPolicyStore::CreateValidator( MachineLevelUserCloudPolicyStore::CreateValidator(
std::unique_ptr<enterprise_management::PolicyFetchResponse> policy, std::unique_ptr<enterprise_management::PolicyFetchResponse> policy,
CloudPolicyValidatorBase::ValidateTimestampOption option) { CloudPolicyValidatorBase::ValidateTimestampOption option) {
std::unique_ptr<UserCloudPolicyValidator> validator = auto validator = std::make_unique<UserCloudPolicyValidator>(
UserCloudPolicyValidator::Create(std::move(policy), std::move(policy), background_task_runner());
background_task_runner());
validator->ValidatePolicyType( validator->ValidatePolicyType(
dm_protocol::kChromeMachineLevelUserCloudPolicyType); dm_protocol::kChromeMachineLevelUserCloudPolicyType);
validator->ValidateDMToken(machine_dm_token_, validator->ValidateDMToken(machine_dm_token_,
......
...@@ -27,21 +27,18 @@ UserCloudPolicyStoreBase::UserCloudPolicyStoreBase( ...@@ -27,21 +27,18 @@ UserCloudPolicyStoreBase::UserCloudPolicyStoreBase(
: background_task_runner_(background_task_runner), : background_task_runner_(background_task_runner),
policy_scope_(policy_scope) {} policy_scope_(policy_scope) {}
UserCloudPolicyStoreBase::~UserCloudPolicyStoreBase() { UserCloudPolicyStoreBase::~UserCloudPolicyStoreBase() {}
}
std::unique_ptr<UserCloudPolicyValidator> std::unique_ptr<UserCloudPolicyValidator>
UserCloudPolicyStoreBase::CreateValidator( UserCloudPolicyStoreBase::CreateValidator(
std::unique_ptr<enterprise_management::PolicyFetchResponse> policy, std::unique_ptr<enterprise_management::PolicyFetchResponse> policy,
CloudPolicyValidatorBase::ValidateTimestampOption timestamp_option) { CloudPolicyValidatorBase::ValidateTimestampOption timestamp_option) {
// Configure the validator. // Configure the validator.
std::unique_ptr<UserCloudPolicyValidator> validator = auto validator = std::make_unique<UserCloudPolicyValidator>(
UserCloudPolicyValidator::Create(std::move(policy), std::move(policy), background_task_runner_);
background_task_runner_);
validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType); validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType);
validator->ValidateAgainstCurrentPolicy( validator->ValidateAgainstCurrentPolicy(
policy_.get(), policy_.get(), timestamp_option,
timestamp_option,
CloudPolicyValidatorBase::DM_TOKEN_REQUIRED, CloudPolicyValidatorBase::DM_TOKEN_REQUIRED,
CloudPolicyValidatorBase::DEVICE_ID_REQUIRED); CloudPolicyValidatorBase::DEVICE_ID_REQUIRED);
validator->ValidatePayload(); validator->ValidatePayload();
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment