• 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 <memory>
8 
9 #include <base/containers/adapters.h>
10 #include <base/files/file_util.h>
11 #include <base/logging.h>
12 #include <base/macros.h>
13 #include <base/memory/ptr_util.h>
14 #include <openssl/evp.h>
15 #include <openssl/x509.h>
16 
17 #include <set>
18 #include <string>
19 
20 #include "bindings/chrome_device_policy.pb.h"
21 #include "bindings/device_management_backend.pb.h"
22 #include "policy/policy_util.h"
23 #include "policy/resilient_policy_util.h"
24 
25 namespace policy {
26 
27 namespace {
28 const char kPolicyPath[] = "/var/lib/whitelist/policy";
29 const char kPublicKeyPath[] = "/var/lib/whitelist/owner.key";
30 
31 // Reads the public key used to sign the policy from |key_file| and stores it
32 // in |public_key|. Returns true on success.
ReadPublicKeyFromFile(const base::FilePath & key_file,std::string * public_key)33 bool ReadPublicKeyFromFile(const base::FilePath& key_file,
34                            std::string* public_key) {
35   if (!base::PathExists(key_file))
36     return false;
37   public_key->clear();
38   if (!base::ReadFileToString(key_file, public_key) || public_key->empty()) {
39     LOG(ERROR) << "Could not read public key off disk";
40     return false;
41   }
42   return true;
43 }
44 
45 // 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)46 bool VerifySignature(const std::string& signed_data,
47                      const std::string& signature,
48                      const std::string& public_key) {
49   EVP_MD_CTX ctx;
50   EVP_MD_CTX_init(&ctx);
51 
52   const EVP_MD* digest = EVP_sha1();
53 
54   char* key = const_cast<char*>(public_key.data());
55   BIO* bio = BIO_new_mem_buf(key, public_key.length());
56   if (!bio) {
57     EVP_MD_CTX_cleanup(&ctx);
58     return false;
59   }
60 
61   EVP_PKEY* public_key_ssl = d2i_PUBKEY_bio(bio, nullptr);
62   if (!public_key_ssl) {
63     BIO_free_all(bio);
64     EVP_MD_CTX_cleanup(&ctx);
65     return false;
66   }
67 
68   const unsigned char* sig =
69       reinterpret_cast<const unsigned char*>(signature.data());
70   int rv = EVP_VerifyInit_ex(&ctx, digest, nullptr);
71   if (rv == 1) {
72     EVP_VerifyUpdate(&ctx, signed_data.data(), signed_data.length());
73     rv = EVP_VerifyFinal(&ctx, sig, signature.length(), public_key_ssl);
74   }
75 
76   EVP_PKEY_free(public_key_ssl);
77   BIO_free_all(bio);
78   EVP_MD_CTX_cleanup(&ctx);
79 
80   return rv == 1;
81 }
82 
83 // Decodes the connection type enum from the device settings protobuf to string
84 // representations. The strings must match the connection manager definitions.
DecodeConnectionType(int type)85 std::string DecodeConnectionType(int type) {
86   static const char* const kConnectionTypes[] = {
87       "ethernet", "wifi", "wimax", "bluetooth", "cellular",
88   };
89 
90   if (type < 0 || type >= static_cast<int>(arraysize(kConnectionTypes)))
91     return std::string();
92 
93   return kConnectionTypes[type];
94 }
95 
96 }  // namespace
97 
DevicePolicyImpl()98 DevicePolicyImpl::DevicePolicyImpl()
99     : policy_path_(kPolicyPath),
100       keyfile_path_(kPublicKeyPath),
101       verify_root_ownership_(true) {}
102 
~DevicePolicyImpl()103 DevicePolicyImpl::~DevicePolicyImpl() {}
104 
LoadPolicy()105 bool DevicePolicyImpl::LoadPolicy() {
106   std::map<int, base::FilePath> sorted_policy_file_paths =
107       policy::GetSortedResilientPolicyFilePaths(policy_path_);
108   if (sorted_policy_file_paths.empty())
109     return false;
110 
111   // Try to load the existent policy files one by one in reverse order of their
112   // index until we succeed. The default policy, if present, appears as index 0
113   // in the map and is loaded the last. This is intentional as that file is the
114   // oldest.
115   bool policy_loaded = false;
116   for (const auto& map_pair : base::Reversed(sorted_policy_file_paths)) {
117     const base::FilePath& policy_path = map_pair.second;
118     if (LoadPolicyFromFile(policy_path)) {
119       policy_loaded = true;
120       break;
121     }
122   }
123 
124   return policy_loaded;
125 }
126 
GetPolicyRefreshRate(int * rate) const127 bool DevicePolicyImpl::GetPolicyRefreshRate(int* rate) const {
128   if (!device_policy_.has_device_policy_refresh_rate())
129     return false;
130   *rate = static_cast<int>(
131       device_policy_.device_policy_refresh_rate().device_policy_refresh_rate());
132   return true;
133 }
134 
GetUserWhitelist(std::vector<std::string> * user_whitelist) const135 bool DevicePolicyImpl::GetUserWhitelist(
136     std::vector<std::string>* user_whitelist) const {
137   if (!device_policy_.has_user_whitelist())
138     return false;
139   const enterprise_management::UserWhitelistProto& proto =
140       device_policy_.user_whitelist();
141   user_whitelist->clear();
142   for (int i = 0; i < proto.user_whitelist_size(); i++)
143     user_whitelist->push_back(proto.user_whitelist(i));
144   return true;
145 }
146 
GetGuestModeEnabled(bool * guest_mode_enabled) const147 bool DevicePolicyImpl::GetGuestModeEnabled(bool* guest_mode_enabled) const {
148   if (!device_policy_.has_guest_mode_enabled())
149     return false;
150   *guest_mode_enabled =
151       device_policy_.guest_mode_enabled().guest_mode_enabled();
152   return true;
153 }
154 
GetCameraEnabled(bool * camera_enabled) const155 bool DevicePolicyImpl::GetCameraEnabled(bool* camera_enabled) const {
156   if (!device_policy_.has_camera_enabled())
157     return false;
158   *camera_enabled = device_policy_.camera_enabled().camera_enabled();
159   return true;
160 }
161 
GetShowUserNames(bool * show_user_names) const162 bool DevicePolicyImpl::GetShowUserNames(bool* show_user_names) const {
163   if (!device_policy_.has_show_user_names())
164     return false;
165   *show_user_names = device_policy_.show_user_names().show_user_names();
166   return true;
167 }
168 
GetDataRoamingEnabled(bool * data_roaming_enabled) const169 bool DevicePolicyImpl::GetDataRoamingEnabled(bool* data_roaming_enabled) const {
170   if (!device_policy_.has_data_roaming_enabled())
171     return false;
172   *data_roaming_enabled =
173       device_policy_.data_roaming_enabled().data_roaming_enabled();
174   return true;
175 }
176 
GetAllowNewUsers(bool * allow_new_users) const177 bool DevicePolicyImpl::GetAllowNewUsers(bool* allow_new_users) const {
178   if (!device_policy_.has_allow_new_users())
179     return false;
180   *allow_new_users = device_policy_.allow_new_users().allow_new_users();
181   return true;
182 }
183 
GetMetricsEnabled(bool * metrics_enabled) const184 bool DevicePolicyImpl::GetMetricsEnabled(bool* metrics_enabled) const {
185   if (!device_policy_.has_metrics_enabled())
186     return false;
187   *metrics_enabled = device_policy_.metrics_enabled().metrics_enabled();
188   return true;
189 }
190 
GetReportVersionInfo(bool * report_version_info) const191 bool DevicePolicyImpl::GetReportVersionInfo(bool* report_version_info) const {
192   if (!device_policy_.has_device_reporting())
193     return false;
194 
195   const enterprise_management::DeviceReportingProto& proto =
196       device_policy_.device_reporting();
197   if (!proto.has_report_version_info())
198     return false;
199 
200   *report_version_info = proto.report_version_info();
201   return true;
202 }
203 
GetReportActivityTimes(bool * report_activity_times) const204 bool DevicePolicyImpl::GetReportActivityTimes(
205     bool* report_activity_times) const {
206   if (!device_policy_.has_device_reporting())
207     return false;
208 
209   const enterprise_management::DeviceReportingProto& proto =
210       device_policy_.device_reporting();
211   if (!proto.has_report_activity_times())
212     return false;
213 
214   *report_activity_times = proto.report_activity_times();
215   return true;
216 }
217 
GetReportBootMode(bool * report_boot_mode) const218 bool DevicePolicyImpl::GetReportBootMode(bool* report_boot_mode) const {
219   if (!device_policy_.has_device_reporting())
220     return false;
221 
222   const enterprise_management::DeviceReportingProto& proto =
223       device_policy_.device_reporting();
224   if (!proto.has_report_boot_mode())
225     return false;
226 
227   *report_boot_mode = proto.report_boot_mode();
228   return true;
229 }
230 
GetEphemeralUsersEnabled(bool * ephemeral_users_enabled) const231 bool DevicePolicyImpl::GetEphemeralUsersEnabled(
232     bool* ephemeral_users_enabled) const {
233   if (!device_policy_.has_ephemeral_users_enabled())
234     return false;
235   *ephemeral_users_enabled =
236       device_policy_.ephemeral_users_enabled().ephemeral_users_enabled();
237   return true;
238 }
239 
GetReleaseChannel(std::string * release_channel) const240 bool DevicePolicyImpl::GetReleaseChannel(std::string* release_channel) const {
241   if (!device_policy_.has_release_channel())
242     return false;
243 
244   const enterprise_management::ReleaseChannelProto& proto =
245       device_policy_.release_channel();
246   if (!proto.has_release_channel())
247     return false;
248 
249   *release_channel = proto.release_channel();
250   return true;
251 }
252 
GetReleaseChannelDelegated(bool * release_channel_delegated) const253 bool DevicePolicyImpl::GetReleaseChannelDelegated(
254     bool* release_channel_delegated) const {
255   if (!device_policy_.has_release_channel())
256     return false;
257 
258   const enterprise_management::ReleaseChannelProto& proto =
259       device_policy_.release_channel();
260   if (!proto.has_release_channel_delegated())
261     return false;
262 
263   *release_channel_delegated = proto.release_channel_delegated();
264   return true;
265 }
266 
GetUpdateDisabled(bool * update_disabled) const267 bool DevicePolicyImpl::GetUpdateDisabled(bool* update_disabled) const {
268   if (!device_policy_.has_auto_update_settings())
269     return false;
270 
271   const enterprise_management::AutoUpdateSettingsProto& proto =
272       device_policy_.auto_update_settings();
273   if (!proto.has_update_disabled())
274     return false;
275 
276   *update_disabled = proto.update_disabled();
277   return true;
278 }
279 
GetTargetVersionPrefix(std::string * target_version_prefix) const280 bool DevicePolicyImpl::GetTargetVersionPrefix(
281     std::string* target_version_prefix) const {
282   if (!device_policy_.has_auto_update_settings())
283     return false;
284 
285   const enterprise_management::AutoUpdateSettingsProto& proto =
286       device_policy_.auto_update_settings();
287   if (!proto.has_target_version_prefix())
288     return false;
289 
290   *target_version_prefix = proto.target_version_prefix();
291   return true;
292 }
293 
GetScatterFactorInSeconds(int64_t * scatter_factor_in_seconds) const294 bool DevicePolicyImpl::GetScatterFactorInSeconds(
295     int64_t* scatter_factor_in_seconds) const {
296   if (!device_policy_.has_auto_update_settings())
297     return false;
298 
299   const enterprise_management::AutoUpdateSettingsProto& proto =
300       device_policy_.auto_update_settings();
301   if (!proto.has_scatter_factor_in_seconds())
302     return false;
303 
304   *scatter_factor_in_seconds = proto.scatter_factor_in_seconds();
305   return true;
306 }
307 
GetAllowedConnectionTypesForUpdate(std::set<std::string> * connection_types) const308 bool DevicePolicyImpl::GetAllowedConnectionTypesForUpdate(
309     std::set<std::string>* connection_types) const {
310   if (!device_policy_.has_auto_update_settings())
311     return false;
312 
313   const enterprise_management::AutoUpdateSettingsProto& proto =
314       device_policy_.auto_update_settings();
315   if (proto.allowed_connection_types_size() <= 0)
316     return false;
317 
318   for (int i = 0; i < proto.allowed_connection_types_size(); i++) {
319     std::string type = DecodeConnectionType(proto.allowed_connection_types(i));
320     if (!type.empty())
321       connection_types->insert(type);
322   }
323   return true;
324 }
325 
GetOpenNetworkConfiguration(std::string * open_network_configuration) const326 bool DevicePolicyImpl::GetOpenNetworkConfiguration(
327     std::string* open_network_configuration) const {
328   if (!device_policy_.has_open_network_configuration())
329     return false;
330 
331   const enterprise_management::DeviceOpenNetworkConfigurationProto& proto =
332       device_policy_.open_network_configuration();
333   if (!proto.has_open_network_configuration())
334     return false;
335 
336   *open_network_configuration = proto.open_network_configuration();
337   return true;
338 }
339 
GetOwner(std::string * owner) const340 bool DevicePolicyImpl::GetOwner(std::string* owner) const {
341   // The device is enterprise enrolled iff a request token exists.
342   if (policy_data_.has_request_token()) {
343     *owner = "";
344     return true;
345   }
346   if (!policy_data_.has_username())
347     return false;
348   *owner = policy_data_.username();
349   return true;
350 }
351 
GetHttpDownloadsEnabled(bool * http_downloads_enabled) const352 bool DevicePolicyImpl::GetHttpDownloadsEnabled(
353     bool* http_downloads_enabled) const {
354   if (!device_policy_.has_auto_update_settings())
355     return false;
356 
357   const enterprise_management::AutoUpdateSettingsProto& proto =
358       device_policy_.auto_update_settings();
359 
360   if (!proto.has_http_downloads_enabled())
361     return false;
362 
363   *http_downloads_enabled = proto.http_downloads_enabled();
364   return true;
365 }
366 
GetAuP2PEnabled(bool * au_p2p_enabled) const367 bool DevicePolicyImpl::GetAuP2PEnabled(bool* au_p2p_enabled) const {
368   if (!device_policy_.has_auto_update_settings())
369     return false;
370 
371   const enterprise_management::AutoUpdateSettingsProto& proto =
372       device_policy_.auto_update_settings();
373 
374   if (!proto.has_p2p_enabled())
375     return false;
376 
377   *au_p2p_enabled = proto.p2p_enabled();
378   return true;
379 }
380 
GetAllowKioskAppControlChromeVersion(bool * allow_kiosk_app_control_chrome_version) const381 bool DevicePolicyImpl::GetAllowKioskAppControlChromeVersion(
382     bool* allow_kiosk_app_control_chrome_version) const {
383   if (!device_policy_.has_allow_kiosk_app_control_chrome_version())
384     return false;
385 
386   const enterprise_management::AllowKioskAppControlChromeVersionProto& proto =
387       device_policy_.allow_kiosk_app_control_chrome_version();
388 
389   if (!proto.has_allow_kiosk_app_control_chrome_version())
390     return false;
391 
392   *allow_kiosk_app_control_chrome_version =
393       proto.allow_kiosk_app_control_chrome_version();
394   return true;
395 }
396 
GetUsbDetachableWhitelist(std::vector<UsbDeviceId> * usb_whitelist) const397 bool DevicePolicyImpl::GetUsbDetachableWhitelist(
398     std::vector<UsbDeviceId>* usb_whitelist) const {
399   if (!device_policy_.has_usb_detachable_whitelist())
400     return false;
401   const enterprise_management::UsbDetachableWhitelistProto& proto =
402       device_policy_.usb_detachable_whitelist();
403   usb_whitelist->clear();
404   for (int i = 0; i < proto.id_size(); i++) {
405     const ::enterprise_management::UsbDeviceIdProto& id = proto.id(i);
406     UsbDeviceId dev_id;
407     dev_id.vendor_id = id.has_vendor_id() ? id.vendor_id() : 0;
408     dev_id.product_id = id.has_product_id() ? id.product_id() : 0;
409     usb_whitelist->push_back(dev_id);
410   }
411   return true;
412 }
413 
GetAutoLaunchedKioskAppId(std::string * app_id_out) const414 bool DevicePolicyImpl::GetAutoLaunchedKioskAppId(
415     std::string* app_id_out) const {
416   if (!device_policy_.has_device_local_accounts())
417     return false;
418 
419   const enterprise_management::DeviceLocalAccountsProto& local_accounts =
420       device_policy_.device_local_accounts();
421 
422   // For auto-launched kiosk apps, the delay needs to be 0.
423   if (local_accounts.has_auto_login_delay() &&
424       local_accounts.auto_login_delay() != 0)
425     return false;
426 
427   for (const enterprise_management::DeviceLocalAccountInfoProto& account :
428        local_accounts.account()) {
429     // If this isn't an auto-login account, move to the next one.
430     if (account.account_id() != local_accounts.auto_login_id())
431       continue;
432 
433     // If the auto-launched account is not a kiosk app, bail out, we aren't
434     // running in auto-launched kiosk mode.
435     if (account.type() !=
436             enterprise_management::DeviceLocalAccountInfoProto::
437                 ACCOUNT_TYPE_KIOSK_APP) {
438       return false;
439     }
440 
441     *app_id_out = account.kiosk_app().app_id();
442     return true;
443   }
444 
445   // No auto-launched account found.
446   return false;
447 }
448 
VerifyPolicyFile(const base::FilePath & policy_path)449 bool DevicePolicyImpl::VerifyPolicyFile(const base::FilePath& policy_path) {
450   if (!verify_root_ownership_) {
451     return true;
452   }
453 
454   // Both the policy and its signature have to exist.
455   if (!base::PathExists(policy_path) || !base::PathExists(keyfile_path_)) {
456     return false;
457   }
458 
459   // Check if the policy and signature file is owned by root.
460   struct stat file_stat;
461   stat(policy_path.value().c_str(), &file_stat);
462   if (file_stat.st_uid != 0) {
463     LOG(ERROR) << "Policy file is not owned by root!";
464     return false;
465   }
466   stat(keyfile_path_.value().c_str(), &file_stat);
467   if (file_stat.st_uid != 0) {
468     LOG(ERROR) << "Policy signature file is not owned by root!";
469     return false;
470   }
471   return true;
472 }
473 
VerifyPolicySignature()474 bool DevicePolicyImpl::VerifyPolicySignature() {
475   if (policy_.has_policy_data_signature()) {
476     std::string policy_data = policy_.policy_data();
477     std::string policy_data_signature = policy_.policy_data_signature();
478     std::string public_key;
479     if (!ReadPublicKeyFromFile(base::FilePath(keyfile_path_), &public_key)) {
480       LOG(ERROR) << "Could not read owner key off disk";
481       return false;
482     }
483     if (!VerifySignature(policy_data, policy_data_signature, public_key)) {
484       LOG(ERROR) << "Signature does not match the data or can not be verified!";
485       return false;
486     }
487     return true;
488   }
489   LOG(ERROR) << "The policy blob is not signed!";
490   return false;
491 }
492 
LoadPolicyFromFile(const base::FilePath & policy_path)493 bool DevicePolicyImpl::LoadPolicyFromFile(const base::FilePath& policy_path) {
494   std::string policy_data_str;
495   if (policy::LoadPolicyFromPath(policy_path, &policy_data_str, &policy_) !=
496       LoadPolicyResult::kSuccess) {
497     return false;
498   }
499   if (!policy_.has_policy_data()) {
500     LOG(ERROR) << "Policy on disk could not be parsed!";
501     return false;
502   }
503   if (!policy_data_.ParseFromString(policy_.policy_data()) ||
504       !policy_data_.has_policy_value()) {
505     LOG(ERROR) << "Policy on disk could not be parsed!";
506     return false;
507   }
508 
509   bool verify_policy = true;
510   if (!install_attributes_reader_) {
511     install_attributes_reader_ = std::make_unique<InstallAttributesReader>();
512   }
513   const std::string& mode = install_attributes_reader_->GetAttribute(
514       InstallAttributesReader::kAttrMode);
515   if (mode == InstallAttributesReader::kDeviceModeEnterpriseAD) {
516     verify_policy = false;
517   }
518   if (verify_policy && !VerifyPolicyFile(policy_path)) {
519     return false;
520   }
521 
522   // Make sure the signature is still valid.
523   if (verify_policy && !VerifyPolicySignature()) {
524     LOG(ERROR) << "Policy signature verification failed!";
525     return false;
526   }
527   if (!device_policy_.ParseFromString(policy_data_.policy_value())) {
528     LOG(ERROR) << "Policy on disk could not be parsed!";
529     return false;
530   }
531 
532   return true;
533 }
534 
535 }  // namespace policy
536