/
testauditd.cc
401 lines (355 loc) · 13 KB
/
testauditd.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
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include <auditd/couchbase_audit_events.h>
#include <folly/portability/GTest.h>
#include <getopt.h>
#include <logger/logger.h>
#include <memcached/audit_interface.h>
#include <memcached/connection_iface.h>
#include <memcached/cookie_iface.h>
#include <memcached/rbac.h>
#include <nlohmann/json.hpp>
#include <platform/dirutils.h>
#include <platform/socket.h>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <limits>
#include <mutex>
#include <thread>
#include "auditd/src/audit.h"
#include "auditd/src/auditconfig.h"
#include "auditd/tests/mock_auditconfig.h"
// The event descriptor file is normally stored in the directory named
// auditd relative to the binary... let's just use that as the default
// and allow the user to override it with -e
static std::string event_descriptor("auditd");
class AuditMockConnection : public ConnectionIface {
public:
void scheduleDcpStep() override {
throw std::runtime_error(
"AuditMockConnection::scheduleDcpStep not implemented");
}
ConnectionPriority getPriority() const override {
throw std::runtime_error(
"AuditMockConnection::getPriority not implemented");
}
void setPriority(ConnectionPriority value) override {
throw std::runtime_error(
"AuditMockConnection::setPriority not implemented");
}
};
class AuditMockCookie : public CookieIface {
public:
ConnectionIface& getConnectionIface() override {
return connection;
}
uint32_t getConnectionId() const override {
return 0;
}
void notifyIoComplete(cb::engine_errc status) override {
std::lock_guard<std::mutex> lock(mutex);
ready = true;
cond.notify_one();
}
bool isMutationExtrasSupported() const override {
return false;
}
bool isCollectionsSupported() const override {
return false;
}
bool isDatatypeSupported(
protocol_binary_datatype_t datatype) const override {
return false;
}
cb::rbac::PrivilegeAccess testPrivilege(
cb::rbac::Privilege privilege,
std::optional<ScopeID> sid,
std::optional<CollectionID> cid) const override {
return cb::rbac::PrivilegeAccess(cb::rbac::PrivilegeAccess::Status::Ok);
}
cb::rbac::PrivilegeAccess checkForPrivilegeAtLeastInOneCollection(
cb::rbac::Privilege privilege) const override {
return cb::rbac::PrivilegeAccess(cb::rbac::PrivilegeAccess::Status::Ok);
}
std::string_view getInflatedInputPayload() const override {
return {};
}
void setCurrentCollectionInfo(ScopeID sid,
CollectionID cid,
uint64_t manifestUid,
bool metered) override {
}
bool checkThrottle(size_t pendingRBytes, size_t pendingWBytes) override {
return false;
}
void sendResponse(cb::engine_errc status, std::string_view value) override {
throw std::runtime_error("AuditMockCookie::sendResponse unimplemented");
}
/// Wait for the cookie to be notified
void wait() {
// we have to wait
std::unique_lock<std::mutex> lk(mutex);
if (ready) {
return;
}
cond.wait(lk, [this] { return ready; });
ready = false;
}
protected:
AuditMockConnection connection;
std::mutex mutex;
std::condition_variable cond;
bool ready = false;
};
class AuditDaemonTest
: public ::testing::TestWithParam<std::tuple<bool, bool>> {
public:
static void SetUpTestCase() {
// create the test directory
testdir = cb::io::mktemp("auditd-test-");
try {
cb::io::rmrf(testdir);
} catch (std::system_error& e) {
if (e.code() != std::error_code(ENOENT, std::system_category())) {
throw e;
}
}
cb::io::mkdirp(testdir);
// create the name of the configuration file to use
cfgfile = cb::io::mktemp("test_audit-");
try {
cb::io::rmrf(cfgfile);
} catch (std::system_error& e) {
if (e.code() != std::error_code(ENOENT, std::system_category())) {
throw e;
}
}
// Start the audit daemon
auditHandle = cb::audit::create_audit_daemon({});
if (!auditHandle) {
throw std::runtime_error(
"AuditDaemonTest::SetUpTestCase() Failed to start audit "
"daemon");
}
}
static void TearDownTestCase() {
auditHandle.reset();
cb::io::rmrf(testdir);
cb::io::rmrf(cfgfile);
}
protected:
void config_auditd(const std::string& fname) {
AuditMockCookie cookie;
if (auditHandle->configure_auditdaemon(fname, cookie)) {
cookie.wait();
} else {
std::cerr << "initialize audit daemon: FAILED" << std::endl;
exit(EXIT_FAILURE);
};
}
void SetUp() override {
config.set_descriptors_path(event_descriptor);
config.set_rotate_size(2000);
config.set_rotate_interval(900);
config.set_log_directory(testdir);
config.set_auditd_enabled(false);
config.set_uuid("12345");
config.set_version(2);
cb::io::rmrf(testdir);
cb::io::mkdirp(testdir);
}
void enable() {
config.set_auditd_enabled(true);
cb::io::rmrf(testdir);
cb::io::mkdirp(testdir);
configure();
}
void TearDown() override {
config.set_auditd_enabled(false);
configure();
}
void configure() {
FILE* fp = fopen(cfgfile.c_str(), "w");
ASSERT_NE(nullptr, fp);
ASSERT_GE(fprintf(fp, "%s\n", config.to_json().dump().c_str()), 0);
ASSERT_NE(-1, fclose(fp));
config_auditd(cfgfile);
}
void assertNumberOfFiles(size_t num) {
auto vec = cb::io::findFilesContaining(testdir, "");
ASSERT_EQ(num, vec.size());
}
// Test to see if a given string exists in the audit log
// @param searchString string to atempt to find in the audit log
// @returns bool return true if searchString is found in the audit log,
// otherwise return false
bool existsInAuditLog(const std::string& searchString) {
// confirm that the audit file exists in the directory.
assertNumberOfFiles(1);
auto vec = cb::io::findFilesContaining(testdir, "");
std::ifstream auditFile;
auditFile.open(vec.front().c_str());
std::string line;
while (std::getline(auditFile, line)) {
if (line.find(searchString) != std::string::npos) {
auditFile.close();
return true;
}
}
auditFile.close();
return false;
}
MockAuditConfig config;
static cb::audit::UniqueAuditPtr auditHandle;
static std::string testdir;
static std::string cfgfile;
};
std::string AuditDaemonTest::testdir;
std::string AuditDaemonTest::cfgfile;
cb::audit::UniqueAuditPtr AuditDaemonTest::auditHandle;
TEST_P(AuditDaemonTest, StartupDisabledDontCreateFiles) {
configure();
assertNumberOfFiles(0);
}
TEST_P(AuditDaemonTest, StartupEnableCreateFile) {
enable();
assertNumberOfFiles(1);
}
class AuditDaemonFilteringTest : public AuditDaemonTest {
protected:
void SetUp() override {
AuditDaemonTest::SetUp();
// Add the userid : {"source" : "internal", "user" : "johndoe"}
// to the disabled users list
nlohmann::json disabled_userids = nlohmann::json::array();
nlohmann::json userIdRoot;
userIdRoot["source"] = "internal";
userIdRoot["user"] = "johndoe";
disabled_userids.push_back(userIdRoot);
config.public_set_disabled_userids(disabled_userids);
}
};
/**
* Tests the filtering of audit events by user.
* An attempt is made to add the new event to the audit log (using
* put_audit_event) with a real_userid:user = "johndoe". Depending on the
* global filter setting and the event's filtering permitted attribute, the
* "johndoe" event may or may not appear in the audit log.
*/
TEST_P(AuditDaemonFilteringTest, AuditFilteringTest) {
bool globalFilterSetting = std::get<0>(GetParam());
bool eventFilteringPermitted = std::get<1>(GetParam());
bool foundJohndoe{false};
auto id = eventFilteringPermitted ? MEMCACHED_AUDIT_INVALID_PACKET
: MEMCACHED_AUDIT_AUTHENTICATION_FAILED;
const std::string payloadjohndoe = R"({"id": )" + std::to_string(id) +
R"(, "timestamp": "test", "real_userid":
{"source": "internal", "user": "johndoe"}})";
const std::string payloadanother = R"({"id": )" + std::to_string(id) +
R"(, "timestamp": "test", "real_userid":
{"source": "internal", "user": "another"}})";
config.set_filtering_enabled(globalFilterSetting);
enable();
// generate the event with real_userid:user = johndoe
auditHandle->put_event(id, payloadjohndoe);
// generate the event with real_userid:user = another
auditHandle->put_event(id, payloadanother);
// Check the audit log exists
assertNumberOfFiles(1);
// wait up to 10 seconds for "another" to appear in the audit log
uint16_t waitIteration = 0;
while (!existsInAuditLog("another") && (waitIteration < 200)) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
waitIteration++;
}
// Check to see if "johndoe" exists or not in the audit log
foundJohndoe = existsInAuditLog("johndoe");
// If filtering is enabled and the event is permitted to be filtered
// then the event should not be found in the audit log.
if (globalFilterSetting && eventFilteringPermitted) {
EXPECT_FALSE(foundJohndoe);
} else {
// exists in audit log
EXPECT_TRUE(foundJohndoe);
}
}
// Check to see if "uuid":"12345" is reported
TEST_F(AuditDaemonTest, UuidTest) {
enable();
// Check the audit log exists
auto vec = cb::io::findFilesContaining(testdir, "");
assertNumberOfFiles(1);
// wait up to 10 seconds for "uuid" to appear in the audit log
uint16_t waitIteration = 0;
while (!existsInAuditLog("uuid") && (waitIteration < 200)) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
waitIteration++;
}
EXPECT_TRUE(existsInAuditLog(R"("uuid")"))
<< "uuid attribute is missing from audit log";
EXPECT_TRUE(existsInAuditLog(R"("uuid":"12345")"))
<< "Wrong uuid in the audit log";
}
// Check to see if "version":2 is reported
TEST_F(AuditDaemonTest, VersionTest) {
enable();
// Check the audit log exists
auto vec = cb::io::findFilesContaining(testdir, "");
assertNumberOfFiles(1);
// wait up to 10 seconds for "version" to appear in the audit log
uint16_t waitIteration = 0;
while (!existsInAuditLog("version") && (waitIteration < 200)) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
waitIteration++;
}
EXPECT_TRUE(existsInAuditLog(R"("version")"))
<< "version attribute is missing from audit log";
EXPECT_TRUE(existsInAuditLog(R"("version":2)"))
<< "Wrong version in the audit log";
}
int main(int argc, char** argv) {
cb::logger::createConsoleLogger();
::testing::InitGoogleTest(&argc, argv);
// required for gethostname(); normally called by memcached's main()
cb::net::initialize();
int cmd;
while ((cmd = getopt(argc, argv, "e:")) != EOF) {
switch (cmd) {
case 'e':
event_descriptor = optarg;
break;
default:
std::cerr << "Usage: " << argv[0] << " [-e]" << std::endl
<< "\t-e\tPath to audit_events.json" << std::endl;
return 1;
}
}
std::string filename = event_descriptor + "/audit_events.json";
FILE* fp = fopen(filename.c_str(), "r");
if (fp == nullptr) {
std::cerr << "Failed to open: " << filename << std::endl;
return EXIT_FAILURE;
}
fclose(fp);
return RUN_ALL_TESTS();
}
static std::vector<bool> allFilteringOptions = {{true, false}};
INSTANTIATE_TEST_SUITE_P(bool,
AuditDaemonTest,
::testing::Values(std::make_tuple(true, true)));
INSTANTIATE_TEST_SUITE_P(
bool,
AuditDaemonFilteringTest,
::testing::Combine(::testing::ValuesIn(allFilteringOptions),
::testing::ValuesIn(allFilteringOptions)));