-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauthpolicy_test.cc
2888 lines (2525 loc) · 124 KB
/
authpolicy_test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "authpolicy/authpolicy.h"
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <base/bind_helpers.h>
#include <base/callback.h>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/strings/string_util.h>
#include <base/strings/stringprintf.h>
#include <base/test/simple_test_clock.h>
#include <base/test/task_environment.h>
#include <brillo/asan.h>
#include <brillo/dbus/dbus_method_invoker.h>
#include <brillo/file_utils.h>
#include <dbus/bus.h>
#include <dbus/cryptohome/dbus-constants.h>
#include <dbus/login_manager/dbus-constants.h>
#include <dbus/message.h>
#include <dbus/mock_bus.h>
#include <dbus/mock_exported_object.h>
#include <dbus/mock_object_proxy.h>
#include <dbus/object_path.h>
#include <dbus/scoped_dbus_error.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <login_manager/proto_bindings/policy_descriptor.pb.h>
#include <policy/device_policy_impl.h>
#include "authpolicy/anonymizer.h"
#include "authpolicy/path_service.h"
#include "authpolicy/policy/preg_policy_writer.h"
#include "authpolicy/proto_bindings/active_directory_info.pb.h"
#include "authpolicy/samba_interface.h"
#include "authpolicy/stub_common.h"
#include "bindings/chrome_device_policy.pb.h"
#include "bindings/cloud_policy.pb.h"
#include "bindings/device_management_backend.pb.h"
#include "bindings/policy_constants.h"
using brillo::dbus_utils::DBusObject;
using brillo::dbus_utils::ExtractMethodCallResults;
using dbus::MessageWriter;
using dbus::MockBus;
using dbus::MockExportedObject;
using dbus::MockObjectProxy;
using dbus::ObjectPath;
using dbus::ObjectProxy;
using dbus::Response;
using login_manager::PolicyDescriptor;
using testing::_;
using testing::AnyNumber;
using testing::Invoke;
using testing::NiceMock;
using testing::Return;
using testing::SaveArg;
namespace em = enterprise_management;
namespace authpolicy {
namespace {
// Some arbitrary D-Bus message serial number. Required for mocking D-Bus calls.
const int kDBusSerial = 123;
// Some constants for policy testing.
const bool kPolicyBool = true;
const int kPolicyInt = 321;
const bool kOtherPolicyBool = false;
const int kOtherPolicyInt = 234;
constexpr char kPolicyStr[] = "Str";
constexpr char kOtherPolicyStr[] = "OtherStr";
constexpr char kExtensionId[] = "abcdeFGHabcdefghAbcdefGhabcdEfgh";
constexpr char kOtherExtensionId[] = "ababababcdcdcdcdefefefefghghghgh";
constexpr char kExtensionPolicy1[] = "Policy1";
constexpr char kExtensionPolicy2[] = "Policy2";
constexpr char kMandatoryKey[] = "Policy";
constexpr char kRecommendedKey[] = "Recommended";
// Encryption types in krb5.conf.
constexpr char kKrb5EncTypesAll[] =
"aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 rc4-hmac";
constexpr char kKrb5EncTypesStrong[] =
"aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96";
// Error message when passing different account IDs to authpolicy.
constexpr char kMultiUserNotSupported[] = "Multi-user not supported";
// Stub user hash, returned from the stub Cryptohome proxy's
// GetSanitizedUsername call. Used as part of the user daemon store path.
constexpr char kSanitizedUsername[] = "user_hash";
// Stub daemon store directory used to back up auth state.
constexpr char kDaemonStoreDir[] = "daemon-store";
// SessionStateChanged signal payload we care about.
constexpr char kSessionStarted[] = "started";
constexpr char kSessionStopped[] = "stopped";
// Stub data for auth data cache testing.
constexpr char kCacheTestUserWorkgroup[] = "cache_test_user_workgroup";
constexpr char kCacheTestUserKdcIp[] = "cache_test_user_kdc_ip";
constexpr char kCacheTestUserDcName[] = "cache_test_user_dc_name";
constexpr char kCacheTestMachineWorkgroup[] = "cache_test_machine_workgroup";
constexpr char kCacheTestMachineDcName[] = "cache_test_machine_dc_name";
// See stub_net_main for the strings. Don't bother to make those constants.
constexpr char kDefaultKdcIp[] = "111.222.33.2";
constexpr char kDefaultDcName[] = "DCNAME.EXAMPLE.COM";
// Policy values for cache testing.
const int kZeroHours = 0;
const int kNonZeroHours = 1;
struct SmbConf {
std::string machine_name;
std::string realm;
std::string kerberos_encryption_types;
std::string workgroup;
};
struct Krb5Conf {
std::string default_tgs_enctypes;
std::string default_tkt_enctypes;
std::string permitted_enctypes;
std::string allow_weak_crypto;
std::string kdc;
};
// Checks and casts an integer |error| to the corresponding ErrorType.
WARN_UNUSED_RESULT ErrorType CastError(int error) {
EXPECT_GE(error, 0);
EXPECT_LT(error, ERROR_COUNT);
return static_cast<ErrorType>(error);
}
// Create a file descriptor pointing to a pipe that contains the given data.
base::ScopedFD MakeFileDescriptor(const char* data) {
int fds[2];
EXPECT_TRUE(base::CreateLocalNonBlockingPipe(fds));
base::ScopedFD read_scoped_fd(fds[0]);
base::ScopedFD write_scoped_fd(fds[1]);
EXPECT_TRUE(
base::WriteFileDescriptor(write_scoped_fd.get(), data, strlen(data)));
return read_scoped_fd;
}
// Shortcut to create a file descriptor from a valid password (valid in the
// sense that the stub executables won't trigger any error behavior).
base::ScopedFD MakePasswordFd() {
return MakeFileDescriptor(kPassword);
}
// Stub completion callback for RegisterAsync().
void DoNothing(bool /* unused */) {}
// Creates a D-Bus response with the given |response_str| as message.
std::unique_ptr<dbus::Response> RespondWithString(
dbus::MethodCall* method_call, const std::string& response_str) {
method_call->SetSerial(kDBusSerial);
std::unique_ptr<dbus::Response> response =
dbus::Response::FromMethodCall(method_call);
dbus::MessageWriter writer(response.get());
writer.AppendString(response_str);
return response;
}
// If |error| is ERROR_NONE, parses |proto_blob| into the |proto| if given.
// Otherwise, makes sure |proto_blob| is empty.
template <typename T>
void MaybeParseProto(int error,
const std::vector<uint8_t>& proto_blob,
T* proto) {
if (error != ERROR_NONE) {
EXPECT_TRUE(proto_blob.empty());
return;
}
if (proto) {
EXPECT_TRUE(proto->ParseFromArray(proto_blob.data(),
static_cast<int>(proto_blob.size())));
}
}
// Reads the smb.conf file at |smb_conf_path| and extracts some values.
void ReadSmbConf(const std::string& smb_conf_path, SmbConf* conf) {
std::string smb_conf;
EXPECT_TRUE(base::ReadFileToString(base::FilePath(smb_conf_path), &smb_conf));
FindToken(smb_conf, '=', "netbios name", &conf->machine_name);
EXPECT_TRUE(FindToken(smb_conf, '=', "realm", &conf->realm));
EXPECT_TRUE(FindToken(smb_conf, '=', "kerberos encryption types",
&conf->kerberos_encryption_types));
EXPECT_TRUE(FindToken(smb_conf, '=', "workgroup", &conf->workgroup));
}
// Checks whether the file at smb_conf_path is an smb.conf file and has the
// expected encryption types |expected_enc_types| set.
void CheckSmbEncTypes(const std::string& smb_conf_path,
const char* expected_enc_types) {
SmbConf conf;
ReadSmbConf(smb_conf_path, &conf);
EXPECT_EQ(expected_enc_types, conf.kerberos_encryption_types);
}
// Reads the krb5.conf file at |krb5_conf_path| and extracts some values.
void ReadKrb5Conf(const std::string& krb5_conf_path, Krb5Conf* conf) {
std::string krb5_conf;
EXPECT_TRUE(
base::ReadFileToString(base::FilePath(krb5_conf_path), &krb5_conf));
EXPECT_TRUE(FindToken(krb5_conf, '=', "default_tgs_enctypes",
&conf->default_tgs_enctypes));
EXPECT_TRUE(FindToken(krb5_conf, '=', "default_tkt_enctypes",
&conf->default_tkt_enctypes));
EXPECT_TRUE(FindToken(krb5_conf, '=', "permitted_enctypes",
&conf->permitted_enctypes));
EXPECT_TRUE(
FindToken(krb5_conf, '=', "allow_weak_crypto", &conf->allow_weak_crypto));
// KDC is optional.
if (!FindToken(krb5_conf, '=', "kdc", &conf->kdc))
conf->kdc.clear();
}
// Checks whether the file at krb5_conf_path is a krb5.conf file and has the
// expected encryption types |expected_enc_types| set.
void CheckKrb5EncTypes(const std::string& krb5_conf_path,
const char* expected_enc_types) {
Krb5Conf conf;
ReadKrb5Conf(krb5_conf_path, &conf);
EXPECT_EQ(expected_enc_types, conf.default_tgs_enctypes);
EXPECT_EQ(expected_enc_types, conf.default_tkt_enctypes);
EXPECT_EQ(expected_enc_types, conf.permitted_enctypes);
EXPECT_EQ("false", conf.allow_weak_crypto);
}
// Returns [|ip|].
std::string EmbraceIp(const std::string& ip) {
return "[" + ip + "]";
}
// Helper class that points some paths to convenient locations we can write to.
class TestPathService : public PathService {
public:
explicit TestPathService(const base::FilePath& base_path)
: PathService(false) {
// Stub binaries are in the OUT folder politely provided by the test script.
base::FilePath stub_path(getenv("OUT"));
CHECK(!stub_path.empty());
// Need to create the run dir since it is usually created by the ebuild.
base::FilePath run_dir = base_path.Append("run");
CHECK(base::CreateDirectory(run_dir));
// Override base directories.
Insert(Path::TEMP_DIR, base_path.Append("temp").value());
Insert(Path::STATE_DIR, base_path.Append("state").value());
Insert(Path::RUN_DIR, run_dir.value());
Insert(Path::DAEMON_STORE_DIR, base_path.Append(kDaemonStoreDir).value());
// Override binaries.
Insert(Path::KINIT, stub_path.Append("stub_kinit").value());
Insert(Path::KLIST, stub_path.Append("stub_klist").value());
Insert(Path::KPASSWD, stub_path.Append("stub_kpasswd").value());
Insert(Path::NET, stub_path.Append("stub_net").value());
Insert(Path::SMBCLIENT, stub_path.Append("stub_smbclient").value());
// Fill in the rest of the paths and build dependend paths.
Initialize();
}
};
// Metrics library that eats in particular timer errors.
class TestMetricsLibrary : public MetricsLibrary {
public:
bool SendToUMA(const std::string&, int, int, int, int) override {
return true;
}
};
// Version of AuthPolicyMetrics that just counts stats.
class TestMetrics : public AuthPolicyMetrics {
public:
TestMetrics() {
// Prevent some error messages from timers.
chromeos_metrics::TimerReporter::set_metrics_lib(&test_metrics_);
}
~TestMetrics() override {
chromeos_metrics::TimerReporter::set_metrics_lib(nullptr);
}
void Report(MetricType metric_type, int sample) override {
last_metrics_sample_[metric_type] = sample;
metrics_report_count_[metric_type]++;
}
void ReportError(ErrorMetricType metric_type,
ErrorType /* error */) override {
error_report_count_[metric_type]++;
}
// Returns the most recently reported sample for the given |metric_type| or
// -1 if the metric has not been reported.
int GetLastMetricSample(MetricType metric_type) {
auto iter = last_metrics_sample_.find(metric_type);
return iter != last_metrics_sample_.end() ? iter->second : -1;
}
// Returns how often Report() was called with given |metric_type| and erases
// the count. Inefficient if metric_type isn't in the map, but shorter :)
int GetNumMetricReports(MetricType metric_type) {
const int count = metrics_report_count_[metric_type];
metrics_report_count_.erase(metric_type);
return count;
}
// Returns how often ReportDBusResult() was called with given |metric_type|
// and erases the count. Inefficient if |metric_type| isn't in the map, but
// shorter :)
int GetNumErrorReports(ErrorMetricType metric_type) {
const int count = error_report_count_[metric_type];
error_report_count_.erase(metric_type);
return count;
}
private:
TestMetricsLibrary test_metrics_;
std::map<MetricType, int> last_metrics_sample_;
std::map<MetricType, int> metrics_report_count_;
std::map<ErrorMetricType, int> error_report_count_;
};
// Helper to check the ErrorType value returned by authpolicy D-Bus calls.
// |was_called| is a marker used by the code that queues this callback to make
// sure that this callback was indeed called.
void CheckError(ErrorType expected_error,
bool* was_called,
std::unique_ptr<Response> response) {
EXPECT_TRUE(response.get());
dbus::MessageReader reader(response.get());
int32_t int_error;
EXPECT_TRUE(reader.PopInt32(&int_error));
ErrorType actual_error = CastError(int_error);
EXPECT_EQ(expected_error, actual_error);
EXPECT_TRUE(was_called);
EXPECT_FALSE(*was_called);
*was_called = true;
}
// Response callback for AuthenticateUser calls in Auth(). Sets |was_called| to
// true and deserializes the |error| and |account_info_blob| parameters.
void AuthResponseCallback(bool* was_called,
int* error,
std::vector<uint8_t>* account_info_blob,
std::unique_ptr<Response> response) {
EXPECT_TRUE(response.get());
dbus::MessageReader reader(response.get());
EXPECT_TRUE(reader.PopInt32(error));
// Note: reader owns buf.
const uint8_t* buf = NULL;
size_t buf_size = 0;
EXPECT_TRUE(reader.PopArrayOfBytes(&buf, &buf_size));
if (*error == ERROR_NONE) {
EXPECT_TRUE(buf);
EXPECT_LT(0, buf_size);
EXPECT_TRUE(account_info_blob);
account_info_blob->assign(buf, buf + buf_size);
} else {
account_info_blob->clear();
}
EXPECT_TRUE(was_called);
EXPECT_FALSE(*was_called);
*was_called = true;
}
// Matcher for D-Bus method names to be used in CallMethod*().
MATCHER_P(IsMethod, method_name, "") {
return arg->GetMember() == method_name;
}
} // namespace
// Integration test for the authpolicyd D-Bus interface.
//
// Since the Active Directory protocols are a black box to us, a stub local
// server cannot be used. Instead, the Samba/Kerberos binaries are stubbed out.
//
// Error behavior is triggered by passing special user principals or passwords
// to the stub binaries. For instance, using |kNonExistingUserPrincipal| makes
// stub_kinit behave as if the requested account does not exist on the server.
// The same principle is used throughout this test.
//
// During policy fetch, authpolicy sends D-Bus messages to Session Manager. This
// communication is mocked out.
class AuthPolicyTest : public testing::Test {
public:
void SetUp() override {
// The message loop registers a task runner with the current thread, which
// is used by TgtManager to post automatic TGT renewal tasks.
const ObjectPath object_path(std::string("/object/path"));
auto dbus_object =
std::make_unique<DBusObject>(nullptr, mock_bus_, object_path);
metrics_ = std::make_unique<TestMetrics>();
// Create path service with all paths pointing into a temp directory.
CHECK(base::CreateNewTempDirectory("" /* prefix (ignored) */, &base_path_));
paths_ = std::make_unique<TestPathService>(base_path_);
// Create the state directory since authpolicyd assumes its existence.
const base::FilePath state_path =
base::FilePath(paths_->Get(Path::STATE_DIR));
CHECK(base::CreateDirectory(state_path));
// Create daemon store directory where authpolicyd backs up auth state.
user_daemon_store_path_ =
base_path_.Append(kDaemonStoreDir).Append(kSanitizedUsername);
CHECK(base::CreateDirectory(user_daemon_store_path_));
// Stub path where the Kerberos ticket is backed up.
backup_path_ = user_daemon_store_path_.Append("user_backup_data");
// Set stub preg path. Since it is not trivial to pass the full path to the
// stub binaries, we simply use the directory from the krb5.conf file.
const base::FilePath gpo_dir =
base::FilePath(paths_->Get(Path::USER_KRB5_CONF)).DirName();
DCHECK(gpo_dir ==
base::FilePath(paths_->Get(Path::DEVICE_KRB5_CONF)).DirName());
stub_gpo1_path_ = gpo_dir.Append(kGpo1Filename);
stub_gpo2_path_ = gpo_dir.Append(kGpo2Filename);
// Mock out D-Bus initialization.
mock_exported_object_ =
new MockExportedObject(mock_bus_.get(), object_path);
EXPECT_CALL(*mock_bus_, GetExportedObject(object_path))
.Times(1)
.WillOnce(Return(mock_exported_object_.get()));
EXPECT_CALL(*mock_bus_, GetDBusTaskRunner())
.Times(1)
.WillOnce(Return(task_environment_.GetMainThreadTaskRunner().get()));
EXPECT_CALL(*mock_exported_object_, ExportMethod(_, _, _, _))
.Times(AnyNumber());
EXPECT_CALL(*mock_exported_object_, SendSignal(_))
.WillRepeatedly(
Invoke(this, &AuthPolicyTest::HandleUserKerberosFilesChanged));
// Set up mock object proxy for session manager called from authpolicy.
mock_session_manager_proxy_ = new MockObjectProxy(
mock_bus_.get(), login_manager::kSessionManagerServiceName,
dbus::ObjectPath(login_manager::kSessionManagerServicePath));
EXPECT_CALL(*mock_bus_,
GetObjectProxy(login_manager::kSessionManagerServiceName, _))
.WillOnce(Return(mock_session_manager_proxy_.get()));
EXPECT_CALL(
*mock_session_manager_proxy_,
DoCallMethodWithErrorCallback(
IsMethod(login_manager::kSessionManagerStoreUnsignedPolicyEx), _, _,
_))
.WillRepeatedly(
Invoke(this, &AuthPolicyTest::StubCallStorePolicyMethod));
EXPECT_CALL(
*mock_session_manager_proxy_,
CallMethodAndBlockWithErrorDetails(
IsMethod(login_manager::kSessionManagerListStoredComponentPolicies),
_, _))
.WillRepeatedly(
Invoke(this, &AuthPolicyTest::StubListComponentIdsMethod));
EXPECT_CALL(
*mock_session_manager_proxy_,
DoConnectToSignal(login_manager::kSessionManagerInterface,
login_manager::kSessionStateChangedSignal, _, _))
.WillOnce((SaveArg<2>(&session_state_changed_callback_)));
EXPECT_CALL(
*mock_session_manager_proxy_.get(),
CallMethodAndBlockWithErrorDetails(
IsMethod(login_manager::kSessionManagerRetrieveSessionState), _, _))
.WillOnce(Invoke([](dbus::MethodCall* method_call, int timeout,
dbus::ScopedDBusError* error) {
return RespondWithString(method_call, kSessionStopped);
}));
// Set up mock object proxy for Cryptohome called from authpolicy.
mock_cryptohome_proxy_ = new NiceMock<MockObjectProxy>(
mock_bus_.get(), cryptohome::kCryptohomeServiceName,
dbus::ObjectPath(cryptohome::kCryptohomeServicePath));
EXPECT_CALL(*mock_bus_,
GetObjectProxy(cryptohome::kCryptohomeServiceName, _))
.WillOnce(Return(mock_cryptohome_proxy_.get()));
// Make Cryptohome's GetSanitizedUsername call return kSanitizedUsername.
ON_CALL(*mock_cryptohome_proxy_, CallMethodAndBlock(_, _))
.WillByDefault(Invoke([](dbus::MethodCall* method_call, int timeout) {
return RespondWithString(method_call, kSanitizedUsername);
}));
// Create AuthPolicy instance. Do this AFTER creating the proxy mocks since
// they might be accessed during initialization.
authpolicy_ = std::make_unique<AuthPolicy>(metrics_.get(), paths_.get());
EXPECT_EQ(ERROR_NONE, authpolicy_->Initialize(false /* expect_config */));
authpolicy_->RegisterAsync(std::move(dbus_object), base::Bind(&DoNothing));
// Don't sleep for kinit/smbclient retries, it just prolongs our tests.
samba().DisableRetrySleepForTesting();
// Unit tests usually run code that only exists in tests (like the
// framework), so disable the seccomp filters.
samba().DisableSeccompForTesting(true);
}
// Stub method called by the Session Manager mock to store policy. Validates
// the type of policy (user/device) contained in the |method_call|. If set by
// the individual unit tests, calls |validate_user_policy_| or
// |validate_device_policy_| to validate the contents of the policy proto.
void StubCallStorePolicyMethod(
dbus::MethodCall* method_call,
int /* timeout_ms */,
ObjectProxy::ResponseCallback* callback,
dbus::ObjectProxy::ErrorCallback* error_callback) {
// Safety check to make sure that old values are not carried along.
if (!store_policy_called_) {
EXPECT_FALSE(user_policy_validated_);
EXPECT_FALSE(device_policy_validated_);
EXPECT_EQ(0, validated_extension_ids_.size());
} else {
// The first policy stored is always user or device policy.
EXPECT_TRUE(user_policy_validated_ ^ device_policy_validated_);
}
store_policy_called_ = true;
// Based on the method name, check whether this is user or device policy.
EXPECT_TRUE(method_call);
EXPECT_TRUE(method_call->GetMember() ==
login_manager::kSessionManagerStoreUnsignedPolicyEx);
// Extract the policy blob from the method call.
std::vector<uint8_t> descriptor_blob;
std::vector<uint8_t> response_blob;
brillo::ErrorPtr error;
EXPECT_TRUE(ExtractMethodCallResults(method_call, &error, &descriptor_blob,
&response_blob));
// Unpack descriptor.
PolicyDescriptor descriptor;
const std::string descriptor_blob_str(descriptor_blob.begin(),
descriptor_blob.end());
EXPECT_TRUE(descriptor.ParseFromString(descriptor_blob_str));
// If policy is deleted, response_blob is an empty string.
if (response_blob.empty()) {
EXPECT_EQ(descriptor.domain(), login_manager::POLICY_DOMAIN_EXTENSIONS);
deleted_extension_ids_.insert(descriptor.component_id());
} else {
// Unwrap the three gazillion layers or policy.
const std::string response_blob_str(response_blob.begin(),
response_blob.end());
em::PolicyFetchResponse policy_response;
EXPECT_TRUE(policy_response.ParseFromString(response_blob_str));
em::PolicyData policy_data;
EXPECT_TRUE(policy_data.ParseFromString(policy_response.policy_data()));
// Run the policy through the appropriate policy validator.
ValidatePolicy(descriptor, policy_data);
}
// Answer authpolicy with an empty response to signal that policy has been
// stored.
EXPECT_FALSE((*callback).is_null());
std::move(*callback).Run(Response::CreateEmpty().get());
}
// Stub method called by the Session Manager mock to list stored component
// policy ids.
std::unique_ptr<dbus::Response> StubListComponentIdsMethod(
dbus::MethodCall* method_call,
int /* timeout_ms */,
dbus::ScopedDBusError* error) {
method_call->SetSerial(kDBusSerial);
auto response = dbus::Response::FromMethodCall(method_call);
dbus::MessageWriter writer(response.get());
writer.AppendArrayOfStrings(stored_extension_ids_);
// Note: The mock wraps this back into a std::unique_ptr.
return response;
}
void TearDown() override {
EXPECT_EQ(expected_error_reports[ERROR_OF_AUTHENTICATE_USER],
metrics_->GetNumErrorReports(ERROR_OF_AUTHENTICATE_USER));
EXPECT_EQ(expected_error_reports[ERROR_OF_GET_USER_STATUS],
metrics_->GetNumErrorReports(ERROR_OF_GET_USER_STATUS));
EXPECT_EQ(expected_error_reports[ERROR_OF_GET_USER_KERBEROS_FILES],
metrics_->GetNumErrorReports(ERROR_OF_GET_USER_KERBEROS_FILES));
EXPECT_EQ(expected_error_reports[ERROR_OF_JOIN_AD_DOMAIN],
metrics_->GetNumErrorReports(ERROR_OF_JOIN_AD_DOMAIN));
EXPECT_EQ(expected_error_reports[ERROR_OF_REFRESH_USER_POLICY],
metrics_->GetNumErrorReports(ERROR_OF_REFRESH_USER_POLICY));
EXPECT_EQ(expected_error_reports[ERROR_OF_REFRESH_DEVICE_POLICY],
metrics_->GetNumErrorReports(ERROR_OF_REFRESH_DEVICE_POLICY));
EXPECT_CALL(*mock_exported_object_, Unregister()).Times(1);
// Don't not leave no mess behind.
base::DeletePathRecursively(base_path_);
}
protected:
// Joins a (stub) Active Directory domain. Returns the error code.
ErrorType Join(const std::string& machine_name,
const std::string& user_principal,
base::ScopedFD password_fd) WARN_UNUSED_RESULT {
JoinDomainRequest request;
request.set_machine_name(machine_name);
request.set_user_principal_name(user_principal);
return JoinEx(request, std::move(password_fd));
}
// Joins a (stub) Active Directory domain, locks the device and fetches empty
// device policy. Expects success.
void JoinAndFetchDevicePolicy(const std::string& machine_name) {
EXPECT_EQ(ERROR_NONE, Join(machine_name, kUserPrincipal, MakePasswordFd()));
MarkDeviceAsLocked();
validate_device_policy_ = &CheckDevicePolicyEmpty;
FetchAndValidateDevicePolicy(ERROR_NONE);
}
// Extended Join() that takes a full JoinDomainRequest proto.
ErrorType JoinEx(const JoinDomainRequest& request,
base::ScopedFD password_fd,
std::string* joined_domain = nullptr) WARN_UNUSED_RESULT {
expected_error_reports[ERROR_OF_JOIN_AD_DOMAIN]++;
std::vector<uint8_t> blob(request.ByteSizeLong());
request.SerializeToArray(blob.data(), blob.size());
int error;
authpolicy_->JoinADDomain(blob, password_fd, &error, joined_domain);
return CastError(error);
}
// Authenticates to a (stub) Active Directory domain with the given
// credentials and returns the error code. Assigns the user account info to
// |account_info| if a non-nullptr is provided.
ErrorType Auth(const std::string& user_principal,
const std::string& account_id,
base::ScopedFD password_fd,
ActiveDirectoryAccountInfo* account_info = nullptr)
WARN_UNUSED_RESULT {
int32_t error = ERROR_NONE;
std::vector<uint8_t> account_info_blob;
expected_error_reports[ERROR_OF_AUTHENTICATE_USER]++;
int prev_files_changed_count = user_kerberos_files_changed_count_;
AuthenticateUserRequest request;
request.set_user_principal_name(user_principal);
request.set_account_id(account_id);
std::vector<uint8_t> request_blob(request.ByteSizeLong());
request.SerializeToArray(request_blob.data(), request_blob.size());
bool callback_was_called = false;
dbus::MethodCall method_call(kAuthPolicyInterface, kAuthenticateUserMethod);
method_call.SetSerial(kDBusSerial);
auto callback = std::make_unique<
brillo::dbus_utils::DBusMethodResponse<int32_t, std::vector<uint8_t>>>(
&method_call, base::Bind(&AuthResponseCallback, &callback_was_called,
&error, &account_info_blob));
authpolicy_->AuthenticateUser(std::move(callback), request_blob,
password_fd);
EXPECT_TRUE(callback_was_called);
MaybeParseProto(error, account_info_blob, account_info);
// At most one UserKerberosFilesChanged signal should have been fired.
EXPECT_LE(user_kerberos_files_changed_count_, prev_files_changed_count + 1);
return CastError(error);
}
// Gets a fake user status from a (stub) Active Directory service.
// |account_id| is the id (aka objectGUID) of the user. Assigns the user's
// status to |user_status| if a non-nullptr is given.
ErrorType GetUserStatus(const std::string& user_principal,
const std::string& account_id,
ActiveDirectoryUserStatus* user_status = nullptr)
WARN_UNUSED_RESULT {
int32_t error = ERROR_NONE;
std::vector<uint8_t> user_status_blob;
expected_error_reports[ERROR_OF_GET_USER_STATUS]++;
GetUserStatusRequest request;
request.set_user_principal_name(user_principal);
request.set_account_id(account_id);
std::vector<uint8_t> blob(request.ByteSizeLong());
request.SerializeToArray(blob.data(), blob.size());
authpolicy_->GetUserStatus(blob, &error, &user_status_blob);
MaybeParseProto(error, user_status_blob, user_status);
return CastError(error);
}
ErrorType GetUserKerberosFiles(const std::string& account_id,
KerberosFiles* kerberos_files = nullptr)
WARN_UNUSED_RESULT {
int32_t error = ERROR_NONE;
std::vector<uint8_t> kerberos_files_blob;
expected_error_reports[ERROR_OF_GET_USER_KERBEROS_FILES]++;
authpolicy_->GetUserKerberosFiles(account_id, &error, &kerberos_files_blob);
MaybeParseProto(error, kerberos_files_blob, kerberos_files);
return CastError(error);
}
// Authenticates to a (stub) Active Directory domain with default credentials.
// Returns the account id.
std::string DefaultAuth() {
ActiveDirectoryAccountInfo account_info;
EXPECT_EQ(ERROR_NONE,
Auth(kUserPrincipal, "", MakePasswordFd(), &account_info));
return account_info.account_id();
}
// Calls AuthPolicy::RefreshUserPolicy(). Verifies that
// StubCallStorePolicyMethod() and validate_user_policy_ are called as
// expected. These callbacks verify that the policy protobuf is valid and
// validate the contents.
void FetchAndValidateUserPolicy(const std::string& account_id,
ErrorType expected_error) {
dbus::MethodCall method_call(kAuthPolicyInterface,
kRefreshUserPolicyMethod);
method_call.SetSerial(kDBusSerial);
store_policy_called_ = false;
user_policy_validated_ = false;
device_policy_validated_ = false;
validated_extension_ids_.clear();
deleted_extension_ids_.clear();
bool callback_was_called = false;
AuthPolicy::PolicyResponseCallback callback =
std::make_unique<brillo::dbus_utils::DBusMethodResponse<int32_t>>(
&method_call,
base::Bind(&CheckError, expected_error, &callback_was_called));
expected_error_reports[ERROR_OF_REFRESH_USER_POLICY]++;
authpolicy_->RefreshUserPolicy(std::move(callback), account_id);
// If policy fetch succeeds, authpolicy_ makes a D-Bus call to Session
// Manager to store policy. We intercept this call and point it to
// StubCallStorePolicyMethod(), which validates policy and calls CheckError.
// If policy fetch fails, StubCallStorePolicyMethod() is not called, but
// authpolicy calls CheckError directly.
EXPECT_EQ(expected_error == ERROR_NONE, store_policy_called_);
EXPECT_EQ(expected_error == ERROR_NONE, user_policy_validated_);
EXPECT_FALSE(expected_error != ERROR_NONE &&
validated_extension_ids_.size() > 0);
EXPECT_FALSE(device_policy_validated_);
EXPECT_TRUE(callback_was_called); // Make sure CheckError() was called.
}
// Calls AuthPolicy::RefreshDevicePolicy(). Verifies that
// StubCallStorePolicyMethod() and validate_device_policy_ are called as
// expected. These callbacks verify that the policy protobuf is valid and
// validate the contents.
void FetchAndValidateDevicePolicy(ErrorType expected_error) {
dbus::MethodCall method_call(kAuthPolicyInterface,
kRefreshDevicePolicyMethod);
method_call.SetSerial(kDBusSerial);
store_policy_called_ = false;
user_policy_validated_ = false;
device_policy_validated_ = false;
validated_extension_ids_.clear();
deleted_extension_ids_.clear();
bool callback_was_called = false;
AuthPolicy::PolicyResponseCallback callback =
std::make_unique<brillo::dbus_utils::DBusMethodResponse<int32_t>>(
&method_call,
base::Bind(&CheckError, expected_error, &callback_was_called));
expected_error_reports[ERROR_OF_REFRESH_DEVICE_POLICY]++;
authpolicy_->RefreshDevicePolicy(std::move(callback));
// If policy fetch succeeds, authpolicy_ makes a D-Bus call to Session
// Manager to store policy. We intercept this call and point it to
// StubCallStorePolicyMethod(), which validates policy and calls CheckError.
// If policy fetch fails, StubCallStorePolicyMethod() is not called, but
// authpolicy calls CheckError directly.
EXPECT_EQ(expected_error == ERROR_NONE, store_policy_called_);
EXPECT_EQ(expected_error == ERROR_NONE, device_policy_validated_);
EXPECT_FALSE(expected_error != ERROR_NONE &&
validated_extension_ids_.size());
EXPECT_FALSE(user_policy_validated_);
EXPECT_TRUE(callback_was_called); // Make sure CheckError() was called.
}
// Runs the policy stored in |policy_data| through the validator function
// for the corresponding policy type.
void ValidatePolicy(const PolicyDescriptor& descriptor,
const em::PolicyData& policy_data) {
if (policy_data.policy_type() == kChromeUserPolicyType) {
EXPECT_EQ(descriptor.account_type(), login_manager::ACCOUNT_TYPE_USER);
EXPECT_FALSE(descriptor.account_id().empty());
EXPECT_EQ(descriptor.domain(), login_manager::POLICY_DOMAIN_CHROME);
EXPECT_TRUE(descriptor.component_id().empty());
em::CloudPolicySettings policy;
EXPECT_TRUE(policy.ParseFromString(policy_data.policy_value()));
if (validate_user_policy_) {
validate_user_policy_(policy);
user_policy_validated_ = true;
}
user_affiliation_marker_set_ =
policy_data.user_affiliation_ids_size() == 1 &&
policy_data.user_affiliation_ids(0) == kAffiliationMarker;
} else if (policy_data.policy_type() == kChromeDevicePolicyType) {
EXPECT_EQ(descriptor.account_type(), login_manager::ACCOUNT_TYPE_DEVICE);
EXPECT_TRUE(descriptor.account_id().empty());
EXPECT_EQ(descriptor.domain(), login_manager::POLICY_DOMAIN_CHROME);
EXPECT_TRUE(descriptor.component_id().empty());
em::ChromeDeviceSettingsProto policy;
EXPECT_TRUE(policy.ParseFromString(policy_data.policy_value()));
if (validate_device_policy_) {
validate_device_policy_(policy);
device_policy_validated_ = true;
}
EXPECT_EQ(1, policy_data.device_affiliation_ids_size());
EXPECT_EQ(kAffiliationMarker, policy_data.device_affiliation_ids(0));
} else if (policy_data.policy_type() == kChromeExtensionPolicyType) {
EXPECT_EQ(descriptor.domain(), login_manager::POLICY_DOMAIN_EXTENSIONS);
EXPECT_EQ(descriptor.component_id(), policy_data.settings_entity_id());
if (validate_extension_policy_) {
// policy_value() is the raw JSON string here.
validate_extension_policy_(descriptor.component_id(),
policy_data.policy_value());
validated_extension_ids_.insert(descriptor.component_id());
}
}
}
// Checks whether the user |policy| is empty.
static void CheckUserPolicyEmpty(const em::CloudPolicySettings& policy) {
em::CloudPolicySettings empty_policy;
EXPECT_EQ(policy.ByteSizeLong(), empty_policy.ByteSizeLong());
}
// Does not validate user policy. Use if you're testing something unrelated.
static void DontValidateUserPolicy(
const em::CloudPolicySettings& /* policy */) {}
// Checks whether the device |policy| is empty.
static void CheckDevicePolicyEmpty(
const em::ChromeDeviceSettingsProto& policy) {
em::ChromeDeviceSettingsProto empty_policy;
EXPECT_EQ(policy.ByteSizeLong(), empty_policy.ByteSizeLong());
}
// Does not validate device policy. Use if you're testing something unrelated.
static void DontValidateDevicePolicy(
const em::ChromeDeviceSettingsProto& /* policy */) {}
// Checks whether the extension |policy_json| is empty.
static void CheckExtensionPolicyEmpty(const std::string& /* extension_id */,
const std::string& policy_json) {
EXPECT_TRUE(policy_json.empty());
}
// Writes some default extension to the given writer.
static void WriteDefaultExtensionPolicy(policy::PRegPolicyWriter* writer) {
writer->SetKeysForExtensionPolicy(kExtensionId);
writer->AppendString(kExtensionPolicy1, kPolicyStr);
writer->SetKeysForExtensionPolicy(kOtherExtensionId);
writer->AppendBoolean(kExtensionPolicy2, kPolicyBool,
policy::POLICY_LEVEL_RECOMMENDED);
}
// Checks some default extension |policy_json| we're using for this test.
static void CheckDefaultExtensionPolicy(const std::string& extension_id,
const std::string& policy_json) {
std::string expected_policy_json;
if (extension_id == kExtensionId) {
expected_policy_json =
base::StringPrintf("{\"%s\":{\"%s\":\"%s\"}}", kMandatoryKey,
kExtensionPolicy1, kPolicyStr);
} else if (extension_id == kOtherExtensionId) {
expected_policy_json = base::StringPrintf(
"{\"%s\":{\"%s\":1}}", kRecommendedKey, kExtensionPolicy2);
} else {
FAIL() << "Unexpected extension id " << extension_id;
}
EXPECT_EQ(policy_json, expected_policy_json);
}
// Authpolicyd revokes write permissions on config.dat. Some tests perform two
// domain joins, though, and need to overwrite the previously generated config
// file.
bool MakeConfigWriteable() {
const base::FilePath config_path(paths_->Get(Path::CONFIG_DAT));
const int mode = base::FILE_PERMISSION_READ_BY_USER |
base::FILE_PERMISSION_WRITE_BY_USER;
return base::SetPosixFilePermissions(config_path, mode);
}
SambaInterface& samba() { return authpolicy_->GetSambaInterfaceForTesting(); }
void MarkDeviceAsLocked() { authpolicy_->SetDeviceIsLockedForTesting(); }
// Writes one file to |gpo_path| with a few policies. Sets up
// |validate_device_policy_| callback with corresponding expectations.
void SetupDeviceOneGpo(const base::FilePath& gpo_path) {
policy::PRegUserDevicePolicyWriter writer;
writer.AppendBoolean(policy::key::kDeviceGuestModeEnabled, kPolicyBool);
writer.AppendInteger(policy::key::kDevicePolicyRefreshRate, kPolicyInt);
writer.AppendString(policy::key::kSystemTimezone, kPolicyStr);
const std::vector<std::string> str_list = {"str1", "str2"};
writer.AppendStringList(policy::key::kDeviceUserWhitelist, str_list);
writer.WriteToFile(gpo_path);
validate_device_policy_ = [str_list](
const em::ChromeDeviceSettingsProto& policy) {
EXPECT_EQ(kPolicyBool, policy.guest_mode_enabled().guest_mode_enabled());
EXPECT_EQ(
kPolicyInt,
policy.device_policy_refresh_rate().device_policy_refresh_rate());
EXPECT_EQ(kPolicyStr, policy.system_timezone().timezone());
const em::UserWhitelistProto& str_list_proto = policy.user_whitelist();
EXPECT_EQ(str_list_proto.user_whitelist_size(),
static_cast<int>(str_list.size()));
for (int n = 0; n < str_list_proto.user_whitelist_size(); ++n)
EXPECT_EQ(str_list_proto.user_whitelist(n), str_list.at(n));
};
}
// Writes a device policy file to |policy_path|. The file can be read with
// libpolicy.
void WriteDevicePolicyFile(const base::FilePath& policy_path,
const em::ChromeDeviceSettingsProto& policy) {
em::PolicyData policy_data;
policy_data.set_policy_value(policy.SerializeAsString());
em::PolicyFetchResponse policy_fetch_response;
policy_fetch_response.set_policy_data(policy_data.SerializeAsString());
std::string policy_blob = policy_fetch_response.SerializeAsString();
brillo::WriteStringToFile(policy_path, policy_blob);
}
// Writes |device_policy| to a file, points samba() to it and reinitializes
// samba(). This simulates a restart of authpolicyd with given device policy.
void WritePolicyAndRestartAuthpolicy(
const em::ChromeDeviceSettingsProto& device_policy) {
const base::FilePath policy_path = base_path_.Append("policy");
WriteDevicePolicyFile(policy_path, device_policy);
// Set up a device policy instance that reads from our fake file.
// Verification has to be disabled since MarkDeviceAsLocked() applies to
// authpolicy only, but doesn't actually set the real install attributes
// read by the impl.
auto policy_impl = std::make_unique<policy::DevicePolicyImpl>();
policy_impl->set_policy_path_for_testing(policy_path);
policy_impl->set_verify_policy_for_testing(false);
// Initialize again. This should load the device policy file.
samba().ResetForTesting();
samba().SetDevicePolicyImplForTesting(std::move(policy_impl));
EXPECT_EQ(ERROR_NONE, samba().Initialize(true /* expect_config */));
}
// Returns the modification time of the file at |path|.
base::Time GetLastModified(const base::FilePath& path) {
base::File::Info file_info;
EXPECT_TRUE(GetFileInfo(path, &file_info));
return file_info.last_modified;
}
// Returns the modification time of the file at |path|.
base::Time GetLastModified(Path path) {
return GetLastModified(base::FilePath(paths_->Get(path)));
}
void SetLastModified(Path path, const base::Time& last_modified) {
const base::FilePath filepath(paths_->Get(path));
base::File::Info file_info;
EXPECT_TRUE(GetFileInfo(filepath, &file_info));
EXPECT_TRUE(
base::TouchFile(filepath, file_info.last_accessed, last_modified));
}
// Returns the contents of the file at |path|.
std::string ReadFile(Path path) {
std::string str;
EXPECT_TRUE(
base::ReadFileToString(base::FilePath(paths_->Get(path)), &str));
return str;
}
// Sends the session started signal to authpolicyd.
void NotifySessionStarted() {
// Tell authpolicyd that the session started.
dbus::Signal signal(login_manager::kSessionManagerInterface,
login_manager::kSessionStateChangedSignal);
dbus::MessageWriter writer(&signal);
writer.AppendString("started");
session_state_changed_callback_.Run(&signal);
}
base::test::TaskEnvironment task_environment_{
base::test::TaskEnvironment::ThreadingMode::MAIN_THREAD_ONLY};