forked from pgaudit/pgaudit
-
Notifications
You must be signed in to change notification settings - Fork 4
/
pgaudit.c
1895 lines (1601 loc) · 56.5 KB
/
pgaudit.c
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
/*------------------------------------------------------------------------------
* pgaudit.c
*
* An audit logging extension for PostgreSQL. Provides detailed logging classes,
* object level logging, and fully-qualified object names for all DML and DDL
* statements where possible (See pgaudit.sgml for details).
*
* Copyright (c) 2014-2015, PostgreSQL Global Development Group
* Copyright (c) 2017, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
*
* IDENTIFICATION
* pgaudit/pgaudit.c
*------------------------------------------------------------------------------
*/
#include "postgres.h"
#include <time.h>
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_class.h"
#include "catalog/namespace.h"
#include "commands/dbcommands.h"
#include "catalog/pg_proc.h"
#include "commands/event_trigger.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "miscadmin.h"
#include "libpq/auth.h"
#include "nodes/nodes.h"
#include "storage/proc.h"
#include "tcop/utility.h"
#include "tcop/deparse_utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/guc.h"
#include "utils/guc_tables.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "pgaudit.h"
#include "config.h"
/* for GUC check */
extern bool Log_connections;
extern bool Log_disconnections;
extern bool log_replication_commands;;
int emitAuditLogCalled = 0;
PG_MODULE_MAGIC;
void _PG_init(void);
PG_FUNCTION_INFO_V1(pgaudit_ddl_command_end);
PG_FUNCTION_INFO_V1(pgaudit_sql_drop);
/*
* GUC variable for pgaudit.config_file
*
* Administrators can specify the path to the configuration file.
*/
char *config_file = NULL;
/*
* Audit type, which is responsbile for the log message
*/
#define AUDIT_TYPE_OBJECT "OBJECT"
#define AUDIT_TYPE_SESSION "SESSION"
/*
* Command, used for SELECT/DML and function calls.
*
* We hook into the executor, but we do not have access to the parsetee there.
* Therefore we can't simply call CreateCommandTag() to get the command and have
* to build it ourselves based on what information we do have.
*
* These should be updated if new commands are added to what the exectuor
* currently handles. Note that most of the interesting commands do not go
* through the executor but rather ProcessUtility, where we have the parsetree.
*/
#define COMMAND_SELECT "SELECT"
#define COMMAND_INSERT "INSERT"
#define COMMAND_UPDATE "UPDATE"
#define COMMAND_DELETE "DELETE"
#define COMMAND_EXECUTE "EXECUTE"
#define COMMAND_UNKNOWN "UNKNOWN"
AuditEventStackItem *auditEventStack = NULL;
/* Function prototype for hook */
static void pgaudit_emit_log_hook(ErrorData *edata);
static void append_valid_csv(StringInfoData *buffer, const char *appendStr);
static void emit_session_sql_log(AuditEventStackItem *stackItem, bool *valid_rules,
const char *className);
/* Function prototype for changing GUC variables */
static int guc_var_compare(const void *a, const void *b);
static int guc_name_compare(const char *namea, const char *nameb);
/*
* Hook functions
*/
static ExecutorCheckPerms_hook_type next_ExecutorCheckPerms_hook = NULL;
static ProcessUtility_hook_type next_ProcessUtility_hook = NULL;
static object_access_hook_type next_object_access_hook = NULL;
static ExecutorStart_hook_type next_ExecutorStart_hook = NULL;
static emit_log_hook_type next_emit_log_hook = NULL;
/*
* pgAudit runs queries of its own when using the event trigger system.
*
* Track when we are running a query and don't log it.
*/
static bool internalStatement = false;
/*
* Track running total for statements and substatements and whether or not
* anything has been logged since the current statement began.
*/
static int64 statementTotal = 0;
static int64 substatementTotal = 0;
static int64 stackTotal = 0;
static bool statementLogged = false;
/* Functions and variable for audit timestamp stuff */
TimeADT auditTimestampOfDay;
pg_time_t auditTimestamp;
static void setAuditTimestamp(void);
static void create_audit_log_string(StringInfo buf, ErrorData *edata,
AuditEventStackItem *stackItem,
const char *className);
/*
* Emit the SESSION log for event from emit_log_hook. This routine is
* used for logging of connection, disconnection, replication command etc.
*/
static void
pgaudit_emit_log_hook(ErrorData *edata)
{
int class;
char *className = NULL;
bool *valid_rules = palloc(sizeof(bool) * list_length(ruleConfigs));
if (emitAuditLogCalled == 0)
{
/* Get class and className using edata */
className = classify_edata_class(edata, &class);
/* If we are not interested in this message, skip routine */
if (className != NULL)
{
StringInfoData auditStr;
ListCell *cell;
int num = 0;
/* Set audit logging timestamp of day */
setAuditTimestamp();
/*
* Only log the statement if the edata matches to all rules of
* multiple rule secion.
*/
if (!apply_all_rules(NULL, edata, class, className, valid_rules))
return;
foreach(cell, ruleConfigs)
{
/* If this event does not match to current rule, ignore it */
if (!valid_rules[num++])
continue;
initStringInfo(&auditStr);
create_audit_log_string(&auditStr, edata, NULL, className);
/*
* XXX : We should support output format specified by 'format' or
* emit the fixed format log.
*/
AUDIT_EREPORT(auditLogLevel,
(errmsg(auditStr.data, ""), /* keep compile quiet */
errhidestmt(true),
errhidecontext(true)));
}
}
}
if (next_emit_log_hook)
(*next_emit_log_hook) (edata);
}
/*
* Emit the SESSION log for stackItem. The caller must set appropriate
* memory context and back it after finished.
*/
static void
emit_session_sql_log(AuditEventStackItem *stackItem, bool *valid_rules,
const char *className)
{
StringInfoData auditStr;
ListCell *cell;
int num = 0;
foreach(cell, ruleConfigs)
{
/* If this event does not match to current rule, ignore it */
if (!valid_rules[num++])
continue;
initStringInfo(&auditStr);
create_audit_log_string(&auditStr, NULL, stackItem, className);
/* Emit the audit log */
AUDIT_EREPORT(auditLogLevel,
(errmsg(auditStr.data, ""), /* keep compile quiet */
errhidestmt(true),
errhidecontext(true)));
stackItem->auditEvent.logged = true;
}
}
/*
* Craft the audit log message string. Retrun the fixed format audit log
* string data that contains all information for the audit.
*
* For regression test, since timestamp of each audit log can be changed
* whenever execute, so if logForTest is true then we don't write such
* information to buf intentionally.
*
* XXX : Since this routine could be called high frequently, it could be
* bottle neck. One optimizatin idea is to change this function so that
* it re-use the static data in one query such as database name, remote
* host.
*/
static void
create_audit_log_string(StringInfo buf, ErrorData *edata,
AuditEventStackItem *stackItem,
const char *className)
{
char strbuf[128];
char separator = ',';
Assert(className != NULL);
/* Prefix "AUDIT: SESSION" */
appendStringInfoString(buf, "AUDIT: SESSION,");
/* class */
if (className)
appendStringInfoString(buf, className);
appendStringInfoChar(buf, separator);
/* timestamp(%t) */
if (!logForTest)
{
pg_time_t stamp_time = (pg_time_t) time(NULL);
pg_strftime(strbuf, sizeof(strbuf),
"%Y-%m-%d %H:%M:%S %Z",
pg_localtime(&stamp_time, log_timezone));
appendStringInfoString(buf, strbuf);
}
appendStringInfoChar(buf, separator);
/* remote host(%h) */
if (MyProcPort && MyProcPort->remote_host)
appendStringInfoString(buf, MyProcPort->remote_host);
appendStringInfoChar(buf, separator);
/* process id (%p) */
if (!logForTest)
appendStringInfo(buf, "%d", MyProcPid);
appendStringInfoChar(buf, separator);
/* applicaton name(%a) */
if (MyProcPort)
{
const char *appname = application_name;
if (appname == NULL || *appname == '\0')
appname = "[unknown]";
appendStringInfoString(buf, appname);
}
appendStringInfoChar(buf, separator);
/* user name(%u) */
if (!logForTest)
{
if (MyProcPort && MyProcPort->user_name)
appendStringInfoString(buf, MyProcPort->user_name);
}
appendStringInfoChar(buf, separator);
/* database name(%d) */
if (MyProcPort && MyProcPort->database_name)
appendStringInfoString(buf, MyProcPort->database_name);
appendStringInfoChar(buf, separator);
/* virtual transaction id (%v) */
if (!logForTest &&
MyProc != NULL && MyProc->backendId != InvalidBackendId)
{
char strbuf[128];
snprintf(strbuf, sizeof(strbuf) - 1, "%d/%u",
MyProc->backendId, MyProc->lxid);
appendStringInfoString(buf, strbuf);
}
appendStringInfoChar(buf, separator);
/* Statement id */
if (stackItem)
appendStringInfo(buf, INT64_FORMAT, stackItem->auditEvent.statementId);
appendStringInfoChar(buf, separator);
/* Sub statement id */
if (stackItem)
appendStringInfo(buf, INT64_FORMAT, stackItem->auditEvent.substatementId);
appendStringInfoChar(buf, separator);
/* command tag */
if (stackItem)
append_valid_csv(buf, stackItem->auditEvent.command);
appendStringInfoChar(buf, separator);
/* error state (%e) */
if (edata != NULL)
appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
appendStringInfoChar(buf, separator);
/* Object type */
if (stackItem)
append_valid_csv(buf, stackItem->auditEvent.objectType);
appendStringInfoChar(buf, separator);
/* Object name */
if (stackItem)
append_valid_csv(buf, stackItem->auditEvent.objectName);
appendStringInfoChar(buf, separator);
/* Error message */
if (edata != NULL)
appendStringInfoString(buf, edata->message);
appendStringInfoChar(buf, separator);
if (stackItem != NULL)
{
if (!stackItem->auditEvent.statementLogged || !auditLogStatementOnce)
{
/* SQL */
append_valid_csv(buf, stackItem->auditEvent.commandText);
appendStringInfoChar(buf, separator);
/* Parameter */
if (auditLogParameter)
{
int paramIdx;
int numParams;
StringInfoData paramStrResult;
ParamListInfo paramList = stackItem->auditEvent.paramList;
numParams = paramList == NULL ? 0 : paramList->numParams;
/* Create the param substring */
initStringInfo(¶mStrResult);
/* Iterate through all params */
for (paramIdx = 0; paramList != NULL && paramIdx < numParams;
paramIdx++)
{
ParamExternData *prm = ¶mList->params[paramIdx];
Oid typeOutput;
bool typeIsVarLena;
char *paramStr;
/* Add a space for each param */
if (paramIdx != 0)
append_valid_csv(¶mStrResult, " ");
/* Skip if null or if oid is invalid */
if (prm->isnull || !OidIsValid(prm->ptype))
continue;
/* Output the string */
getTypeOutputInfo(prm->ptype, &typeOutput, &typeIsVarLena);
paramStr = OidOutputFunctionCall(typeOutput, prm->value);
append_valid_csv(¶mStrResult, paramStr);
pfree(paramStr);
}
if (numParams == 0)
appendStringInfoString(buf, "<none>");
else
append_valid_csv(buf, paramStrResult.data);
}
else
appendStringInfoString(buf, "<not logged>");
stackItem->auditEvent.statementLogged = true;
}
else
{
/* we were asked to not log it */
appendStringInfoChar(buf, separator);
appendStringInfoString(buf,
"<previously logged>,<previously logged>");
}
}
else
/* padding for <sql>,<parameter> */
appendStringInfoString(buf, ",");
}
/* Show all audit configuration */
static void
print_config(void)
{
ListCell *cell;
int n_rule = 0;
AUDIT_EREPORT(LOG, (errmsg("log_catalog = %d", auditLogCatalog)));
AUDIT_EREPORT(LOG, (errmsg("log_level_string = %s", auditLogLevelString)));
AUDIT_EREPORT(LOG, (errmsg("log_level = %d", auditLogLevel)));
AUDIT_EREPORT(LOG, (errmsg("log_parameter = %d", auditLogParameter)));
AUDIT_EREPORT(LOG, (errmsg("log_statement_once = %d", auditLogStatementOnce)));
AUDIT_EREPORT(LOG, (errmsg("log_for_test = %d", logForTest)));
AUDIT_EREPORT(LOG, (errmsg("role = %s", auditRole)));
AUDIT_EREPORT(LOG, (errmsg("logger = %s", outputConfig.logger)));
AUDIT_EREPORT(LOG, (errmsg("facility = %s", outputConfig.facility)));
AUDIT_EREPORT(LOG, (errmsg("priority = %s", outputConfig.priority)));
AUDIT_EREPORT(LOG, (errmsg("ident = %s", outputConfig.ident)));
AUDIT_EREPORT(LOG, (errmsg("option = %s", outputConfig.option)));
AUDIT_EREPORT(LOG, (errmsg("pathlog = %s", outputConfig.pathlog)));
foreach(cell, ruleConfigs)
{
AuditRuleConfig *rconf = lfirst(cell);
int j;
AUDIT_EREPORT(LOG, (errmsg("Rule %d", n_rule)));
n_rule++;
for (j = 0; j < AUDIT_NUM_RULES; j++)
{
AuditRule rule = rconf->rules[j];
if (rule.values == NULL)
continue;
/* String rule */
if (isStringRule(rule))
{
int num = rule.nval;
int i;
for (i = 0; i < num; i++)
{
char *val = ((char **)rule.values)[i];
AUDIT_EREPORT(LOG, (errmsg(" STR %s %s %s",
rule.field,
rule.eq ? "=" : "!=",
val)));
}
}
/* Bitmap rule */
else if (isBitmapRule(rule))
{
int val = *((int *)rule.values);
AUDIT_EREPORT(LOG, (errmsg(" BMP %s %s %d",
rule.field,
rule.eq ? "=" : "!=",
val)));
}
/* Timestamp rule */
else if (isTimestampRule(rule))
{
int num = rule.nval;
int i;
for (i = 0; i < num; i++)
{
pg_time_t val = ((pg_time_t *)rule.values)[i];
AUDIT_EREPORT(LOG, (errmsg(" TMS %s %s %ld",
rule.field,
rule.eq ? "=" : "!=",
val)));
}
}
}
}
}
/*
* Stack functions
*
* Audit events can go down to multiple levels so a stack is maintained to keep
* track of them.
*/
/*
* Respond to callbacks registered with MemoryContextRegisterResetCallback().
* Removes the event(s) off the stack that have become obsolete once the
* MemoryContext has been freed. The callback should always be freeing the top
* of the stack, but the code is tolerant of out-of-order callbacks.
*/
static void
stack_free(void *stackFree)
{
AuditEventStackItem *nextItem = auditEventStack;
/* Only process if the stack contains items */
while (nextItem != NULL)
{
/* Check if this item matches the item to be freed */
if (nextItem == (AuditEventStackItem *) stackFree)
{
/* Move top of stack to the item after the freed item */
auditEventStack = nextItem->next;
/* If the stack is not empty */
if (auditEventStack == NULL)
{
/*
* Reset internal statement to false. Normally this will be
* reset but in case of an error it might be left set.
*/
internalStatement = false;
/*
* Reset sub statement total so the next statement will start
* from 1.
*/
substatementTotal = 0;
/*
* Reset statement logged so that next statement will be
* logged.
*/
statementLogged = false;
}
return;
}
nextItem = nextItem->next;
}
}
/*
* Push a new audit event onto the stack and create a new memory context to
* store it.
*/
static AuditEventStackItem *
stack_push()
{
MemoryContext contextAudit;
MemoryContext contextOld;
AuditEventStackItem *stackItem;
/*
* Create a new memory context to contain the stack item. This will be
* free'd on stack_pop, or by our callback when the parent context is
* destroyed.
*/
contextAudit = AllocSetContextCreate(CurrentMemoryContext,
"pgaudit stack context",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
/* Save the old context to switch back to at the end */
contextOld = MemoryContextSwitchTo(contextAudit);
/* Create our new stack item in our context */
stackItem = palloc0(sizeof(AuditEventStackItem));
stackItem->contextAudit = contextAudit;
stackItem->stackId = ++stackTotal;
/*
* Setup a callback in case an error happens. stack_free() will truncate
* the stack at this item.
*/
stackItem->contextCallback.func = stack_free;
stackItem->contextCallback.arg = (void *) stackItem;
MemoryContextRegisterResetCallback(contextAudit,
&stackItem->contextCallback);
/* Push new item onto the stack */
if (auditEventStack != NULL)
stackItem->next = auditEventStack;
else
stackItem->next = NULL;
auditEventStack = stackItem;
MemoryContextSwitchTo(contextOld);
return stackItem;
}
/*
* Pop an audit event from the stack by deleting the memory context that
* contains it. The callback to stack_free() does the actual pop.
*/
static void
stack_pop(int64 stackId)
{
/* Make sure what we want to delete is at the top of the stack */
if (auditEventStack != NULL && auditEventStack->stackId == stackId)
MemoryContextDelete(auditEventStack->contextAudit);
else
elog(ERROR, "pgaudit stack item " INT64_FORMAT " not found on top - cannot pop",
stackId);
}
/*
* Check that an item is on the stack. If not, an error will be raised since
* this is a bad state to be in and it might mean audit records are being lost.
*/
static void
stack_valid(int64 stackId)
{
AuditEventStackItem *nextItem = auditEventStack;
/* Look through the stack for the stack entry */
while (nextItem != NULL && nextItem->stackId != stackId)
nextItem = nextItem->next;
/* If we didn't find it, something went wrong. */
if (nextItem == NULL)
elog(ERROR, "pgaudit stack item " INT64_FORMAT
" not found - top of stack is " INT64_FORMAT "",
stackId,
auditEventStack == NULL ? (int64) -1 : auditEventStack->stackId);
}
/*
* Appends a properly quoted CSV field to StringInfo.
*/
static void
append_valid_csv(StringInfoData *buffer, const char *appendStr)
{
const char *pChar;
/*
* If the append string is null then do nothing. NULL fields are not
* quoted in CSV.
*/
if (appendStr == NULL)
return;
/* Only format for CSV if appendStr contains: ", comma, \n, \r */
if (strstr(appendStr, ",") || strstr(appendStr, "\"") ||
strstr(appendStr, "\n") || strstr(appendStr, "\r"))
{
appendStringInfoCharMacro(buffer, '"');
for (pChar = appendStr; *pChar; pChar++)
{
if (*pChar == '"') /* double single quotes */
appendStringInfoCharMacro(buffer, *pChar);
appendStringInfoCharMacro(buffer, *pChar);
}
appendStringInfoCharMacro(buffer, '"');
}
/* Else just append */
else
appendStringInfoString(buffer, appendStr);
}
/*
* Takes an AuditEvent, classifies it, then logs it if appropriate.
*
* Logging is decided based on if the statement is in one of the classes being
* logged or if an object used has been marked for auditing.
*
* Objects are marked for auditing by the auditor role being granted access
* to the object. The kind of access (INSERT, UPDATE, etc) is also considered
* and logging is only performed when the kind of access matches the granted
* right on the object.
*
* This will need to be updated if new kinds of GRANTs are added.
*/
static void
log_audit_event(AuditEventStackItem *stackItem)
{
/* By default, put everything in the MISC class. */
char *className = CLASS_MISC;
int class;
MemoryContext contextOld;
StringInfoData auditStr;
bool *valid_rules;
/* If this event has already been logged don't log it again */
if (stackItem->auditEvent.logged)
return;
valid_rules = palloc(sizeof(bool) * list_length(ruleConfigs));
/* Get class and className using stackItem */
className = classify_statement_class(stackItem, &class);
/* Set audit logging timestamp of day */
setAuditTimestamp();
/*----------
* Only log the statement if:
*
* 1. If object was selected for audit logging (granted), or
* 2. The statement matches to all rules of multiple rule sections.
*
* If neither of these is true, return.
*----------
*/
/*
* XXX : Here, we have to do check if auditEven can be machted with
* any rules we defined. Return from here if not matched to any rules.
*/
if (!stackItem->auditEvent.granted &&
!apply_all_rules(stackItem, NULL, class, className, valid_rules))
return ;
/*
* Use audit memory context in case something is not free'd while
* appending strings and parameters.
*/
contextOld = MemoryContextSwitchTo(stackItem->contextAudit);
/* Set statement and substatement IDs */
if (stackItem->auditEvent.statementId == 0)
{
/* If nothing has been logged yet then create a new statement Id */
if (!statementLogged)
{
statementTotal++;
statementLogged = true;
}
stackItem->auditEvent.statementId = statementTotal;
stackItem->auditEvent.substatementId = ++substatementTotal;
}
/*
* When we are going to emit the SESSION log, granted is set false.
* In this case, we emit the log according to defined rules
*/
if (stackItem->auditEvent.granted == false)
{
emit_session_sql_log(stackItem, valid_rules, className);
MemoryContextSwitchTo(contextOld);
return;
}
/*
* Create the audit substring
*
* The type-of-audit-log and statement/substatement ID are handled below,
* this string is everything else.
*/
initStringInfo(&auditStr);
append_valid_csv(&auditStr, stackItem->auditEvent.command);
appendStringInfoCharMacro(&auditStr, ',');
append_valid_csv(&auditStr, stackItem->auditEvent.objectType);
appendStringInfoCharMacro(&auditStr, ',');
append_valid_csv(&auditStr, stackItem->auditEvent.objectName);
/*
* If auditLogStatmentOnce is true, then only log the statement and
* parameters if they have not already been logged for this substatement.
*/
appendStringInfoCharMacro(&auditStr, ',');
if (!stackItem->auditEvent.statementLogged || !auditLogStatementOnce)
{
append_valid_csv(&auditStr, stackItem->auditEvent.commandText);
appendStringInfoCharMacro(&auditStr, ',');
/* Handle parameter logging, if enabled. */
if (auditLogParameter)
{
int paramIdx;
int numParams;
StringInfoData paramStrResult;
ParamListInfo paramList = stackItem->auditEvent.paramList;
numParams = paramList == NULL ? 0 : paramList->numParams;
/* Create the param substring */
initStringInfo(¶mStrResult);
/* Iterate through all params */
for (paramIdx = 0; paramList != NULL && paramIdx < numParams;
paramIdx++)
{
ParamExternData *prm = ¶mList->params[paramIdx];
Oid typeOutput;
bool typeIsVarLena;
char *paramStr;
/* Add a comma for each param */
if (paramIdx != 0)
appendStringInfoCharMacro(¶mStrResult, ',');
/* Skip if null or if oid is invalid */
if (prm->isnull || !OidIsValid(prm->ptype))
continue;
/* Output the string */
getTypeOutputInfo(prm->ptype, &typeOutput, &typeIsVarLena);
paramStr = OidOutputFunctionCall(typeOutput, prm->value);
append_valid_csv(¶mStrResult, paramStr);
pfree(paramStr);
}
if (numParams == 0)
appendStringInfoString(&auditStr, "<none>");
else
append_valid_csv(&auditStr, paramStrResult.data);
}
else
appendStringInfoString(&auditStr, "<not logged>");
stackItem->auditEvent.statementLogged = true;
}
else
/* we were asked to not log it */
appendStringInfoString(&auditStr,
"<previously logged>,<previously logged>");
/*
* Log the audit entry. Note: use of INT64_FORMAT here is bad for
* translatability, but we currently haven't got translation support in
* pgaudit anyway.
*/
AUDIT_EREPORT(auditLogLevel,
(errmsg("AUDIT: OBJECT," INT64_FORMAT "," INT64_FORMAT ",%s,%s",
stackItem->auditEvent.statementId,
stackItem->auditEvent.substatementId,
className,
auditStr.data),
errhidestmt(true),
errhidecontext(true)));
stackItem->auditEvent.logged = true;
MemoryContextSwitchTo(contextOld);
}
/*
* Check if the role or any inherited role has any permission in the mask. The
* public role is excluded from this check and superuser permissions are not
* considered.
*/
static bool
audit_on_acl(Datum aclDatum,
Oid auditOid,
AclMode mask)
{
bool result = false;
Acl *acl;
AclItem *aclItemData;
int aclIndex;
int aclTotal;
/* Detoast column's ACL if necessary */
acl = DatumGetAclP(aclDatum);
/* Get the acl list and total number of items */
aclTotal = ACL_NUM(acl);
aclItemData = ACL_DAT(acl);
/* Check privileges granted directly to auditOid */
for (aclIndex = 0; aclIndex < aclTotal; aclIndex++)
{
AclItem *aclItem = &aclItemData[aclIndex];
if (aclItem->ai_grantee == auditOid &&
aclItem->ai_privs & mask)
{
result = true;
break;
}
}
/*
* Check privileges granted indirectly via role memberships. We do this in
* a separate pass to minimize expensive indirect membership tests. In
* particular, it's worth testing whether a given ACL entry grants any
* privileges still of interest before we perform the has_privs_of_role
* test.
*/
if (!result)
{
for (aclIndex = 0; aclIndex < aclTotal; aclIndex++)
{
AclItem *aclItem = &aclItemData[aclIndex];
/* Don't test public or auditOid (it has been tested already) */
if (aclItem->ai_grantee == ACL_ID_PUBLIC ||
aclItem->ai_grantee == auditOid)
continue;
/*
* Check that the role has the required privileges and that it is
* inherited by auditOid.
*/
if (aclItem->ai_privs & mask &&
has_privs_of_role(auditOid, aclItem->ai_grantee))
{
result = true;
break;
}
}
}
/* if we have a detoasted copy, free it */
if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
pfree(acl);
return result;
}
/*
* Check if a role has any of the permissions in the mask on a relation.
*/
static bool
audit_on_relation(Oid relOid,
Oid auditOid,
AclMode mask)
{
bool result = false;
HeapTuple tuple;
Datum aclDatum;
bool isNull;
/* Get relation tuple from pg_class */
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
if (!HeapTupleIsValid(tuple))
return false;
/* Get the relation's ACL */
aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
&isNull);
/* Only check if non-NULL, since NULL means no permissions */
if (!isNull)
result = audit_on_acl(aclDatum, auditOid, mask);
/* Free the relation tuple */
ReleaseSysCache(tuple);
return result;
}
/*
* Check if a role has any of the permissions in the mask on a column.
*/
static bool
audit_on_attribute(Oid relOid,
AttrNumber attNum,
Oid auditOid,
AclMode mask)
{
bool result = false;
HeapTuple attTuple;
Datum aclDatum;
bool isNull;
/* Get the attribute's ACL */
attTuple = SearchSysCache2(ATTNUM,
ObjectIdGetDatum(relOid),
Int16GetDatum(attNum));
if (!HeapTupleIsValid(attTuple))
return false;
/* Only consider attributes that have not been dropped */
if (!((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped)
{
aclDatum = SysCacheGetAttr(ATTNUM, attTuple, Anum_pg_attribute_attacl,
&isNull);