1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
6 
7 #include <stddef.h>
8 
9 #include <utility>
10 
11 #include "base/bind.h"
12 #include "base/callback.h"
13 #include "base/callback_helpers.h"
14 #include "base/command_line.h"
15 #include "base/files/file_path.h"
16 #include "base/macros.h"
17 #include "base/path_service.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/system/sys_info.h"
20 #include "base/time/time.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/chromeos/attestation/attestation_policy_observer.h"
23 #include "chrome/browser/chromeos/attestation/enrollment_certificate_uploader_impl.h"
24 #include "chrome/browser/chromeos/attestation/enrollment_policy_observer.h"
25 #include "chrome/browser/chromeos/attestation/machine_certificate_uploader_impl.h"
26 #include "chrome/browser/chromeos/login/enrollment/auto_enrollment_controller.h"
27 #include "chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h"
28 #include "chrome/browser/chromeos/policy/heartbeat_scheduler.h"
29 #include "chrome/browser/chromeos/policy/policy_pref_names.h"
30 #include "chrome/browser/chromeos/policy/remote_commands/device_commands_factory_chromeos.h"
31 #include "chrome/browser/chromeos/policy/rsu/lookup_key_uploader.h"
32 #include "chrome/browser/chromeos/policy/server_backed_state_keys_broker.h"
33 #include "chrome/browser/chromeos/policy/status_collector/device_status_collector.h"
34 #include "chrome/browser/chromeos/policy/status_uploader.h"
35 #include "chrome/browser/chromeos/policy/system_log_uploader.h"
36 #include "chrome/common/pref_names.h"
37 #include "chromeos/constants/chromeos_constants.h"
38 #include "chromeos/constants/chromeos_paths.h"
39 #include "chromeos/constants/chromeos_switches.h"
40 #include "chromeos/system/statistics_provider.h"
41 #include "chromeos/tpm/install_attributes.h"
42 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
43 #include "components/policy/core/common/cloud/cloud_policy_core.h"
44 #include "components/policy/core/common/cloud/cloud_policy_service.h"
45 #include "components/policy/core/common/cloud/cloud_policy_store.h"
46 #include "components/policy/core/common/cloud/policy_invalidation_scope.h"
47 #include "components/policy/core/common/policy_types.h"
48 #include "components/policy/core/common/remote_commands/remote_commands_factory.h"
49 #include "components/policy/core/common/schema_registry.h"
50 #include "components/policy/proto/device_management_backend.pb.h"
51 #include "components/prefs/pref_registry_simple.h"
52 #include "components/prefs/pref_service.h"
53 #include "content/public/browser/network_service_instance.h"
54 #include "crypto/sha2.h"
55 #include "services/network/public/cpp/shared_url_loader_factory.h"
56 #include "url/gurl.h"
57 
58 namespace em = enterprise_management;
59 
60 namespace policy {
61 
62 namespace {
63 
64 // Zero-touch enrollment flag values.
65 
66 const char kZeroTouchEnrollmentForced[] = "forced";
67 const char kZeroTouchEnrollmentHandsOff[] = "hands-off";
68 
69 // Default frequency for uploading enterprise status reports. Can be overriden
70 // by Device Policy.
71 constexpr base::TimeDelta kDeviceStatusUploadFrequency =
72     base::TimeDelta::FromHours(3);
73 
74 // Checks whether forced re-enrollment is enabled.
ForcedReEnrollmentEnabled()75 bool ForcedReEnrollmentEnabled() {
76   return chromeos::AutoEnrollmentController::IsFREEnabled();
77 }
78 
79 }  // namespace
80 
DeviceCloudPolicyManagerChromeOS(std::unique_ptr<DeviceCloudPolicyStoreChromeOS> store,std::unique_ptr<CloudExternalDataManager> external_data_manager,const scoped_refptr<base::SequencedTaskRunner> & task_runner,ServerBackedStateKeysBroker * state_keys_broker)81 DeviceCloudPolicyManagerChromeOS::DeviceCloudPolicyManagerChromeOS(
82     std::unique_ptr<DeviceCloudPolicyStoreChromeOS> store,
83     std::unique_ptr<CloudExternalDataManager> external_data_manager,
84     const scoped_refptr<base::SequencedTaskRunner>& task_runner,
85     ServerBackedStateKeysBroker* state_keys_broker)
86     : CloudPolicyManager(
87           dm_protocol::kChromeDevicePolicyType,
88           std::string(),
89           store.get(),
90           task_runner,
91           base::BindRepeating(&content::GetNetworkConnectionTracker)),
92       device_store_(std::move(store)),
93       external_data_manager_(std::move(external_data_manager)),
94       state_keys_broker_(state_keys_broker),
95       task_runner_(task_runner),
96       local_state_(nullptr) {}
97 
~DeviceCloudPolicyManagerChromeOS()98 DeviceCloudPolicyManagerChromeOS::~DeviceCloudPolicyManagerChromeOS() {}
99 
Initialize(PrefService * local_state)100 void DeviceCloudPolicyManagerChromeOS::Initialize(PrefService* local_state) {
101   CHECK(local_state);
102 
103   local_state_ = local_state;
104 
105   state_keys_update_subscription_ = state_keys_broker_->RegisterUpdateCallback(
106       base::Bind(&DeviceCloudPolicyManagerChromeOS::OnStateKeysUpdated,
107                  base::Unretained(this)));
108 }
109 
AddDeviceCloudPolicyManagerObserver(Observer * observer)110 void DeviceCloudPolicyManagerChromeOS::AddDeviceCloudPolicyManagerObserver(
111     Observer* observer) {
112   observers_.AddObserver(observer);
113 }
114 
RemoveDeviceCloudPolicyManagerObserver(Observer * observer)115 void DeviceCloudPolicyManagerChromeOS::RemoveDeviceCloudPolicyManagerObserver(
116     Observer* observer) {
117   observers_.RemoveObserver(observer);
118 }
119 
120 // Keep clean up order as the reversed creation order.
Shutdown()121 void DeviceCloudPolicyManagerChromeOS::Shutdown() {
122   heartbeat_scheduler_.reset();
123   syslog_uploader_.reset();
124   status_uploader_.reset();
125   external_data_manager_->Disconnect();
126   state_keys_update_subscription_.reset();
127   CloudPolicyManager::Shutdown();
128   signin_profile_forwarding_schema_registry_.reset();
129 }
130 
131 // static
RegisterPrefs(PrefRegistrySimple * registry)132 void DeviceCloudPolicyManagerChromeOS::RegisterPrefs(
133     PrefRegistrySimple* registry) {
134   registry->RegisterDictionaryPref(prefs::kServerBackedDeviceState);
135   registry->RegisterBooleanPref(prefs::kRemoveUsersRemoteCommand, false);
136   registry->RegisterStringPref(prefs::kLastRsuDeviceIdUploaded, std::string());
137   registry->RegisterListPref(prefs::kStoreLogStatesAcrossReboots);
138 }
139 
140 // static
141 ZeroTouchEnrollmentMode
GetZeroTouchEnrollmentMode()142 DeviceCloudPolicyManagerChromeOS::GetZeroTouchEnrollmentMode() {
143   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
144   if (!command_line->HasSwitch(
145           chromeos::switches::kEnterpriseEnableZeroTouchEnrollment)) {
146     return ZeroTouchEnrollmentMode::DISABLED;
147   }
148 
149   std::string value = command_line->GetSwitchValueASCII(
150       chromeos::switches::kEnterpriseEnableZeroTouchEnrollment);
151   if (value == kZeroTouchEnrollmentForced) {
152     return ZeroTouchEnrollmentMode::FORCED;
153   }
154   if (value == kZeroTouchEnrollmentHandsOff) {
155     return ZeroTouchEnrollmentMode::HANDS_OFF;
156   }
157   if (value.empty()) {
158     return ZeroTouchEnrollmentMode::ENABLED;
159   }
160   LOG(WARNING) << "Malformed value \"" << value << "\" for switch --"
161                << chromeos::switches::kEnterpriseEnableZeroTouchEnrollment
162                << ". Ignoring switch.";
163   return ZeroTouchEnrollmentMode::DISABLED;
164 }
165 
StartConnection(std::unique_ptr<CloudPolicyClient> client_to_connect,chromeos::InstallAttributes * install_attributes)166 void DeviceCloudPolicyManagerChromeOS::StartConnection(
167     std::unique_ptr<CloudPolicyClient> client_to_connect,
168     chromeos::InstallAttributes* install_attributes) {
169   CHECK(!service());
170 
171   // Set state keys here so the first policy fetch submits them to the server.
172   if (ForcedReEnrollmentEnabled())
173     client_to_connect->SetStateKeysToUpload(state_keys_broker_->state_keys());
174 
175   // Create the component cloud policy service for fetching, caching and
176   // exposing policy for extensions.
177   if (!component_policy_disabled_for_testing_) {
178     const base::FilePath component_policy_cache_dir =
179         base::PathService::CheckedGet(
180             chromeos::DIR_SIGNIN_PROFILE_COMPONENT_POLICY);
181     CHECK(signin_profile_forwarding_schema_registry_);
182     CreateComponentCloudPolicyService(
183         dm_protocol::kChromeSigninExtensionPolicyType,
184         component_policy_cache_dir, POLICY_SOURCE_CLOUD,
185         client_to_connect.get(),
186         signin_profile_forwarding_schema_registry_.get());
187   }
188 
189   core()->Connect(std::move(client_to_connect));
190   core()->StartRefreshScheduler();
191   core()->RefreshSoon();
192   core()->TrackRefreshDelayPref(local_state_,
193                                 prefs::kDevicePolicyRefreshRate);
194 
195   external_data_manager_->Connect(
196       g_browser_process->shared_url_loader_factory());
197 
198   enrollment_certificate_uploader_.reset(
199       new chromeos::attestation::EnrollmentCertificateUploaderImpl(client()));
200   enrollment_policy_observer_.reset(
201       new chromeos::attestation::EnrollmentPolicyObserver(client()));
202   lookup_key_uploader_.reset(
203       new LookupKeyUploader(device_store(), g_browser_process->local_state(),
204                             enrollment_certificate_uploader_.get()));
205 
206   // Don't create a MachineCertificateUploader or start the
207   // AttestationPolicyObserver if machine cert requests are disabled.
208   if (!(base::CommandLine::ForCurrentProcess()->HasSwitch(
209           chromeos::switches::kDisableMachineCertRequest))) {
210     machine_certificate_uploader_.reset(
211         new chromeos::attestation::MachineCertificateUploaderImpl(client()));
212     attestation_policy_observer_.reset(
213         new chromeos::attestation::AttestationPolicyObserver(
214             machine_certificate_uploader_.get()));
215   }
216 
217   // Start remote commands services now that we have setup everything they need.
218   core()->StartRemoteCommandsService(
219       std::make_unique<DeviceCommandsFactoryChromeOS>(this),
220       PolicyInvalidationScope::kDevice);
221 
222   // Enable device reporting and status monitoring for cloud managed devices. We
223   // want to create these objects even if monitoring is currently inactive, in
224   // case monitoring is turned back on in a future policy fetch - the classes
225   // themselves track the current state of the monitoring settings and only
226   // perform monitoring if it is active.
227   if (install_attributes->IsCloudManaged()) {
228     CreateStatusUploader();
229     syslog_uploader_.reset(new SystemLogUploader(nullptr, task_runner_));
230     heartbeat_scheduler_.reset(new HeartbeatScheduler(
231         g_browser_process->gcm_driver(), client(), device_store_.get(),
232         install_attributes->GetDeviceId(), task_runner_));
233   }
234 
235   NotifyConnected();
236 }
237 
Unregister(const UnregisterCallback & callback)238 void DeviceCloudPolicyManagerChromeOS::Unregister(
239     const UnregisterCallback& callback) {
240   if (!service()) {
241     LOG(ERROR) << "Tried to unregister but DeviceCloudPolicyManagerChromeOS is "
242                << "not connected.";
243     callback.Run(false);
244     return;
245   }
246 
247   service()->Unregister(callback);
248 }
249 
Disconnect()250 void DeviceCloudPolicyManagerChromeOS::Disconnect() {
251   status_uploader_.reset();
252   syslog_uploader_.reset();
253   heartbeat_scheduler_.reset();
254   core()->Disconnect();
255 
256   NotifyDisconnected();
257 }
258 
SetSigninProfileSchemaRegistry(SchemaRegistry * schema_registry)259 void DeviceCloudPolicyManagerChromeOS::SetSigninProfileSchemaRegistry(
260     SchemaRegistry* schema_registry) {
261   DCHECK(!signin_profile_forwarding_schema_registry_);
262   signin_profile_forwarding_schema_registry_.reset(
263       new ForwardingSchemaRegistry(schema_registry));
264 }
265 
OnStateKeysUpdated()266 void DeviceCloudPolicyManagerChromeOS::OnStateKeysUpdated() {
267   if (client() && ForcedReEnrollmentEnabled())
268     client()->SetStateKeysToUpload(state_keys_broker_->state_keys());
269 }
270 
NotifyConnected()271 void DeviceCloudPolicyManagerChromeOS::NotifyConnected() {
272   for (auto& observer : observers_)
273     observer.OnDeviceCloudPolicyManagerConnected();
274 }
275 
NotifyDisconnected()276 void DeviceCloudPolicyManagerChromeOS::NotifyDisconnected() {
277   for (auto& observer : observers_)
278     observer.OnDeviceCloudPolicyManagerDisconnected();
279 }
280 
CreateStatusUploader()281 void DeviceCloudPolicyManagerChromeOS::CreateStatusUploader() {
282   status_uploader_.reset(new StatusUploader(
283       client(),
284       std::make_unique<DeviceStatusCollector>(
285           local_state_, chromeos::system::StatisticsProvider::GetInstance()),
286       task_runner_, kDeviceStatusUploadFrequency));
287 }
288 
289 }  // namespace policy
290