/
AuditHook.php
451 lines (401 loc) · 15.2 KB
/
AuditHook.php
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
<?php
namespace SilverStripe\Auditor;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Control\Email\Email;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\Connect\Database;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataObjectSchema;
use SilverStripe\ORM\DB;
use SilverStripe\Security\Group;
use SilverStripe\Security\Member;
use SilverStripe\Security\PermissionRole;
use SilverStripe\Security\PermissionRoleCode;
use SilverStripe\Security\Security;
/**
* Provides logging hooks that are inserted into Framework objects.
*/
class AuditHook extends DataExtension
{
protected function getAuditLogger()
{
// We cannot use the 'dependencies' private property, because this will prevent us
// from injecting a mock logger for testing. This is because by the time the testing framework
// is instantiated, the part of the object graph where AuditLogger lives has already been created.
// In other words, Framework does not permit hooking in early enough to adjust the graph when
// 'dependencies' is used :-(
return Injector::inst()->get('AuditLogger');
}
/**
* This will bind a new class dynamically so we can hook into manipulation
* and capture it. It creates a new PHP file in the temp folder, then
* loads it and sets it as the active DB class.
*
* @deprecated 2.1.0 Use ProxyDBExtension with the tractorcow/silverstripe-proxy-db module instead
*/
public static function bind_manipulation_capture()
{
Deprecation::notice('2.1.0', 'Use ProxyDBExtension with the tractorcow/silverstripe-proxy-db module instead');
$current = DB::get_conn();
if (!$current || !$current->getConnector()->getSelectedDatabase() || @$current->isManipulationLoggingCapture) {
return;
} // If not yet set, or its already captured, just return
$type = get_class($current);
$sanitisedType = str_replace('\\', '_', $type ?? '');
$file = TEMP_FOLDER . "/.cache.CLC.$sanitisedType";
$dbClass = 'AuditLoggerManipulateCapture_' . $sanitisedType;
if (!is_file($file ?? '')) {
file_put_contents($file ?? '', "<?php
class $dbClass extends $type
{
public \$isManipulationLoggingCapture = true;
public function manipulate(\$manipulation)
{
\SilverStripe\Auditor\AuditHook::handle_manipulation(\$manipulation);
return parent::manipulate(\$manipulation);
}
}
");
}
require_once $file;
/** @var Database $captured */
$captured = new $dbClass();
$captured->setConnector($current->getConnector());
$captured->setQueryBuilder($current->getQueryBuilder());
$captured->setSchemaManager($current->getSchemaManager());
// The connection might have had it's name changed (like if we're currently in a test)
$captured->selectDatabase($current->getConnector()->getSelectedDatabase());
DB::set_conn($captured);
}
public static function handle_manipulation($manipulation)
{
$auditLogger = Injector::inst()->get('AuditLogger');
$currentMember = Security::getCurrentUser();
if (!($currentMember && $currentMember->exists())) {
return false;
}
/** @var DataObjectSchema $schema */
$schema = DataObject::getSchema();
// The tables that we watch for manipulation on
$watchedTables = [
$schema->tableName(Member::class),
$schema->tableName(Group::class),
$schema->tableName(PermissionRole::class),
$schema->tableName(PermissionRoleCode::class),
];
foreach ($manipulation as $table => $details) {
if (!in_array($details['command'], ['update', 'insert'])) {
continue;
}
// logging writes to specific tables (just not when logging in, as it's noise)
if (in_array($table, $watchedTables ?? [])
&& !preg_match('/Security/', @$_SERVER['REQUEST_URI'])
&& isset($details['id'])
) {
$className = $schema->tableClass($table);
$data = $className::get()->byID($details['id']);
if (!$data) {
continue;
}
$actionText = 'modified '.$table;
$extendedText = '';
if ($table === $schema->tableName(Group::class)) {
$extendedText = sprintf(
'Effective permissions: %s',
implode(', ', $data->Permissions()->column('Code'))
);
}
if ($table === $schema->tableName(PermissionRole::class)) {
$extendedText = sprintf(
'Effective groups: %s, Effective permissions: %s',
implode(', ', $data->Groups()->column('Title')),
implode(', ', $data->Codes()->column('Code'))
);
}
if ($table === $schema->tableName(PermissionRoleCode::class)) {
$extendedText = sprintf(
'Effective code: %s',
$data->Code
);
}
if ($table === $schema->tableName(Member::class)) {
$extendedText = sprintf(
'Effective groups: %s',
implode(', ', $data->Groups()->column('Title'))
);
}
$auditLogger->info(sprintf(
'"%s" (ID: %s) %s (ID: %s, ClassName: %s, Title: "%s", %s)',
$currentMember->Email ?: $currentMember->Title,
$currentMember->ID,
$actionText,
$details['id'],
$data->ClassName,
$data->Title,
$extendedText
));
}
// log PermissionRole being added to a Group
if ($table === $schema->tableName(Group::class) . '_Roles') {
$role = PermissionRole::get()->byId($details['fields']['PermissionRoleID']);
$group = Group::get()->byId($details['fields']['GroupID']);
// if the permission role isn't already applied to the group
if (!DB::query(sprintf(
'SELECT "ID" FROM "Group_Roles" WHERE "GroupID" = %s AND "PermissionRoleID" = %s',
$details['fields']['GroupID'],
$details['fields']['PermissionRoleID']
))->value()) {
$auditLogger->info(sprintf(
'"%s" (ID: %s) added PermissionRole "%s" (ID: %s) to Group "%s" (ID: %s)',
$currentMember->Email ?: $currentMember->Title,
$currentMember->ID,
$role->Title,
$role->ID,
$group->Title,
$group->ID
));
}
}
// log Member added to a Group
if ($table === $schema->tableName(Group::class) . '_Members') {
$member = Member::get()->byId($details['fields']['MemberID']);
$group = Group::get()->byId($details['fields']['GroupID']);
// if the user isn't already in the group, log they've been added
if (!DB::query(sprintf(
'SELECT "ID" FROM "Group_Members" WHERE "GroupID" = %s AND "MemberID" = %s',
$details['fields']['GroupID'],
$details['fields']['MemberID']
))->value()) {
$auditLogger->info(sprintf(
'"%s" (ID: %s) added Member "%s" (ID: %s) to Group "%s" (ID: %s)',
$currentMember->Email ?: $currentMember->Title,
$currentMember->ID,
$member->Email ?: $member->Title,
$member->ID,
$group->Title,
$group->ID
));
}
}
}
}
/**
* Log a record being published.
*/
public function onAfterPublish(&$original)
{
$member = Security::getCurrentUser();
if (!$member || !$member->exists()) {
return false;
}
$effectiveViewerGroups = '';
if ($this->owner->CanViewType === 'OnlyTheseUsers') {
$originalViewerGroups = $original ? $original->ViewerGroups()->column('Title') : [];
$effectiveViewerGroups = implode(', ', $originalViewerGroups);
}
if (!$effectiveViewerGroups) {
$effectiveViewerGroups = $this->owner->CanViewType;
}
$effectiveEditorGroups = '';
if ($this->owner->CanEditType === 'OnlyTheseUsers') {
$originalEditorGroups = $original ? $original->EditorGroups()->column('Title') : [];
$effectiveEditorGroups = implode(', ', $originalEditorGroups);
}
if (!$effectiveEditorGroups) {
$effectiveEditorGroups = $this->owner->CanEditType;
}
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) published %s "%s" (ID: %s, Version: %s, ClassName: %s, Effective ViewerGroups: %s, '
. 'Effective EditorGroups: %s)',
$member->Email ?: $member->Title,
$member->ID,
$this->owner->singular_name(),
$this->owner->Title,
$this->owner->ID,
$this->owner->Version,
$this->owner->ClassName,
$effectiveViewerGroups,
$effectiveEditorGroups
));
}
/**
* Log a record being unpublished.
*/
public function onAfterUnpublish()
{
$member = Security::getCurrentUser();
if (!$member || !$member->exists()) {
return false;
}
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) unpublished %s "%s" (ID: %s)',
$member->Email ?: $member->Title,
$member->ID,
$this->owner->singular_name(),
$this->owner->Title,
$this->owner->ID
));
}
/**
* Log a record being reverted to live.
*/
public function onAfterRevertToLive()
{
$member = Security::getCurrentUser();
if (!$member || !$member->exists()) {
return false;
}
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) reverted %s "%s" (ID: %s) to it\'s live version (#%d)',
$member->Email ?: $member->Title,
$member->ID,
$this->owner->singular_name(),
$this->owner->Title,
$this->owner->ID,
$this->owner->Version
));
}
/**
* Log a record being duplicated.
*/
public function onAfterDuplicate()
{
$member = Security::getCurrentUser();
if (!$member || !$member->exists()) {
return false;
}
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) duplicated %s "%s" (ID: %s)',
$member->Email ?: $member->Title,
$member->ID,
$this->owner->singular_name(),
$this->owner->Title,
$this->owner->ID
));
}
/**
* Log a record being deleted.
*/
public function onAfterDelete()
{
$member = Security::getCurrentUser();
if (!$member || !$member->exists()) {
return false;
}
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) deleted %s "%s" (ID: %s)',
$member->Email ?: $member->Title,
$member->ID,
$this->owner->singular_name(),
$this->owner->Title,
$this->owner->ID
));
}
/**
* Log a record being restored to stage.
*/
public function onAfterRestoreToStage()
{
$member = Security::getCurrentUser();
if (!$member || !$member->exists()) {
return false;
}
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) restored %s "%s" to stage (ID: %s)',
$member->Email ?: $member->Title,
$member->ID,
$this->owner->singular_name(),
$this->owner->Title,
$this->owner->ID
));
}
/**
* Log successful login attempts.
*/
public function afterMemberLoggedIn()
{
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) successfully logged in',
$this->owner->Email ?: $this->owner->Title,
$this->owner->ID
));
}
/**
* Log successfully restored sessions from "remember me" cookies ("auto login").
*/
public function memberAutoLoggedIn()
{
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) successfully restored autologin session',
$this->owner->Email ?: $this->owner->Title,
$this->owner->ID
));
}
/**
* Log failed login attempts.
*/
public function authenticationFailed($data)
{
// LDAP authentication uses a "Login" POST field instead of Email.
$login = isset($data['Login'])
? $data['Login']
: (isset($data[Email::class]) ? $data[Email::class] : '');
if (empty($login)) {
return $this->getAuditLogger()->warning(
'Could not determine username/email of failed authentication. '.
'This could be due to login form not using Email or Login field for POST data.'
);
}
$this->getAuditLogger()->info(sprintf('Failed login attempt using email "%s"', $login));
}
/**
* @deprecated 2.1.0 Use tractorcow/silverstripe-proxy-db instead
*/
public function onBeforeInit()
{
Deprecation::withNoReplacement(function () {
Deprecation::notice('2.1.0', 'Use tractorcow/silverstripe-proxy-db instead');
});
// no-op
}
/**
* Log permission failures (where the status is set after init of page).
*/
public function onAfterInit()
{
// Suppress errors if dev/build necessary
if (!Security::database_is_ready()) {
return false;
}
$currentMember = Security::getCurrentUser();
if (!$currentMember || !$currentMember->exists()) {
return false;
}
$statusCode = $this->owner->getResponse()->getStatusCode();
if (substr($statusCode ?? '', 0, 1) == '4') {
$this->logPermissionDenied($statusCode, $currentMember);
}
}
protected function logPermissionDenied($statusCode, $member)
{
$this->getAuditLogger()->info(sprintf(
'HTTP code %s - "%s" (ID: %s) is denied access to %s',
$statusCode,
$member->Email ?: $member->Title,
$member->ID,
$_SERVER['REQUEST_URI']
));
}
/**
* Log successful logout.
*/
public function afterMemberLoggedOut()
{
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) successfully logged out',
$this->owner->Email ?: $this->owner->Title,
$this->owner->ID
));
}
}