• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium OS 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 "policy/device_policy_impl.h"
6 
7 #include <algorithm>
8 #include <map>
9 #include <memory>
10 #include <set>
11 #include <string>
12 
13 #include <base/containers/adapters.h>
14 #include <base/files/file_util.h>
15 #include <base/json/json_reader.h>
16 #include <base/logging.h>
17 #include <base/macros.h>
18 #include <base/memory/ptr_util.h>
19 #include <base/stl_util.h>
20 #include <base/time/time.h>
21 #include <base/values.h>
22 #include <openssl/evp.h>
23 #include <openssl/x509.h>
24 
25 #include "bindings/chrome_device_policy.pb.h"
26 #include "bindings/device_management_backend.pb.h"
27 #include "policy/policy_util.h"
28 #include "policy/resilient_policy_util.h"
29 
30 namespace em = enterprise_management;
31 
32 namespace policy {
33 
34 // TODO(crbug.com/984789): Remove once support for OpenSSL <1.1 is dropped.
35 #if OPENSSL_VERSION_NUMBER < 0x10100000L
36 #define EVP_MD_CTX_new EVP_MD_CTX_create
37 #define EVP_MD_CTX_free EVP_MD_CTX_destroy
38 #endif
39 
40 // Maximum value of RollbackAllowedMilestones policy.
41 const int kMaxRollbackAllowedMilestones = 4;
42 
43 namespace {
44 const char kPolicyPath[] = "/var/lib/whitelist/policy";
45 const char kPublicKeyPath[] = "/var/lib/whitelist/owner.key";
46 
47 // Reads the public key used to sign the policy from |key_file| and stores it
48 // in |public_key|. Returns true on success.
ReadPublicKeyFromFile(const base::FilePath & key_file,std::string * public_key)49 bool ReadPublicKeyFromFile(const base::FilePath& key_file,
50                            std::string* public_key) {
51   if (!base::PathExists(key_file))
52     return false;
53   public_key->clear();
54   if (!base::ReadFileToString(key_file, public_key) || public_key->empty()) {
55     LOG(ERROR) << "Could not read public key off disk";
56     return false;
57   }
58   return true;
59 }
60 
61 // Verifies that the |signed_data| has correct |signature| with |public_key|.
VerifySignature(const std::string & signed_data,const std::string & signature,const std::string & public_key)62 bool VerifySignature(const std::string& signed_data,
63                      const std::string& signature,
64                      const std::string& public_key) {
65   std::unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX *)> ctx(EVP_MD_CTX_new(),
66                                                           EVP_MD_CTX_free);
67   if (!ctx)
68     return false;
69 
70   const EVP_MD* digest = EVP_sha1();
71 
72   char* key = const_cast<char*>(public_key.data());
73   BIO* bio = BIO_new_mem_buf(key, public_key.length());
74   if (!bio)
75     return false;
76 
77   EVP_PKEY* public_key_ssl = d2i_PUBKEY_bio(bio, nullptr);
78   if (!public_key_ssl) {
79     BIO_free_all(bio);
80     return false;
81   }
82 
83   const unsigned char* sig =
84       reinterpret_cast<const unsigned char*>(signature.data());
85   int rv = EVP_VerifyInit_ex(ctx.get(), digest, nullptr);
86   if (rv == 1) {
87     EVP_VerifyUpdate(ctx.get(), signed_data.data(), signed_data.length());
88     rv = EVP_VerifyFinal(ctx.get(), sig, signature.length(), public_key_ssl);
89   }
90 
91   EVP_PKEY_free(public_key_ssl);
92   BIO_free_all(bio);
93 
94   return rv == 1;
95 }
96 
97 // Decodes the connection type enum from the device settings protobuf to string
98 // representations. The strings must match the connection manager definitions.
DecodeConnectionType(int type)99 std::string DecodeConnectionType(int type) {
100   static const char* const kConnectionTypes[] = {
101       "ethernet", "wifi", "wimax", "bluetooth", "cellular",
102   };
103 
104   if (type < 0 || type >= static_cast<int>(base::size(kConnectionTypes)))
105     return std::string();
106 
107   return kConnectionTypes[type];
108 }
109 
110 // TODO(adokar): change type to base::Optional<int> when available.
ConvertDayOfWeekStringToInt(const std::string & day_of_week_str)111 int ConvertDayOfWeekStringToInt(const std::string& day_of_week_str) {
112   if (day_of_week_str == "Sunday") return 0;
113   if (day_of_week_str == "Monday") return 1;
114   if (day_of_week_str == "Tuesday") return 2;
115   if (day_of_week_str == "Wednesday") return 3;
116   if (day_of_week_str == "Thursday") return 4;
117   if (day_of_week_str == "Friday") return 5;
118   if (day_of_week_str == "Saturday") return 6;
119   return -1;
120 }
121 
DecodeWeeklyTimeFromValue(const base::DictionaryValue & dict_value,int * day_of_week_out,base::TimeDelta * time_out)122 bool DecodeWeeklyTimeFromValue(const base::DictionaryValue& dict_value,
123                                int* day_of_week_out,
124                                base::TimeDelta* time_out) {
125   std::string day_of_week_str;
126   if (!dict_value.GetString("day_of_week", &day_of_week_str)) {
127     LOG(ERROR) << "Day of the week is absent.";
128     return false;
129   }
130   *day_of_week_out = ConvertDayOfWeekStringToInt(day_of_week_str);
131   if (*day_of_week_out == -1) {
132     LOG(ERROR) << "Undefined day of the week: " << day_of_week_str;
133     return false;
134   }
135 
136   int hours;
137   if (!dict_value.GetInteger("hours", &hours) || hours < 0 || hours > 23) {
138     LOG(ERROR) << "Hours are absent or are outside of the range [0, 24).";
139     return false;
140   }
141 
142   int minutes;
143   if (!dict_value.GetInteger("minutes", &minutes) || minutes < 0 ||
144       minutes > 59) {
145     LOG(ERROR) << "Minutes are absent or are outside the range [0, 60)";
146     return false;
147   }
148 
149   *time_out =
150       base::TimeDelta::FromMinutes(minutes) + base::TimeDelta::FromHours(hours);
151   return true;
152 }
153 
DecodeListValueFromJSON(const std::string & json_string)154 std::unique_ptr<base::ListValue> DecodeListValueFromJSON(
155     const std::string& json_string) {
156   std::string error;
157   std::unique_ptr<base::Value> decoded_json =
158       base::JSONReader::ReadAndReturnError(json_string,
159                                            base::JSON_ALLOW_TRAILING_COMMAS,
160                                            nullptr, &error);
161   if (!decoded_json) {
162     LOG(ERROR) << "Invalid JSON string: " << error;
163     return nullptr;
164   }
165 
166   std::unique_ptr<base::ListValue> list_val =
167       base::ListValue::From(std::move(decoded_json));
168   if (!list_val) {
169     LOG(ERROR) << "JSON string is not a list";
170     return nullptr;
171   }
172 
173   return list_val;
174 }
175 
176 }  // namespace
177 
DevicePolicyImpl()178 DevicePolicyImpl::DevicePolicyImpl()
179     : policy_path_(kPolicyPath), keyfile_path_(kPublicKeyPath) {}
180 
~DevicePolicyImpl()181 DevicePolicyImpl::~DevicePolicyImpl() {}
182 
LoadPolicy()183 bool DevicePolicyImpl::LoadPolicy() {
184   std::map<int, base::FilePath> sorted_policy_file_paths =
185       policy::GetSortedResilientPolicyFilePaths(policy_path_);
186   if (sorted_policy_file_paths.empty())
187     return false;
188 
189   // Try to load the existent policy files one by one in reverse order of their
190   // index until we succeed. The default policy, if present, appears as index 0
191   // in the map and is loaded the last. This is intentional as that file is the
192   // oldest.
193   bool policy_loaded = false;
194   for (const auto& map_pair : base::Reversed(sorted_policy_file_paths)) {
195     const base::FilePath& policy_path = map_pair.second;
196     if (LoadPolicyFromFile(policy_path)) {
197       policy_loaded = true;
198       break;
199     }
200   }
201 
202   return policy_loaded;
203 }
204 
IsEnterpriseEnrolled() const205 bool DevicePolicyImpl::IsEnterpriseEnrolled() const {
206   DCHECK(install_attributes_reader_);
207   if (!install_attributes_reader_->IsLocked())
208     return false;
209 
210   const std::string& device_mode = install_attributes_reader_->GetAttribute(
211       InstallAttributesReader::kAttrMode);
212   return device_mode == InstallAttributesReader::kDeviceModeEnterprise ||
213       device_mode == InstallAttributesReader::kDeviceModeEnterpriseAD;
214 }
215 
GetPolicyRefreshRate(int * rate) const216 bool DevicePolicyImpl::GetPolicyRefreshRate(int* rate) const {
217   if (!device_policy_.has_device_policy_refresh_rate())
218     return false;
219   *rate = static_cast<int>(
220       device_policy_.device_policy_refresh_rate().device_policy_refresh_rate());
221   return true;
222 }
223 
GetUserWhitelist(std::vector<std::string> * user_whitelist) const224 bool DevicePolicyImpl::GetUserWhitelist(
225     std::vector<std::string>* user_whitelist) const {
226   if (!device_policy_.has_user_whitelist())
227     return false;
228   const em::UserWhitelistProto& proto = device_policy_.user_whitelist();
229   user_whitelist->clear();
230   for (int i = 0; i < proto.user_whitelist_size(); i++)
231     user_whitelist->push_back(proto.user_whitelist(i));
232   return true;
233 }
234 
GetGuestModeEnabled(bool * guest_mode_enabled) const235 bool DevicePolicyImpl::GetGuestModeEnabled(bool* guest_mode_enabled) const {
236   if (!device_policy_.has_guest_mode_enabled())
237     return false;
238   *guest_mode_enabled =
239       device_policy_.guest_mode_enabled().guest_mode_enabled();
240   return true;
241 }
242 
GetCameraEnabled(bool * camera_enabled) const243 bool DevicePolicyImpl::GetCameraEnabled(bool* camera_enabled) const {
244   if (!device_policy_.has_camera_enabled())
245     return false;
246   *camera_enabled = device_policy_.camera_enabled().camera_enabled();
247   return true;
248 }
249 
GetShowUserNames(bool * show_user_names) const250 bool DevicePolicyImpl::GetShowUserNames(bool* show_user_names) const {
251   if (!device_policy_.has_show_user_names())
252     return false;
253   *show_user_names = device_policy_.show_user_names().show_user_names();
254   return true;
255 }
256 
GetDataRoamingEnabled(bool * data_roaming_enabled) const257 bool DevicePolicyImpl::GetDataRoamingEnabled(bool* data_roaming_enabled) const {
258   if (!device_policy_.has_data_roaming_enabled())
259     return false;
260   *data_roaming_enabled =
261       device_policy_.data_roaming_enabled().data_roaming_enabled();
262   return true;
263 }
264 
GetAllowNewUsers(bool * allow_new_users) const265 bool DevicePolicyImpl::GetAllowNewUsers(bool* allow_new_users) const {
266   if (!device_policy_.has_allow_new_users())
267     return false;
268   *allow_new_users = device_policy_.allow_new_users().allow_new_users();
269   return true;
270 }
271 
GetMetricsEnabled(bool * metrics_enabled) const272 bool DevicePolicyImpl::GetMetricsEnabled(bool* metrics_enabled) const {
273   if (!device_policy_.has_metrics_enabled())
274     return false;
275   *metrics_enabled = device_policy_.metrics_enabled().metrics_enabled();
276   return true;
277 }
278 
GetReportVersionInfo(bool * report_version_info) const279 bool DevicePolicyImpl::GetReportVersionInfo(bool* report_version_info) const {
280   if (!device_policy_.has_device_reporting())
281     return false;
282 
283   const em::DeviceReportingProto& proto = device_policy_.device_reporting();
284   if (!proto.has_report_version_info())
285     return false;
286 
287   *report_version_info = proto.report_version_info();
288   return true;
289 }
290 
GetReportActivityTimes(bool * report_activity_times) const291 bool DevicePolicyImpl::GetReportActivityTimes(
292     bool* report_activity_times) const {
293   if (!device_policy_.has_device_reporting())
294     return false;
295 
296   const em::DeviceReportingProto& proto = device_policy_.device_reporting();
297   if (!proto.has_report_activity_times())
298     return false;
299 
300   *report_activity_times = proto.report_activity_times();
301   return true;
302 }
303 
GetReportBootMode(bool * report_boot_mode) const304 bool DevicePolicyImpl::GetReportBootMode(bool* report_boot_mode) const {
305   if (!device_policy_.has_device_reporting())
306     return false;
307 
308   const em::DeviceReportingProto& proto = device_policy_.device_reporting();
309   if (!proto.has_report_boot_mode())
310     return false;
311 
312   *report_boot_mode = proto.report_boot_mode();
313   return true;
314 }
315 
GetEphemeralUsersEnabled(bool * ephemeral_users_enabled) const316 bool DevicePolicyImpl::GetEphemeralUsersEnabled(
317     bool* ephemeral_users_enabled) const {
318   if (!device_policy_.has_ephemeral_users_enabled())
319     return false;
320   *ephemeral_users_enabled =
321       device_policy_.ephemeral_users_enabled().ephemeral_users_enabled();
322   return true;
323 }
324 
GetReleaseChannel(std::string * release_channel) const325 bool DevicePolicyImpl::GetReleaseChannel(std::string* release_channel) const {
326   if (!device_policy_.has_release_channel())
327     return false;
328 
329   const em::ReleaseChannelProto& proto = device_policy_.release_channel();
330   if (!proto.has_release_channel())
331     return false;
332 
333   *release_channel = proto.release_channel();
334   return true;
335 }
336 
GetReleaseChannelDelegated(bool * release_channel_delegated) const337 bool DevicePolicyImpl::GetReleaseChannelDelegated(
338     bool* release_channel_delegated) const {
339   if (!device_policy_.has_release_channel())
340     return false;
341 
342   const em::ReleaseChannelProto& proto = device_policy_.release_channel();
343   if (!proto.has_release_channel_delegated())
344     return false;
345 
346   *release_channel_delegated = proto.release_channel_delegated();
347   return true;
348 }
349 
GetUpdateDisabled(bool * update_disabled) const350 bool DevicePolicyImpl::GetUpdateDisabled(bool* update_disabled) const {
351   if (!IsEnterpriseEnrolled())
352     return false;
353 
354   if (!device_policy_.has_auto_update_settings())
355     return false;
356 
357   const em::AutoUpdateSettingsProto& proto =
358       device_policy_.auto_update_settings();
359   if (!proto.has_update_disabled())
360     return false;
361 
362   *update_disabled = proto.update_disabled();
363   return true;
364 }
365 
GetTargetVersionPrefix(std::string * target_version_prefix) const366 bool DevicePolicyImpl::GetTargetVersionPrefix(
367     std::string* target_version_prefix) const {
368   if (!IsEnterpriseEnrolled())
369     return false;
370 
371   if (!device_policy_.has_auto_update_settings())
372     return false;
373 
374   const em::AutoUpdateSettingsProto& proto =
375       device_policy_.auto_update_settings();
376   if (!proto.has_target_version_prefix())
377     return false;
378 
379   *target_version_prefix = proto.target_version_prefix();
380   return true;
381 }
382 
GetRollbackToTargetVersion(int * rollback_to_target_version) const383 bool DevicePolicyImpl::GetRollbackToTargetVersion(
384     int* rollback_to_target_version) const {
385   if (!device_policy_.has_auto_update_settings())
386     return false;
387 
388   const em::AutoUpdateSettingsProto& proto =
389       device_policy_.auto_update_settings();
390   if (!proto.has_rollback_to_target_version())
391     return false;
392 
393   *rollback_to_target_version = proto.rollback_to_target_version();
394   return true;
395 }
396 
GetRollbackAllowedMilestones(int * rollback_allowed_milestones) const397 bool DevicePolicyImpl::GetRollbackAllowedMilestones(
398     int* rollback_allowed_milestones) const {
399   // This policy can be only set for devices which are enterprise enrolled.
400   if (!IsEnterpriseEnrolled())
401     return false;
402 
403   if (device_policy_.has_auto_update_settings()) {
404     const em::AutoUpdateSettingsProto& proto =
405         device_policy_.auto_update_settings();
406     if (proto.has_rollback_allowed_milestones()) {
407       // Policy is set, enforce minimum and maximum constraints.
408       *rollback_allowed_milestones = proto.rollback_allowed_milestones();
409       if (*rollback_allowed_milestones < 0)
410         *rollback_allowed_milestones = 0;
411       if (*rollback_allowed_milestones > kMaxRollbackAllowedMilestones)
412         *rollback_allowed_milestones = kMaxRollbackAllowedMilestones;
413       return true;
414     }
415   }
416   // Policy is not present, use default for enterprise devices.
417   VLOG(1) << "RollbackAllowedMilestones policy is not set, using default "
418           << kMaxRollbackAllowedMilestones << ".";
419   *rollback_allowed_milestones = kMaxRollbackAllowedMilestones;
420   return true;
421 }
422 
GetScatterFactorInSeconds(int64_t * scatter_factor_in_seconds) const423 bool DevicePolicyImpl::GetScatterFactorInSeconds(
424     int64_t* scatter_factor_in_seconds) const {
425   if (!device_policy_.has_auto_update_settings())
426     return false;
427 
428   const em::AutoUpdateSettingsProto& proto =
429       device_policy_.auto_update_settings();
430   if (!proto.has_scatter_factor_in_seconds())
431     return false;
432 
433   *scatter_factor_in_seconds = proto.scatter_factor_in_seconds();
434   return true;
435 }
436 
GetAllowedConnectionTypesForUpdate(std::set<std::string> * connection_types) const437 bool DevicePolicyImpl::GetAllowedConnectionTypesForUpdate(
438     std::set<std::string>* connection_types) const {
439   if (!IsEnterpriseEnrolled())
440     return false;
441 
442   if (!device_policy_.has_auto_update_settings())
443     return false;
444 
445   const em::AutoUpdateSettingsProto& proto =
446       device_policy_.auto_update_settings();
447   if (proto.allowed_connection_types_size() <= 0)
448     return false;
449 
450   for (int i = 0; i < proto.allowed_connection_types_size(); i++) {
451     std::string type = DecodeConnectionType(proto.allowed_connection_types(i));
452     if (!type.empty())
453       connection_types->insert(type);
454   }
455   return true;
456 }
457 
GetOpenNetworkConfiguration(std::string * open_network_configuration) const458 bool DevicePolicyImpl::GetOpenNetworkConfiguration(
459     std::string* open_network_configuration) const {
460   if (!device_policy_.has_open_network_configuration())
461     return false;
462 
463   const em::DeviceOpenNetworkConfigurationProto& proto =
464       device_policy_.open_network_configuration();
465   if (!proto.has_open_network_configuration())
466     return false;
467 
468   *open_network_configuration = proto.open_network_configuration();
469   return true;
470 }
471 
GetOwner(std::string * owner) const472 bool DevicePolicyImpl::GetOwner(std::string* owner) const {
473   if (IsEnterpriseManaged()) {
474     *owner = "";
475     return true;
476   }
477 
478   if (!policy_data_.has_username())
479     return false;
480   *owner = policy_data_.username();
481   return true;
482 }
483 
GetHttpDownloadsEnabled(bool * http_downloads_enabled) const484 bool DevicePolicyImpl::GetHttpDownloadsEnabled(
485     bool* http_downloads_enabled) const {
486   if (!device_policy_.has_auto_update_settings())
487     return false;
488 
489   const em::AutoUpdateSettingsProto& proto =
490       device_policy_.auto_update_settings();
491 
492   if (!proto.has_http_downloads_enabled())
493     return false;
494 
495   *http_downloads_enabled = proto.http_downloads_enabled();
496   return true;
497 }
498 
GetAuP2PEnabled(bool * au_p2p_enabled) const499 bool DevicePolicyImpl::GetAuP2PEnabled(bool* au_p2p_enabled) const {
500   if (!device_policy_.has_auto_update_settings())
501     return false;
502 
503   const em::AutoUpdateSettingsProto& proto =
504       device_policy_.auto_update_settings();
505 
506   if (!proto.has_p2p_enabled())
507     return false;
508 
509   *au_p2p_enabled = proto.p2p_enabled();
510   return true;
511 }
512 
GetAllowKioskAppControlChromeVersion(bool * allow_kiosk_app_control_chrome_version) const513 bool DevicePolicyImpl::GetAllowKioskAppControlChromeVersion(
514     bool* allow_kiosk_app_control_chrome_version) const {
515   if (!device_policy_.has_allow_kiosk_app_control_chrome_version())
516     return false;
517 
518   const em::AllowKioskAppControlChromeVersionProto& proto =
519       device_policy_.allow_kiosk_app_control_chrome_version();
520 
521   if (!proto.has_allow_kiosk_app_control_chrome_version())
522     return false;
523 
524   *allow_kiosk_app_control_chrome_version =
525       proto.allow_kiosk_app_control_chrome_version();
526   return true;
527 }
528 
GetUsbDetachableWhitelist(std::vector<UsbDeviceId> * usb_whitelist) const529 bool DevicePolicyImpl::GetUsbDetachableWhitelist(
530     std::vector<UsbDeviceId>* usb_whitelist) const {
531   if (!device_policy_.has_usb_detachable_whitelist())
532     return false;
533   const em::UsbDetachableWhitelistProto& proto =
534       device_policy_.usb_detachable_whitelist();
535   usb_whitelist->clear();
536   for (int i = 0; i < proto.id_size(); i++) {
537     const em::UsbDeviceIdProto& id = proto.id(i);
538     UsbDeviceId dev_id;
539     dev_id.vendor_id = id.has_vendor_id() ? id.vendor_id() : 0;
540     dev_id.product_id = id.has_product_id() ? id.product_id() : 0;
541     usb_whitelist->push_back(dev_id);
542   }
543   return true;
544 }
545 
GetDeviceUpdateStagingSchedule(std::vector<DayPercentagePair> * staging_schedule_out) const546 bool DevicePolicyImpl::GetDeviceUpdateStagingSchedule(
547     std::vector<DayPercentagePair>* staging_schedule_out) const {
548   staging_schedule_out->clear();
549 
550   if (!device_policy_.has_auto_update_settings())
551     return false;
552 
553   const em::AutoUpdateSettingsProto &proto =
554       device_policy_.auto_update_settings();
555 
556   if (!proto.has_staging_schedule())
557     return false;
558 
559   std::unique_ptr<base::ListValue> list_val =
560       DecodeListValueFromJSON(proto.staging_schedule());
561   if (!list_val)
562     return false;
563 
564   for (const auto& pair_value : *list_val) {
565     const base::DictionaryValue* day_percentage_pair;
566     if (!pair_value.GetAsDictionary(&day_percentage_pair))
567       return false;
568     int days, percentage;
569     if (!day_percentage_pair->GetInteger("days", &days) ||
570         !day_percentage_pair->GetInteger("percentage", &percentage))
571       return false;
572     // Limit the percentage to [0, 100] and days to [1, 28];
573     staging_schedule_out->push_back({std::max(std::min(days, 28), 1),
574                                      std::max(std::min(percentage, 100), 0)});
575   }
576 
577   return true;
578 }
579 
GetAutoLaunchedKioskAppId(std::string * app_id_out) const580 bool DevicePolicyImpl::GetAutoLaunchedKioskAppId(
581     std::string* app_id_out) const {
582   if (!device_policy_.has_device_local_accounts())
583     return false;
584 
585   const em::DeviceLocalAccountsProto& local_accounts =
586       device_policy_.device_local_accounts();
587 
588   // For auto-launched kiosk apps, the delay needs to be 0.
589   if (local_accounts.has_auto_login_delay() &&
590       local_accounts.auto_login_delay() != 0)
591     return false;
592 
593   for (const em::DeviceLocalAccountInfoProto& account :
594        local_accounts.account()) {
595     // If this isn't an auto-login account, move to the next one.
596     if (account.account_id() != local_accounts.auto_login_id())
597       continue;
598 
599     // If the auto-launched account is not a kiosk app, bail out, we aren't
600     // running in auto-launched kiosk mode.
601     if (account.type() !=
602         em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_KIOSK_APP) {
603       return false;
604     }
605 
606     *app_id_out = account.kiosk_app().app_id();
607     return true;
608   }
609 
610   // No auto-launched account found.
611   return false;
612 }
613 
IsEnterpriseManaged() const614 bool DevicePolicyImpl::IsEnterpriseManaged() const {
615   if (policy_data_.has_management_mode())
616     return policy_data_.management_mode() == em::PolicyData::ENTERPRISE_MANAGED;
617   // Fall back to checking the request token, see management_mode documentation
618   // in device_management_backend.proto.
619   return policy_data_.has_request_token();
620 }
621 
GetSecondFactorAuthenticationMode(int * mode_out) const622 bool DevicePolicyImpl::GetSecondFactorAuthenticationMode(int* mode_out) const {
623   if (!device_policy_.has_device_second_factor_authentication())
624     return false;
625 
626   const em::DeviceSecondFactorAuthenticationProto& proto =
627       device_policy_.device_second_factor_authentication();
628 
629   if (!proto.has_mode())
630     return false;
631 
632   *mode_out = proto.mode();
633   return true;
634 }
635 
GetDisallowedTimeIntervals(std::vector<WeeklyTimeInterval> * intervals_out) const636 bool DevicePolicyImpl::GetDisallowedTimeIntervals(
637     std::vector<WeeklyTimeInterval>* intervals_out) const {
638   intervals_out->clear();
639   if (!IsEnterpriseEnrolled())
640     return false;
641 
642   if (!device_policy_.has_auto_update_settings()) {
643     return false;
644   }
645 
646   const em::AutoUpdateSettingsProto& proto =
647       device_policy_.auto_update_settings();
648 
649   if (!proto.has_disallowed_time_intervals()) {
650     return false;
651   }
652 
653   std::unique_ptr<base::ListValue> list_val =
654       DecodeListValueFromJSON(proto.disallowed_time_intervals());
655   if (!list_val)
656     return false;
657 
658   for (const auto& interval_value : *list_val) {
659     const base::DictionaryValue* interval_dict;
660     if (!interval_value.GetAsDictionary(&interval_dict)) {
661       LOG(ERROR) << "Invalid JSON string given. Interval is not a dict.";
662       return false;
663     }
664     const base::DictionaryValue* start;
665     const base::DictionaryValue* end;
666     if (!interval_dict->GetDictionary("start", &start) ||
667         !interval_dict->GetDictionary("end", &end)) {
668       LOG(ERROR) << "Interval is missing start/end.";
669       return false;
670     }
671     WeeklyTimeInterval weekly_interval;
672     if (!DecodeWeeklyTimeFromValue(*start, &weekly_interval.start_day_of_week,
673                                    &weekly_interval.start_time) ||
674         !DecodeWeeklyTimeFromValue(*end, &weekly_interval.end_day_of_week,
675                                    &weekly_interval.end_time)) {
676       return false;
677     }
678 
679     intervals_out->push_back(weekly_interval);
680   }
681   return true;
682 }
683 
GetDeviceQuickFixBuildToken(std::string * device_quick_fix_build_token) const684 bool DevicePolicyImpl::GetDeviceQuickFixBuildToken(
685     std::string* device_quick_fix_build_token) const {
686   if (!IsEnterpriseEnrolled() || !device_policy_.has_auto_update_settings())
687     return false;
688 
689   const em::AutoUpdateSettingsProto& proto =
690       device_policy_.auto_update_settings();
691   if (!proto.has_device_quick_fix_build_token())
692     return false;
693 
694   *device_quick_fix_build_token = proto.device_quick_fix_build_token();
695   return true;
696 }
697 
GetDeviceDirectoryApiId(std::string * directory_api_id_out) const698 bool DevicePolicyImpl::GetDeviceDirectoryApiId(
699     std::string* directory_api_id_out) const {
700   if (!policy_data_.has_directory_api_id())
701     return false;
702 
703   *directory_api_id_out = policy_data_.directory_api_id();
704   return true;
705 }
706 
VerifyPolicyFile(const base::FilePath & policy_path)707 bool DevicePolicyImpl::VerifyPolicyFile(const base::FilePath& policy_path) {
708   if (!verify_root_ownership_) {
709     return true;
710   }
711 
712   // Both the policy and its signature have to exist.
713   if (!base::PathExists(policy_path) || !base::PathExists(keyfile_path_)) {
714     return false;
715   }
716 
717   // Check if the policy and signature file is owned by root.
718   struct stat file_stat;
719   stat(policy_path.value().c_str(), &file_stat);
720   if (file_stat.st_uid != 0) {
721     LOG(ERROR) << "Policy file is not owned by root!";
722     return false;
723   }
724   stat(keyfile_path_.value().c_str(), &file_stat);
725   if (file_stat.st_uid != 0) {
726     LOG(ERROR) << "Policy signature file is not owned by root!";
727     return false;
728   }
729   return true;
730 }
731 
VerifyPolicySignature()732 bool DevicePolicyImpl::VerifyPolicySignature() {
733   if (policy_.has_policy_data_signature()) {
734     std::string policy_data = policy_.policy_data();
735     std::string policy_data_signature = policy_.policy_data_signature();
736     std::string public_key;
737     if (!ReadPublicKeyFromFile(base::FilePath(keyfile_path_), &public_key)) {
738       LOG(ERROR) << "Could not read owner key off disk";
739       return false;
740     }
741     if (!VerifySignature(policy_data, policy_data_signature, public_key)) {
742       LOG(ERROR) << "Signature does not match the data or can not be verified!";
743       return false;
744     }
745     return true;
746   }
747   LOG(ERROR) << "The policy blob is not signed!";
748   return false;
749 }
750 
LoadPolicyFromFile(const base::FilePath & policy_path)751 bool DevicePolicyImpl::LoadPolicyFromFile(const base::FilePath& policy_path) {
752   std::string policy_data_str;
753   if (policy::LoadPolicyFromPath(policy_path, &policy_data_str, &policy_) !=
754       LoadPolicyResult::kSuccess) {
755     return false;
756   }
757   if (!policy_.has_policy_data()) {
758     LOG(ERROR) << "Policy on disk could not be parsed!";
759     return false;
760   }
761   if (!policy_data_.ParseFromString(policy_.policy_data()) ||
762       !policy_data_.has_policy_value()) {
763     LOG(ERROR) << "Policy on disk could not be parsed!";
764     return false;
765   }
766 
767   bool verify_policy = verify_policy_;
768   if (!install_attributes_reader_) {
769     install_attributes_reader_ = std::make_unique<InstallAttributesReader>();
770   }
771   const std::string& mode = install_attributes_reader_->GetAttribute(
772       InstallAttributesReader::kAttrMode);
773   if (mode == InstallAttributesReader::kDeviceModeEnterpriseAD) {
774     verify_policy = false;
775   }
776   if (verify_policy && !VerifyPolicyFile(policy_path)) {
777     return false;
778   }
779 
780   // Make sure the signature is still valid.
781   if (verify_policy && !VerifyPolicySignature()) {
782     LOG(ERROR) << "Policy signature verification failed!";
783     return false;
784   }
785   if (!device_policy_.ParseFromString(policy_data_.policy_value())) {
786     LOG(ERROR) << "Policy on disk could not be parsed!";
787     return false;
788   }
789 
790   return true;
791 }
792 
793 }  // namespace policy
794