forked from OpenAtomFoundation/pikiwidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathacl.cc
1415 lines (1241 loc) · 40.6 KB
/
acl.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 (c) 2015-present, Qihoo, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <fmt/format.h>
#include <cstring>
#include <fstream>
#include <shared_mutex>
#include "include/acl.h"
#include "include/pika_cmd_table_manager.h"
#include "include/pika_command.h"
#include "include/pika_server.h"
#include "pstd_defer.h"
#include "pstd_hash.h"
extern PikaServer* g_pika_server;
extern std::unique_ptr<PikaCmdTableManager> g_pika_cmd_table_manager;
// class User
User::User(std::string name) : name_(std::move(name)) {
selectors_.emplace_back(std::make_shared<AclSelector>(static_cast<uint32_t>(AclSelectorFlag::ROOT)));
}
User::User(const User& user) : name_(user.Name()) {
flags_ = user.flags_.load();
passwords_ = user.passwords_;
aclString_ = user.aclString_;
for (const auto& item : user.selectors_) {
selectors_.emplace_back(std::make_shared<AclSelector>(*item));
}
}
std::string User::Name() const { return name_; }
void User::CleanAclString() { aclString_.clear(); }
void User::AddPassword(const std::string& password) { passwords_.insert(password); }
void User::RemovePassword(const std::string& password) { passwords_.erase(password); }
void User::CleanPassword() { passwords_.clear(); }
void User::AddSelector(const std::shared_ptr<AclSelector>& selector) { selectors_.push_back(selector); }
pstd::Status User::SetUser(const std::vector<std::string>& rules) {
std::unique_lock wl(mutex_);
for (const auto& rule : rules) {
auto status = SetUser(rule);
if (!status.ok()) {
LOG(ERROR) << "SetUser rule:" << rule << status.ToString();
return status;
}
}
return pstd::Status::OK();
}
pstd::Status User::SetUser(const std::string& op) {
CleanAclString();
if (op.empty()) {
return pstd::Status::OK();
}
if (!strcasecmp(op.data(), "on")) {
AddFlags(static_cast<uint32_t>(AclUserFlag::ENABLED));
DecFlags(static_cast<uint32_t>(AclUserFlag::DISABLED));
} else if (!strcasecmp(op.data(), "off")) {
AddFlags(static_cast<uint32_t>(AclUserFlag::DISABLED));
DecFlags(static_cast<uint32_t>(AclUserFlag::ENABLED));
} else if (!strcasecmp(op.data(), "nopass")) {
AddFlags(static_cast<uint32_t>(AclUserFlag::NO_PASS));
CleanPassword();
} else if (!strcasecmp(op.data(), "resetpass")) {
DecFlags(static_cast<uint32_t>(AclUserFlag::NO_PASS));
CleanPassword();
} else if (op[0] == '>' || op[0] == '#') {
std::string newpass;
if (op[0] == '>') {
newpass = pstd::sha256(op.data() + 1);
} else {
if (!pstd::isSha256(op.data() + 1)) {
return pstd::Status::Error("password not sha256");
}
newpass = op.data() + 1;
}
AddPassword(newpass);
DecFlags(static_cast<uint32_t>(AclUserFlag::NO_PASS));
} else if (op[0] == '<' || op[0] == '!') {
std::string delpass;
if (op[0] == '<') {
delpass = pstd::sha256(op.data() + 1);
} else {
if (!pstd::isSha256(op.data() + 1)) {
return pstd::Status::Error("password not sha256");
}
delpass = op.data() + 1;
}
// passwords_.erase(delpass);
RemovePassword(delpass);
} else if (op[0] == '(' && op[op.size() - 1] == ')') {
auto status = CreateSelectorFromOpSet(op);
if (!status.ok()) {
return status;
}
} else if (!strcasecmp(op.data(), "clearselectors")) {
selectors_.clear();
return pstd::Status::OK();
} else if (!strcasecmp(op.data(), "reset")) {
auto status = SetUser("resetpass");
if (!status.ok()) {
return status;
}
status = SetUser("resetkeys");
if (!status.ok()) {
return status;
}
status = SetUser("resetchannels");
if (!status.ok()) {
return status;
}
if (g_pika_conf->acl_pubsub_default() & static_cast<uint32_t>(AclSelectorFlag::ALL_CHANNELS)) {
status = SetUser("allchannels");
if (!status.ok()) {
return status;
}
}
status = SetUser("off");
if (!status.ok()) {
return status;
}
status = SetUser("-@all");
if (!status.ok()) {
return status;
}
} else {
auto root = GetRootSelector();
if (!root) { // does not appear under normal circumstances
LOG(ERROR) << "set user:" << Name() << " not find root selector";
return pstd::Status::Error("set user error,See pika log for details");
}
auto status = root->SetSelector(op);
if (!status.ok()) {
return status;
}
}
return pstd::Status::OK();
}
pstd::Status User::CreateSelectorFromOpSet(const std::string& opSet) {
auto selector = std::make_shared<AclSelector>();
auto status = selector->SetSelectorFromOpSet(opSet);
if (!status.ok()) {
return status;
}
AddSelector(selector);
return status;
}
std::shared_ptr<AclSelector> User::GetRootSelector() {
for (const auto& item : selectors_) {
if (item->HasFlags(static_cast<uint32_t>(AclSelectorFlag::ROOT))) {
return item;
}
}
return nullptr;
}
void User::DescribeUser(std::string* str) {
std::unique_lock wl(mutex_);
if (!aclString_.empty()) {
str->append(aclString_);
return;
}
// flag
for (const auto& item : Acl::UserFlags) {
if (HasFlags(item.second)) {
aclString_ += " ";
aclString_ += item.first;
}
}
// password
for (const auto& item : passwords_) {
aclString_ += " #" + item;
}
// selector
std::string selectorStr;
for (const auto& item : selectors_) {
selectorStr.clear();
item->ACLDescribeSelector(&selectorStr);
if (item->HasFlags(static_cast<uint32_t>(AclSelectorFlag::ROOT))) {
aclString_ += selectorStr;
} else {
aclString_ += fmt::format(" ({})", selectorStr.data() + 1);
}
}
str->append(aclString_);
}
bool User::MatchPassword(const std::string& password) {
std::shared_lock l(mutex_);
return passwords_.find(password) != passwords_.end();
}
void User::GetUserDescribe(CmdRes* res) {
std::shared_lock l(mutex_);
res->AppendArrayLen(12);
res->AppendString("flags");
std::vector<std::string> vector;
for (const auto& item : Acl::UserFlags) {
if (HasFlags(item.second)) {
vector.emplace_back(item.first);
}
}
res->AppendStringVector(vector);
vector.clear();
res->AppendString("passwords");
for (const auto& item : passwords_) {
vector.emplace_back(item);
}
res->AppendStringVector(vector);
size_t i = 0;
for (const auto& selector : selectors_) {
vector.clear();
if (i == 0) { // root selector
selector->ACLDescribeSelector(vector);
for (const auto& item : vector) {
res->AppendString(item);
}
res->AppendString("selectors");
if (selectors_.size() == 1) {
res->AppendArrayLen(0);
}
++i;
continue;
}
if (i == 1) {
res->AppendArrayLen(static_cast<int64_t>(selectors_.size()) - 1);
}
selector->ACLDescribeSelector(vector);
res->AppendStringVector(vector);
++i;
}
}
AclDeniedCmd User::CheckUserPermission(std::shared_ptr<Cmd>& cmd, const PikaCmdArgsType& argv, int8_t& subCmdIndex,
std::string* errKey) {
std::shared_lock l(mutex_);
subCmdIndex = -1;
if (cmd->HasSubCommand()) {
subCmdIndex = cmd->SubCmdIndex(argv[1]);
if (subCmdIndex < 0) {
return AclDeniedCmd::NO_SUB_CMD;
}
}
auto keys = cmd->current_key();
AclDeniedCmd res = AclDeniedCmd::OK;
for (const auto& selector : selectors_) {
res = selector->CheckCanExecCmd(cmd, subCmdIndex, keys, errKey);
if (res == AclDeniedCmd::OK) {
return AclDeniedCmd::OK;
}
}
return res;
}
std::vector<std::string> User::AllChannelKey() {
std::vector<std::string> result;
for (const auto& selector : selectors_) {
for (const auto& item : selector->channels_) {
result.emplace_back(item);
}
}
return result;
}
// class User end
// class Acl
pstd::Status Acl::Initialization() {
AddUser(CreateDefaultUser());
UpdateDefaultUserPassword(g_pika_conf->requirepass());
auto status = LoadUsersAtStartup();
auto u = GetUser(DefaultLimitUser);
bool limit_exist = true;
if (nullptr == u) {
AddUser(CreatedUser(DefaultLimitUser));
limit_exist = false;
}
InitLimitUser(g_pika_conf->GetUserBlackList(), limit_exist);
if (!status.ok()) {
return status;
}
return status;
}
std::shared_ptr<User> Acl::GetUser(const std::string& userName) {
auto u = users_.find(userName);
if (u == users_.end()) {
return nullptr;
}
return u->second;
}
std::shared_ptr<User> Acl::GetUserLock(const std::string& userName) {
std::shared_lock rl(mutex_);
auto u = users_.find(userName);
if (u == users_.end()) {
return nullptr;
}
return u->second;
}
void Acl::AddUser(const std::shared_ptr<User>& user) { users_[user->Name()] = user; }
void Acl::AddUserLock(const std::shared_ptr<User>& user) {
std::unique_lock wl(mutex_);
users_[user->Name()] = user;
}
pstd::Status Acl::LoadUsersAtStartup() {
if (!g_pika_conf->users().empty() && !g_pika_conf->acl_file().empty()) {
return pstd::Status::NotSupported("Only one configuration file and acl file can be used", "");
}
if (g_pika_conf->users().empty()) {
return LoadUserFromFile(g_pika_conf->acl_file());
} else {
return LoadUserConfigured(g_pika_conf->users());
}
}
pstd::Status Acl::LoadUserConfigured(std::vector<std::string>& users) {
std::vector<std::string> userRules;
for (const auto& item : users) {
userRules.clear();
pstd::StringSplit(item, ' ', userRules);
if (userRules.size() < 2) {
return pstd::Status::Error("acl from configuration file read rules error");
}
auto user = GetUser(userRules[0]);
if (user) {
if (user->Name() != DefaultUser) { // only `default` users are allowed to repeat
return pstd::Status::Error("acl user: " + user->Name() + " is repeated");
} else {
user->SetUser("reset");
}
} else {
user = CreatedUser(userRules[0]);
}
std::vector<std::string> aclArgc;
auto subRule = std::vector<std::string>(userRules.begin() + 1, userRules.end());
ACLMergeSelectorArguments(subRule, &aclArgc);
for (const auto& rule : aclArgc) {
auto status = user->SetUser(rule);
if (!status.ok()) {
LOG(ERROR) << "load user from configured file error," << status.ToString();
return status;
}
}
AddUser(user);
}
return pstd::Status().OK();
}
pstd::Status Acl::LoadUserFromFile(std::set<std::string>* toUnAuthUsers) {
std::unique_lock wl(mutex_);
for (const auto& item : users_) {
if (item.first != DefaultUser) {
toUnAuthUsers->insert(item.first);
}
}
auto status = LoadUserFromFile(g_pika_conf->acl_file());
if (!status.ok()) {
return status;
}
return status;
}
pstd::Status Acl::LoadUserFromFile(const std::string& fileName) {
if (fileName.empty()) {
return pstd::Status::OK();
}
std::map<std::string, std::shared_ptr<User>> users;
std::vector<std::string> rules;
bool hasDefaultUser = false;
std::ifstream ruleFile(fileName);
if (!ruleFile) {
return pstd::Status::IOError(fmt::format("open file {} fail"), fileName);
}
DEFER { ruleFile.close(); };
int lineNum = 0;
std::string lineContent;
while (std::getline(ruleFile, lineContent)) {
++lineNum;
if (lineContent.empty()) {
continue;
}
lineContent = pstd::StringTrim(lineContent, "\r\n ");
rules.clear();
pstd::StringSplit(lineContent, ' ', rules);
if (rules.empty()) {
continue;
}
if (rules[0] != "user" || rules.size() < 2) {
LOG(ERROR) << fmt::format("load user from acl file,line:{} '{}' illegal", lineNum, lineContent);
return pstd::Status::Error(fmt::format("line:{} '{}' illegal", lineNum, lineContent));
}
auto user = users.find(rules[1]);
if (user != users.end()) {
// if user is exists, exit
auto err = fmt::format("Duplicate user '{}' found on line {}.", rules[1], lineNum);
LOG(ERROR) << err;
return pstd::Status::Error(err);
}
std::vector<std::string> aclArgc;
auto subRule = std::vector<std::string>(rules.begin() + 2, rules.end());
ACLMergeSelectorArguments(subRule, &aclArgc);
auto u = CreatedUser(rules[1]);
for (const auto& item : aclArgc) {
auto status = u->SetUser(item);
if (!status.ok()) {
LOG(ERROR) << "load user from acl file error," << status.ToString();
return status;
}
}
if (rules[1] == DefaultUser) {
hasDefaultUser = true;
}
users[rules[1]] = u;
}
if (!hasDefaultUser) {
users[DefaultUser] = GetUser(DefaultUser);
}
users_ = std::move(users);
return pstd::Status().OK();
}
void Acl::UpdateDefaultUserPassword(const std::string& pass) {
std::unique_lock wl(mutex_);
auto u = GetUser(DefaultUser);
u->SetUser("resetpass");
if (pass.empty()) {
u->SetUser("nopass");
} else {
u->SetUser(">" + pass);
}
}
void Acl::InitLimitUser(const std::string& bl, bool limit_exist) {
auto pass = g_pika_conf->userpass();
std::vector<std::string> blacklist;
pstd::StringSplit(bl, ',', blacklist);
std::unique_lock wl(mutex_);
auto u = GetUser(DefaultLimitUser);
if (limit_exist) {
if (!bl.empty()) {
u->SetUser("+@all");
for(auto& cmd : blacklist) {
cmd = pstd::StringTrim(cmd, " ");
u->SetUser("-" + cmd);
}
u->SetUser("on");
if (!pass.empty()) {
u->SetUser(">"+pass);
}
}
} else {
if (pass.empty()) {
u->SetUser("nopass");
} else {
u->SetUser(">"+pass);
}
u->SetUser("on");
u->SetUser("+@all");
u->SetUser("~*");
u->SetUser("&*");
for(auto& cmd : blacklist) {
cmd = pstd::StringTrim(cmd, " ");
u->SetUser("-" + cmd);
}
}
}
// bool Acl::CheckUserCanExec(const std::shared_ptr<Cmd>& cmd, const PikaCmdArgsType& argv) { cmd->name(); }
std::shared_ptr<User> Acl::CreateDefaultUser() {
auto defaultUser = std::make_shared<User>(DefaultUser);
defaultUser->SetUser("+@all");
defaultUser->SetUser("~*");
defaultUser->SetUser("&*");
defaultUser->SetUser("on");
defaultUser->SetUser("nopass");
return defaultUser;
}
std::shared_ptr<User> Acl::CreatedUser(const std::string& name) { return std::make_shared<User>(name); }
pstd::Status Acl::SetUser(const std::string& userName, std::vector<std::string>& op) {
auto user = GetUserLock(userName);
std::shared_ptr<User> tempUser = nullptr;
bool add = false;
if (!user) { // if the user not exist, create new user
user = CreatedUser(userName);
add = true;
} else {
tempUser = std::make_shared<User>(*user);
}
std::vector<std::string> aclArgc;
ACLMergeSelectorArguments(op, &aclArgc);
auto status = user->SetUser(aclArgc);
if (!status.ok()) {
return status;
}
if (add) {
AddUserLock(user);
} else {
KillPubsubClientsIfNeeded(tempUser, user);
}
return pstd::Status::OK();
}
void Acl::KillPubsubClientsIfNeeded(const std::shared_ptr<User>& origin, const std::shared_ptr<User>& newUser) {
std::shared_lock l(mutex_);
bool match = true;
for (const auto& newUserSelector : newUser->selectors_) {
if (newUserSelector->HasFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_CHANNELS))) { // new user has all channels
return;
}
}
auto newChKey = newUser->AllChannelKey();
for (const auto& selector : origin->selectors_) {
if (selector->HasFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_CHANNELS))) {
match = false;
break;
}
if (!selector->EqualChannel(newChKey)) {
match = false;
break;
}
}
if (match) {
return;
}
g_pika_server->CheckPubsubClientKill(newUser->Name(), newChKey);
}
uint32_t Acl::GetCommandCategoryFlagByName(const std::string& name) {
for (const auto& item : CommandCategories) {
if (item.first == name) {
return item.second;
}
}
return 0;
}
std::string Acl::GetCommandCategoryFlagByName(const uint32_t category) {
for (const auto& item : CommandCategories) {
if (item.second == category) {
return item.first;
}
}
return "";
}
std::vector<std::string> Acl::GetAllCategoryName() {
std::vector<std::string> result;
result.reserve(CommandCategories.size());
for (const auto& item : CommandCategories) {
result.emplace_back(item.first);
}
return result;
}
void Acl::ACLMergeSelectorArguments(std::vector<std::string>& argv, std::vector<std::string>* merged) {
bool openBracketStart = false;
std::string selector;
for (const auto& item : argv) {
if (item[0] == '(' && item[item.size() - 1] != ')') {
selector = item;
openBracketStart = true;
continue;
}
if (openBracketStart) {
selector += " " + item;
if (item[item.size() - 1] == ')') {
openBracketStart = false;
merged->emplace_back(selector);
}
continue;
}
merged->emplace_back(item);
}
}
std::shared_ptr<User> Acl::Auth(const std::string& userName, const std::string& password) {
std::shared_lock l(mutex_);
auto user = GetUser(userName);
if (!user) {
return nullptr;
}
if (user->HasFlags(static_cast<uint32_t>(AclUserFlag::DISABLED))) {
return nullptr;
}
if (user->HasFlags(static_cast<uint32_t>(AclUserFlag::NO_PASS))) {
return user;
}
if (user->MatchPassword(pstd::sha256(password))) {
return user;
}
return nullptr;
}
std::vector<std::string> Acl::Users() {
std::shared_lock l(mutex_);
std::vector<std::string> result;
result.reserve(users_.size());
for (const auto& item : users_) {
result.emplace_back(item.first);
}
return result;
}
void Acl::DescribeAllUser(std::vector<std::string>* content) {
std::shared_lock l(mutex_);
content->reserve(users_.size());
for (const auto& item : users_) {
std::string saveContent;
saveContent += "user ";
saveContent += item.first;
item.second->DescribeUser(&saveContent);
content->emplace_back(saveContent);
}
}
pstd::Status Acl::SaveToFile() {
std::string aclFileName = g_pika_conf->acl_file();
if (aclFileName.empty()) {
LOG(ERROR) << "save user to acl file, file name is empty";
return pstd::Status::Error("acl file name is empty");
}
std::unique_lock wl(mutex_);
std::unique_ptr<pstd::WritableFile> file;
const std::string tmpFile = aclFileName + ".tmp";
auto status = pstd::NewWritableFile(tmpFile, file);
if (!status.ok()) {
auto error = fmt::format("open acl user file:{} fail, error:{}", aclFileName, status.ToString());
LOG(ERROR) << error;
return pstd::Status::Error(error);
}
std::string saveContent;
for (const auto& item : users_) {
saveContent += "user ";
saveContent += item.first;
item.second->DescribeUser(&saveContent);
saveContent += "\n";
}
file->Append(saveContent);
file->Sync();
file->Close();
if (pstd::RenameFile(tmpFile, aclFileName) < 0) { // rename fail
return pstd::Status::Error("save acl rule to file fail. specific information see pika log");
}
return pstd::Status::OK();
}
std::set<std::string> Acl::DeleteUser(const std::vector<std::string>& userNames) {
std::unique_lock wl(mutex_);
std::set<std::string> delUserNames;
for (const auto& userName : userNames) {
if (users_.erase(userName)) {
delUserNames.insert(userName);
}
}
return delUserNames;
}
std::array<std::pair<std::string, uint32_t>, 21> Acl::CommandCategories = {{
{"keyspace", static_cast<uint32_t>(AclCategory::KEYSPACE)},
{"read", static_cast<uint32_t>(AclCategory::READ)},
{"write", static_cast<uint32_t>(AclCategory::WRITE)},
{"set", static_cast<uint32_t>(AclCategory::SET)},
{"sortedset", static_cast<uint32_t>(AclCategory::SORTEDSET)},
{"list", static_cast<uint32_t>(AclCategory::LIST)},
{"hash", static_cast<uint32_t>(AclCategory::HASH)},
{"string", static_cast<uint32_t>(AclCategory::STRING)},
{"bitmap", static_cast<uint32_t>(AclCategory::BITMAP)},
{"hyperloglog", static_cast<uint32_t>(AclCategory::HYPERLOGLOG)},
{"geo", static_cast<uint32_t>(AclCategory::GEO)},
{"stream", static_cast<uint32_t>(AclCategory::STREAM)},
{"pubsub", static_cast<uint32_t>(AclCategory::PUBSUB)},
{"admin", static_cast<uint32_t>(AclCategory::ADMIN)},
{"fast", static_cast<uint32_t>(AclCategory::FAST)},
{"slow", static_cast<uint32_t>(AclCategory::SLOW)},
{"blocking", static_cast<uint32_t>(AclCategory::BLOCKING)},
{"dangerous", static_cast<uint32_t>(AclCategory::DANGEROUS)},
{"connection", static_cast<uint32_t>(AclCategory::CONNECTION)},
{"transaction", static_cast<uint32_t>(AclCategory::TRANSACTION)},
{"scripting", static_cast<uint32_t>(AclCategory::SCRIPTING)},
}};
std::array<std::pair<std::string, uint32_t>, 3> Acl::UserFlags = {{
{"on", static_cast<uint32_t>(AclUserFlag::ENABLED)},
{"off", static_cast<uint32_t>(AclUserFlag::DISABLED)},
{"nopass", static_cast<uint32_t>(AclUserFlag::NO_PASS)},
}};
std::array<std::pair<std::string, uint32_t>, 3> Acl::SelectorFlags = {{
{"allkeys", static_cast<uint32_t>(AclSelectorFlag::ALL_KEYS)},
{"allchannels", static_cast<uint32_t>(AclSelectorFlag::ALL_CHANNELS)},
{"allcommands", static_cast<uint32_t>(AclSelectorFlag::ALL_COMMANDS)},
}};
const std::string Acl::DefaultUser = "default";
const std::string Acl::DefaultLimitUser = "limit";
const int64_t Acl::LogGroupingMaxTimeDelta = 60000;
void Acl::AddLogEntry(int32_t reason, int32_t context, const std::string& username, const std::string& object,
const std::string& cInfo) {
int64_t nowUnix =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count();
{
std::unique_lock wl(mutex_);
for (const auto& item : logEntries_) {
if (item->Match(reason, context, nowUnix, object, username)) {
item->AddEntry(cInfo, nowUnix);
return;
}
}
auto entry = std::make_unique<ACLLogEntry>(reason, context, object, username, nowUnix, cInfo);
logEntries_.push_front(std::move(entry));
auto maxLen = g_pika_conf->acl_log_max_len();
if (logEntries_.size() > maxLen) { // remove overflow log
if (maxLen == 0) {
logEntries_.clear();
} else {
logEntries_.erase(std::next(logEntries_.begin(), maxLen), logEntries_.end());
}
}
}
}
void Acl::GetLog(long count, CmdRes* res) {
std::shared_lock rl(mutex_);
auto size = static_cast<long>(logEntries_.size());
if (count == -1) {
count = size;
}
if (count > size) {
count = size;
}
if (count == 0) {
res->AppendArrayLen(0);
return;
}
std::vector<std::string> items;
res->AppendArrayLen(static_cast<int64_t>(count));
items.reserve(14);
for (const auto& item : logEntries_) {
items.clear();
item->GetReplyInfo(&items);
res->AppendStringVector(items);
count--;
if (count == 0) {
break;
}
}
}
void Acl::ResetLog() {
std::unique_lock wl(mutex_);
logEntries_.clear();
}
// class Acl end
// class ACLLogEntry
bool ACLLogEntry::Match(int32_t reason, int32_t context, int64_t ctime, const std::string& object,
const std::string& username) {
if (reason_ != reason) {
return false;
}
if (context_ != context) {
return false;
}
auto delta = ctime_ - ctime;
if (delta > Acl::LogGroupingMaxTimeDelta) {
return false;
};
if (object_ != object) {
return false;
}
if (username_ != username) {
return false;
}
return true;
}
void ACLLogEntry::AddEntry(const std::string& cinfo, u_int64_t ctime) {
cinfo_ = cinfo;
ctime_ = ctime;
++count_;
}
void ACLLogEntry::GetReplyInfo(std::vector<std::string>* vector) {
vector->emplace_back("count");
vector->emplace_back(std::to_string(count_));
vector->emplace_back("reason");
switch (reason_) {
case static_cast<int32_t>(AclDeniedCmd::CMD):
vector->emplace_back("command");
break;
case static_cast<int32_t>(AclDeniedCmd::KEY):
vector->emplace_back("key");
break;
case static_cast<int32_t>(AclDeniedCmd::CHANNEL):
vector->emplace_back("channel");
break;
case static_cast<int32_t>(AclDeniedCmd::NO_AUTH):
vector->emplace_back("auth");
break;
default:
vector->emplace_back("unknown");
break;
}
vector->emplace_back("context");
switch (context_) {
case static_cast<int32_t>(AclLogCtx::TOPLEVEL):
vector->emplace_back("toplevel");
break;
case static_cast<int32_t>(AclLogCtx::MULTI):
vector->emplace_back("multi");
break;
case static_cast<int32_t>(AclLogCtx::LUA):
vector->emplace_back("lua");
break;
default:
vector->emplace_back("unknown");
break;
}
vector->emplace_back("object");
vector->emplace_back(object_);
vector->emplace_back("username");
vector->emplace_back(username_);
vector->emplace_back("age-seconds");
int64_t nowUnix =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count();
char latitude[32];
pstd::d2string(latitude, 32, static_cast<double>(nowUnix - ctime_) / 1000);
vector->emplace_back(latitude);
vector->emplace_back("client-info");
vector->emplace_back(cinfo_);
}
// class ACLLogEntry end
// class AclSelector
AclSelector::AclSelector(uint32_t flag) : flags_(flag) {
if (g_pika_conf->acl_pubsub_default()) {
AddFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_CHANNELS));
}
}
AclSelector::AclSelector(const AclSelector& selector) {
flags_ = selector.Flags();
allowedCommands_ = selector.allowedCommands_;
subCommand_ = selector.subCommand_;
channels_ = selector.channels_;
commandRules_ = selector.commandRules_;
for (const auto& item : selector.patterns_) {
auto pattern = std::make_shared<AclKeyPattern>();
pattern->flags = item->flags;
pattern->pattern = item->pattern;
patterns_.emplace_back(pattern);
}
}
pstd::Status AclSelector::SetSelector(const std::string& op) {
if (!strcasecmp(op.data(), "allkeys") || op == "~*") {
AddFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_KEYS));
patterns_.clear();
} else if (!strcasecmp(op.data(), "resetkeys")) {
DecFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_KEYS));
patterns_.clear();
} else if (!strcasecmp(op.data(), "allchannels") || !strcasecmp(op.data(), "&*")) {
AddFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_CHANNELS));
channels_.clear();
} else if (!strcasecmp(op.data(), "resetchannels")) {
DecFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_CHANNELS));
channels_.clear();
} else if (!strcasecmp(op.data(), "allcommands") || !strcasecmp(op.data(), "+@all")) {
SetAllCommandSelector();
} else if (!strcasecmp(op.data(), "nocommands") || !strcasecmp(op.data(), "-@all")) {
RestAllCommandSelector();
} else if (op[0] == '~' || op[0] == '%') {
if (HasFlags(static_cast<int>(AclSelectorFlag::ALL_KEYS))) {
return pstd::Status::Error(
fmt::format("Error in ACL SETUSER modifier '{}': Adding a pattern after the * "
"pattern (or the 'allkeys' flag) is not valid and does not have any effect."
" Try 'resetkeys' to start with an empty list of patterns",
op));
}
int flags = 0;
size_t offset = 1;
if (op[0] == '%') {
for (; offset < op.size(); offset++) {
if (toupper(op[offset]) == 'R' && !(flags & static_cast<int>(AclPermission::READ))) {
flags |= static_cast<int>(AclPermission::READ);
} else if (toupper(op[offset]) == 'W' && !(flags & static_cast<int>(AclPermission::WRITE))) {
flags |= static_cast<int>(AclPermission::WRITE);
} else if (op[offset] == '~') {
offset++;
break;
} else {
return pstd::Status::Error("Syntax error");
}
}
} else {
flags = static_cast<int>(AclPermission::ALL);
}
if (pstd::isspace(op)) {
return pstd::Status::Error("Syntax error");
}
InsertKeyPattern(op.substr(offset, std::string::npos), flags);
DecFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_KEYS));
} else if (op[0] == '&') {
if (HasFlags(static_cast<uint32_t>(AclSelectorFlag::ALL_CHANNELS))) {
return pstd::Status::Error(
"Adding a pattern after the * pattern (or the 'allchannels' flag) is not valid and does not have any effect. "
"Try 'resetchannels' to start with an empty list of channels");
}
if (pstd::isspace(op)) {
return pstd::Status::Error("Syntax error");
}