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