forked from pgaudit/pgaudit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgaudit.c
2335 lines (1986 loc) · 74.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 README.md for details).
*
* Copyright (c) 2014-2024, PostgreSQL Global Development Group
*------------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "access/relation.h"
#include "catalog/catalog.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_class.h"
#include "catalog/namespace.h"
#include "commands/dbcommands.h"
#include "commands/extension.h"
#include "catalog/pg_proc.h"
#include "commands/event_trigger.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "miscadmin.h"
#include "libpq/auth.h"
#include "nodes/nodes.h"
#include "nodes/params.h"
#include "parser/parse_relation.h"
#include "tcop/utility.h"
#include "tcop/deparse_utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
PG_MODULE_MAGIC;
void _PG_init(void);
PG_FUNCTION_INFO_V1(pgaudit_ddl_command_end);
PG_FUNCTION_INFO_V1(pgaudit_sql_drop);
/*
* Log Classes
*
* pgAudit categorizes actions into classes (eg: DDL, FUNCTION calls, READ
* queries, WRITE queries). A GUC is provided for the administrator to
* configure which class (or classes) of actions to include in the
* audit log. We track the currently active set of classes using
* auditLogBitmap.
*/
/* Bits within auditLogBitmap, defines the classes we understand */
#define LOG_DDL (1 << 0) /* CREATE/DROP/ALTER objects */
#define LOG_FUNCTION (1 << 1) /* Functions and DO blocks */
#define LOG_MISC (1 << 2) /* Statements not covered */
#define LOG_READ (1 << 3) /* SELECTs */
#define LOG_ROLE (1 << 4) /* GRANT/REVOKE, CREATE/ALTER/DROP ROLE */
#define LOG_WRITE (1 << 5) /* INSERT, UPDATE, DELETE, TRUNCATE */
#define LOG_MISC_SET (1 << 6) /* SET ... */
#define LOG_NONE 0 /* nothing */
#define LOG_ALL (0xFFFFFFFF) /* All */
/* GUC variable for pgaudit.log, which defines the classes to log. */
char *auditLog = NULL;
/* Bitmap of classes selected */
static int auditLogBitmap = LOG_NONE;
/*
* String constants for log classes - used when processing tokens in the
* pgaudit.log GUC.
*/
#define CLASS_DDL "DDL"
#define CLASS_FUNCTION "FUNCTION"
#define CLASS_MISC "MISC"
#define CLASS_MISC_SET "MISC_SET"
#define CLASS_READ "READ"
#define CLASS_ROLE "ROLE"
#define CLASS_WRITE "WRITE"
#define CLASS_NONE "NONE"
#define CLASS_ALL "ALL"
/*
* GUC variable for pgaudit.log_catalog
*
* Administrators can choose to NOT log queries when all relations used in
* the query are in pg_catalog. Interactive sessions (eg: psql) can cause
* a lot of noise in the logs which might be uninteresting.
*/
bool auditLogCatalog = true;
/*
* GUC variable for pgaudit.log_client
*
* Specifies whether audit messages should be visible to the client. This
* setting should generally be left disabled but may be useful for debugging or
* other purposes.
*/
bool auditLogClient = false;
/*
* GUC variable for pgaudit.log_level
*
* Administrators can choose which log level the audit log is to be logged
* at. The default level is LOG, which goes into the server log but does
* not go to the client. Set to NOTICE in the regression tests.
*/
char *auditLogLevelString = NULL;
int auditLogLevel = LOG;
/*
* GUC variable for pgaudit.log_parameter
*
* Administrators can choose if parameters passed into a statement are
* included in the audit log.
*/
bool auditLogParameter = false;
/*
* GUC variable for pgaudit.log_relation
*
* Administrators can choose, in SESSION logging, to log each relation involved
* in READ/WRITE class queries. By default, SESSION logs include the query but
* do not have a log entry for each relation.
*/
bool auditLogRelation = false;
/*
* GUC variable for pgaudit.log_parameter_max_size
*
* Administrators can choose to prevent the logging of large variable-length
* parameters. If set to 0 (the default), all parameters are logged. If set
* greater than 0, variable length parameters (before character output) whose
* size is greater than the specified number of bytes will be replaced
* by a placeholder.
*/
int auditLogParameterMaxSize = 0;
/*
* GUC variable for pgaudit.log_rows
*
* Administrators can choose if the rows retrieved or affected by a statement
* are included in the audit log.
*/
bool auditLogRows = false;
/*
* GUC variable for pgaudit.log_statement
*
* Administrators can choose to not have the full statement text logged.
*/
bool auditLogStatement = true;
/*
* GUC variable for pgaudit.log_statement_once
*
* Administrators can choose to have the statement run logged only once instead
* of on every line. By default, the statement is repeated on every line of
* the audit log to facilitate searching, but this can cause the log to be
* unnecessarily bloated in some environments.
*/
bool auditLogStatementOnce = false;
/*
* GUC variable for pgaudit.role
*
* Administrators can choose which role to base OBJECT auditing off of.
* Object-level auditing uses the privileges which are granted to this role to
* determine if a statement should be logged.
*/
char *auditRole = NULL;
/*
* String constants for the audit log fields.
*/
/*
* Audit type, which is responsbile for the log message
*/
#define AUDIT_TYPE_OBJECT "OBJECT"
#define AUDIT_TYPE_SESSION "SESSION"
/*
* Object type, used for SELECT/DML statements and function calls.
*
* For relation objects, this is essentially relkind (though we do not have
* access to a function which will just return a string given a relkind;
* getRelationTypeDescription() comes close but is not public currently).
*
* We also handle functions, so it isn't quite as simple as just relkind.
*
* This should be kept consistent with what is returned from
* pg_event_trigger_ddl_commands(), as that's what we use for DDL.
*/
#define OBJECT_TYPE_TABLE "TABLE"
#define OBJECT_TYPE_INDEX "INDEX"
#define OBJECT_TYPE_SEQUENCE "SEQUENCE"
#define OBJECT_TYPE_TOASTVALUE "TOAST TABLE"
#define OBJECT_TYPE_VIEW "VIEW"
#define OBJECT_TYPE_MATVIEW "MATERIALIZED VIEW"
#define OBJECT_TYPE_COMPOSITE_TYPE "COMPOSITE TYPE"
#define OBJECT_TYPE_FOREIGN_TABLE "FOREIGN TABLE"
#define OBJECT_TYPE_FUNCTION "FUNCTION"
#define OBJECT_TYPE_UNKNOWN "UNKNOWN"
/*
* String constants used for redacting text after the password token in
* CREATE/ALTER ROLE commands.
*/
#define TOKEN_PASSWORD "password"
#define TOKEN_REDACTED "<REDACTED>"
/*
* An AuditEvent represents an operation that potentially affects a single
* object. If a statement affects multiple objects then multiple AuditEvents
* are created to represent them.
*/
typedef struct
{
int64 statementId; /* Simple counter */
int64 substatementId; /* Simple counter */
LogStmtLevel logStmtLevel; /* From GetCommandLogLevel when possible,
generated when not. */
NodeTag commandTag; /* same here */
int command; /* same here */
const char *objectType; /* From event trigger when possible,
generated when not. */
char *objectName; /* Fully qualified object identification */
const char *commandText; /* sourceText / queryString */
int commandLen; /* Length of commandText */
ParamListInfo paramList; /* QueryDesc/ProcessUtility parameters */
bool granted; /* Audit role has object permissions? */
bool logged; /* Track if we have logged this event, used
post-ProcessUtility to make sure we log */
bool statementLogged; /* Track if we have logged the statement */
int64 rows; /* Track rows processed by the statement */
MemoryContext queryContext; /* Context for query tracking rows */
Oid auditOid; /* Role running query tracking rows */
List *rangeTabls; /* Tables in query tracking rows */
List *permInfos; /* Permission info rows for each table involved
in the query */
} AuditEvent;
/*
* A simple FIFO queue to keep track of the current stack of audit events.
*/
typedef struct AuditEventStackItem
{
struct AuditEventStackItem *next;
AuditEvent auditEvent;
int64 stackId;
MemoryContext contextAudit;
MemoryContextCallback contextCallback;
} AuditEventStackItem;
AuditEventStackItem *auditEventStack = 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;
/*
* 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_SIZES);
/* 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);
}
/*
* Find an item on the stack by the specified query memory context.
*/
static AuditEventStackItem *
stack_find_context(MemoryContext findContext)
{
AuditEventStackItem *nextItem = auditEventStack;
/* Look through the stack for the stack entry by query memory context */
while (nextItem != NULL)
{
if (nextItem->auditEvent.queryContext == findContext)
break;
nextItem = nextItem->next;
}
return nextItem;
}
/*
* Set command text.
*/
static void
command_text_set(AuditEvent *auditEvent, const char *commandText,
int commandLoc, int commandLen)
{
/* If statements are being logged then set command text. */
if (auditLogStatement)
{
char commandChr;
/* If location is not -1 then offset. */
if (commandLoc != -1)
commandText += commandLoc;
/* If len is zero then use the entire string. */
if (commandLen == 0)
commandLen = strlen(commandText);
/*
* Trim leading whitespace. This assumes that commandText is a valid
* zero-terminated string.
*/
commandChr = *commandText;
while (commandChr == ' ' || commandChr == '\t' || commandChr == '\n' ||
commandChr == '\r')
{
commandText++;
commandLen--;
commandChr = *commandText;
}
/*
* Trim trailing whitespace. Also trim trailing semicolons since they
* might be included if commandLen was not provided. This makes output
* consistent with when commandLen is provided.
*/
commandChr = *(commandText + commandLen - 1);
while (commandLen > 0 &&
(commandChr == ' ' || commandChr == ';' || commandChr == '\t' ||
commandChr == '\n' || commandChr == '\r'))
{
commandLen--;
commandChr = *(commandText + commandLen - 1);
}
/* Assign final command text and length. */
auditEvent->commandText = commandText;
auditEvent->commandLen = commandLen;
}
}
/*
* 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. */
int class = LOG_MISC;
const char *className = CLASS_MISC;
MemoryContext contextOld;
StringInfoData auditStr;
/*
* Skip logging script statements if an extension is currently being created
* or altered. PostgreSQL reports the statement text for each statement in
* the script as the entire script text, which can blow up the logs. The
* create/alter statement will still be logged.
*
* Since a superuser is responsible for determining which extensions are
* available, and in most cases installing them, it should not be necessary
* to log each statement in the script.
*/
if (creating_extension)
return;
/* If this event has already been logged don't log it again */
if (stackItem->auditEvent.logged)
return;
/* Classify the statement using log stmt level and the command tag */
switch (stackItem->auditEvent.logStmtLevel)
{
/* All mods go in WRITE class, except EXECUTE */
case LOGSTMT_MOD:
className = CLASS_WRITE;
class = LOG_WRITE;
switch (stackItem->auditEvent.commandTag)
{
/* Currently, only EXECUTE is different */
case T_ExecuteStmt:
className = CLASS_MISC;
class = LOG_MISC;
break;
default:
break;
}
break;
/* These are DDL, unless they are ROLE */
case LOGSTMT_DDL:
className = CLASS_DDL;
class = LOG_DDL;
/* Identify role statements */
switch (stackItem->auditEvent.commandTag)
{
/* In the case of create and alter role or user mapping redact all text in the
* command after the password token for security. This doesn't
* cover all possible cases where passwords can be leaked but
* should take care of the most common usage.
*/
case T_CreateRoleStmt:
case T_AlterRoleStmt:
case T_CreateUserMappingStmt:
case T_AlterUserMappingStmt:
if (stackItem->auditEvent.commandText != NULL)
{
char *commandStr;
char *passwordToken;
int i;
int passwordPos;
/* Copy the command string and convert to lower case */
commandStr = pnstrdup(stackItem->auditEvent.commandText,
stackItem->auditEvent.commandLen);
for (i = 0; commandStr[i]; i++)
commandStr[i] =
(char)pg_tolower((unsigned char)commandStr[i]);
/* Find index of password token */
passwordToken = strstr(commandStr, TOKEN_PASSWORD);
if (passwordToken != NULL)
{
/* Copy command string up to password token */
passwordPos = (passwordToken - commandStr) +
strlen(TOKEN_PASSWORD);
commandStr = palloc(passwordPos + 1 +
strlen(TOKEN_REDACTED) + 1);
strncpy(commandStr,
stackItem->auditEvent.commandText,
passwordPos);
/* And append redacted token */
commandStr[passwordPos] = ' ';
strcpy(commandStr + passwordPos + 1, TOKEN_REDACTED);
/* Assign new command string */
stackItem->auditEvent.commandText = commandStr;
stackItem->auditEvent.commandLen = strlen(commandStr);
}
}
/* Fall through */
/* Classify role statements */
case T_GrantStmt:
case T_GrantRoleStmt:
case T_DropRoleStmt:
case T_AlterRoleSetStmt:
case T_AlterDefaultPrivilegesStmt:
className = CLASS_ROLE;
class = LOG_ROLE;
break;
/*
* Rename and Drop are general and therefore we have to do
* an additional check against the command string to see
* if they are role or regular DDL.
*/
case T_RenameStmt:
case T_DropStmt:
if (stackItem->auditEvent.command == CMDTAG_ALTER_ROLE ||
stackItem->auditEvent.command == CMDTAG_DROP_ROLE)
{
className = CLASS_ROLE;
class = LOG_ROLE;
}
break;
default:
break;
}
break;
/* Classify the rest */
case LOGSTMT_ALL:
switch (stackItem->auditEvent.commandTag)
{
/* READ statements */
case T_CopyStmt:
case T_DeclareCursorStmt:
case T_SelectStmt:
case T_PrepareStmt:
case T_PlannedStmt:
className = CLASS_READ;
class = LOG_READ;
break;
/* FUNCTION statements */
case T_DoStmt:
className = CLASS_FUNCTION;
class = LOG_FUNCTION;
break;
/*
* SET statements reported as MISC but filtered by MISC_SET
* flags to maintain existing functionality.
*/
case T_VariableSetStmt:
className = CLASS_MISC;
class = LOG_MISC_SET;
break;
default:
break;
}
break;
case LOGSTMT_NONE:
break;
}
/*
* Only log the statement if:
*
* 1. The object was selected for audit logging (granted), or
* 2. The statement belongs to a class that is being logged
*
* If neither of these is true, return.
*/
if (!stackItem->auditEvent.granted && !(auditLogBitmap & class))
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;
}
/*
* 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, GetCommandTagName(stackItem->auditEvent.command));
appendStringInfoCharMacro(&auditStr, ',');
append_valid_csv(&auditStr, stackItem->auditEvent.objectType);
appendStringInfoCharMacro(&auditStr, ',');
append_valid_csv(&auditStr, stackItem->auditEvent.objectName);
/*
* If auditLogStatementOnce is true, then only log the statement and
* parameters if they have not already been logged for this substatement.
*/
appendStringInfoCharMacro(&auditStr, ',');
if (auditLogStatement && !(stackItem->auditEvent.statementLogged && auditLogStatementOnce))
{
/* Log the command. */
char *commandStr = pnstrdup(stackItem->auditEvent.commandText,
stackItem->auditEvent.commandLen);
append_valid_csv(&auditStr, commandStr);
appendStringInfoCharMacro(&auditStr, ',');
pfree(commandStr);
/* 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;
/* 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;
/*
* Append the param, suppressing long params if the appropriate
* GUC is set.
*/
getTypeOutputInfo(prm->ptype, &typeOutput, &typeIsVarLena);
if (auditLogParameterMaxSize > 0 &&
typeIsVarLena &&
VARSIZE_ANY_EXHDR(prm->value) > auditLogParameterMaxSize)
{
append_valid_csv(¶mStrResult,
"<long param suppressed>");
}
else
{
char *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;
}
/* we were asked to not log it */
else if (!auditLogStatement)
appendStringInfoString(&auditStr,
"<not logged>,<not logged>");
else
appendStringInfoString(&auditStr,
"<previously logged>,<previously logged>");
/* Log rows affected */
if (auditLogRows)
appendStringInfo(&auditStr, "," INT64_FORMAT,
stackItem->auditEvent.rows);
/*
* 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.
*/
ereport(auditLogClient ? auditLogLevel : LOG_SERVER_ONLY,
(errmsg("AUDIT: %s," INT64_FORMAT "," INT64_FORMAT ",%s,%s",
stackItem->auditEvent.granted ?
AUDIT_TYPE_OBJECT : AUDIT_TYPE_SESSION,
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