-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcredcheck.c
2510 lines (2092 loc) · 69.2 KB
/
credcheck.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
/*-------------------------------------------------------------------------
*
* credcheck.c:
* This file has the general PostgreSQL credential checks.
*
* This program is open source, licensed under the PostgreSQL license.
* For license terms, see the LICENSE file.
*
* Copyright (c) 2021-2023: MigOps Inc
* Copyright (c) 2023: Gilles Darold
* Copyright (c) 2024-2025: HexaCluster Corp
*
*-------------------------------------------------------------------------
*/
#include <ctype.h>
#include <limits.h>
#include <unistd.h>
#ifdef USE_CRACKLIB
#include <crack.h>
#endif
#include "postgres.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "catalog/catalog.h"
#include "catalog/indexing.h"
#include "catalog/pg_auth_members.h"
#include "catalog/pg_authid.h"
#include "commands/user.h"
#if PG_VERSION_NUM >= 140000
#include "common/hmac.h"
#endif
#include "common/sha2.h"
#include "executor/spi.h"
#include "libpq/auth.h"
#include "nodes/makefuncs.h"
#include "nodes/nodes.h"
#include "nodes/pg_list.h"
#include "postmaster/postmaster.h"
#include "tcop/utility.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/shmem.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
/* Default passord encryption */
#define Password_encryption = PASSWORD_TYPE_SCRAM_SHA_256;
/* Name of external file to store password history in the PGDATA */
#define PGPH_DUMP_FILE_OLD "global/pg_password_history"
#define PGPH_DUMP_FILE "pg_password_history"
/* Number of output arguments (columns) in the pg_password_history pseudo table */
#define PG_PASSWORD_HISTORY_COLS 3
/* Number of output arguments (columns) in the pg_banned_role pseudo table */
#define PG_BANNED_ROLE_COLS 3
/* Magic number identifying the stats file format */
static const uint32 PGPH_FILE_HEADER = 0x48504750;
/* credcheck password history version, changes in which invalidate all entries */
static const uint32 PGPH_VERSION = 100;
#define PGPH_TRANCHE_NAME "credcheck_history"
#define PGAF_TRANCHE_NAME "credcheck_auth_failure"
static bool statement_has_password = false;
static bool no_password_logging = true;
#if PG_VERSION_NUM < 120000
#define table_open(r,l) heap_open(r,l)
#define table_openrv(r,l) heap_openrv(r,l)
#define table_close(r,l) heap_close(r,l)
#endif
#if PG_VERSION_NUM < 100000
#error Minimum version of PostgreSQL required is 10
#endif
/* Define ProcessUtility hook proto/parameters following the PostgreSQL version */
#if PG_VERSION_NUM >= 140000
#define PEL_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
bool readOnlyTree, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
QueryCompletion *qc
#define PEL_PROCESSUTILITY_ARGS pstmt, queryString, readOnlyTree, context, params, queryEnv, dest, qc
#else
#if PG_VERSION_NUM >= 130000
#define PEL_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
QueryCompletion *qc
#define PEL_PROCESSUTILITY_ARGS pstmt, queryString, context, params, queryEnv, dest, qc
#else
#define PEL_PROCESSUTILITY_PROTO PlannedStmt *pstmt, const char *queryString, \
ProcessUtilityContext context, ParamListInfo params, \
QueryEnvironment *queryEnv, DestReceiver *dest, \
char *completionTag
#define PEL_PROCESSUTILITY_ARGS pstmt, queryString, context, params, queryEnv, dest, completionTag
#endif
#endif
PG_MODULE_MAGIC;
/* Hooks */
static check_password_hook_type prev_check_password_hook = NULL;
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
/* Hold previous client authent hook */
static ClientAuthentication_hook_type prev_ClientAuthentication = NULL;
/* Hold previous logging hook */
static emit_log_hook_type prev_log_hook = NULL;
/* In memory storage of password history */
typedef struct pgphHashKey
{
char rolename[NAMEDATALEN];
char password_hash[PG_SHA256_DIGEST_STRING_LENGTH];
} pgphHashKey;
typedef struct pgphEntry
{
pgphHashKey key; /* hash key of entry - MUST BE FIRST */
TimestampTz password_date;
} pgphEntry;
/* Global shared state */
typedef struct pgphSharedState
{
LWLock *lock; /* protects hashtable search/modification */
int num_entries; /* number of entries in the password history */
} pgphSharedState;
/* Links to shared memory state */
static pgphSharedState *pgph = NULL;
static HTAB *pgph_hash = NULL;
static int pgph_max = 65535;
static int pgaf_max = 1024;
static int fail_max = 0;
static bool reset_superuser = false;
static bool encrypted_password_allowed = false;
/* In memory storage of auth failure history */
typedef struct pgafHashKey
{
Oid roleid;
} pgafHashKey;
typedef struct pgafEntry
{
pgafHashKey key; /* hash key of entry - MUST BE FIRST */
float failure_count;
TimestampTz banned_date;
} pgafEntry;
/* Global shared state */
typedef struct pgafSharedState
{
LWLock *lock; /* protects hashtable search/modification */
int num_entries; /* number of entries in the auth failure history */
} pgafSharedState;
static pgafSharedState *pgaf = NULL;
static HTAB *pgaf_hash = NULL;
/* Functions */
extern void _PG_init(void);
extern void _PG_fini(void);
static void cc_ProcessUtility(PEL_PROCESSUTILITY_PROTO);
static void flush_password_history(void);
static pgphEntry *pgph_entry_alloc(pgphHashKey *key, TimestampTz password_date);
static pgafEntry *pgaf_entry_alloc(pgafHashKey *key, float failure_count);
#if PG_VERSION_NUM >= 150000
static void pghist_shmem_request(void);
#endif
static void pghist_shmem_startup(void);
static void pgph_shmem_startup(void);
static void pgaf_shmem_startup(void);
#if PG_VERSION_NUM >= 120000
static int entry_cmp(const void *lhs, const void *rhs);
#endif
static Size pgph_memsize(void);
static void pg_password_history_internal(FunctionCallInfo fcinfo);
static void fix_log(ErrorData *edata);
static Size pgaf_memsize(void);
static void credcheck_max_auth_failure(Port *port, int status);
static float get_auth_failure(const char *username, Oid userid, int status);
static float save_auth_failure(Port *port, Oid userid);
static void remove_auth_failure(const char *username, Oid userid);
static void pg_banned_role_internal(FunctionCallInfo fcinfo);
/* Username flags*/
static int username_min_length = 1;
static int username_min_special = 0;
static int username_min_digit = 0;
static int username_min_upper = 0;
static int username_min_lower = 0;
static int username_min_repeat = 0;
static char *username_not_contain = NULL;
static char *username_contain = NULL;
static bool username_contain_password = true;
static bool username_ignore_case = false;
static char *username_whitelist = NULL;
static char *max_auth_whitelist = NULL;
/* Password flags*/
static int password_min_length = 1;
static int password_min_special = 0;
static int password_min_digit = 0;
static int password_min_upper = 0;
static int password_min_lower = 0;
static int password_min_repeat = 0;
static char *password_not_contain = NULL;
static char *password_contain = NULL;
static bool password_contain_username = true;
static bool password_ignore_case = false;
static int password_valid_until = 0;
static int password_valid_max = 0;
static int auth_delay_milliseconds = 0;
#if PG_VERSION_NUM >= 120000
/*
password_reuse_history:
number of distinct passwords set before a password can be reused.
password_reuse_interval:
amount of time it takes before a password can be reused again.
*/
static int password_reuse_history = 0;
static int password_reuse_interval = 0;
char *str_to_sha256(const char *str, const char *salt);
#endif
bool check_whitelist(char **newval, void **extra, GucSource source);
bool is_in_whitelist(char *username, char *whitelist);
static char *to_nlower(const char *str, size_t max) {
char *lower_str;
int i = 0;
lower_str = (char *)calloc(strlen(str), sizeof(char));
for (const char *p = str; *p && i < max; p++) {
lower_str[i++] = tolower(*p);
}
lower_str[i] = '\0';
return lower_str;
}
static bool str_contains(const char *chars, const char *str) {
for (const char *i = str; *i; i++) {
for (const char *j = chars; *j; j++) {
if (*i == *j) {
return true;
}
}
}
return false;
}
static void check_str_counters(const char *str, int *lower, int *upper,
int *digit, int *special) {
for (const char *i = str; *i; i++) {
if (islower(*i)) {
(*lower)++;
} else if (isupper(*i)) {
(*upper)++;
} else if (isdigit(*i)) {
(*digit)++;
} else {
(*special)++;
}
}
}
static bool char_repeat_exceeds(const char *str, int max_repeat) {
int occurred = 1;
size_t len = strlen(str);
/*if string has only one character, then no need to proceed further*/
if (len==1) {
return false;
}
for (size_t i = 0; i < len;) {
occurred = 1;
/*first character = str[i]
second character = str[i+1]
search for an adjacent repeated characters
for example, in this string "weekend summary"
search for the series "ee", "mm"
*/
for (size_t j = (i + 1), k = 1; j < len; j++, k++) {
/* character matched*/
if (str[i] == str[j]) {
/* is the previous, current character positions are adjacent*/
if (i + k == j) {
occurred++;
if (occurred > max_repeat) {
return true;
}
}
}
/* if we reach an end of the string, no need to process further*/
if (j + 1 == len) {
return false;
}
/* if the characters are not equal then point "i" to "j"*/
if (str[i] != str[j]) {
i = j;
break;
}
}
}
return false;
}
static void
username_check(const char *username, const char *password)
{
int user_total_special = 0;
int user_total_digit = 0;
int user_total_upper = 0;
int user_total_lower = 0;
char *tmp_pass = NULL;
char *tmp_user = NULL;
char *tmp_contains = NULL;
char *tmp_not_contains = NULL;
if (strcasestr(debug_query_string, "PASSWORD") != NULL)
statement_has_password = true;
/* checks has to be done by ignoring case */
if (username_ignore_case)
{
if (password != NULL && strlen(password) > 0)
tmp_pass = to_nlower(password, INT_MAX);
tmp_user = to_nlower(username, INT_MAX);
tmp_contains = to_nlower(username_contain, INT_MAX);
tmp_not_contains = to_nlower(username_not_contain, INT_MAX);
}
else
{
if (password != NULL && strlen(password) > 0)
tmp_pass = strndup(password, INT_MAX);
tmp_user = strndup(username, INT_MAX);
tmp_contains = strndup(username_contain, INT_MAX);
tmp_not_contains = strndup(username_not_contain, INT_MAX);
}
/* Rule 1: username length */
if (strnlen(tmp_user, INT_MAX) < username_min_length)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("username length should match the configured %s (%d)"),
"credcheck.username_min_length", username_min_length)));
goto clean;
}
/* Rule 2: username contains password
* Note:
* tmp_pass is NULL for ALTER USER ... RENAME TO ...;
* statement so this rule can not be applied.
*/
if (tmp_pass != NULL && username_contain_password)
{
if (strstr(tmp_user, tmp_pass)) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("username should not contain password"))));
goto clean;
}
}
/* Rule 3: contain characters */
if (tmp_contains != NULL && strlen(tmp_contains) > 0)
{
if (str_contains(tmp_contains, tmp_user) == false)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("username does not contain the configured %s characters: %s"),
"credcheck.username_contain", tmp_contains)));
goto clean;
}
}
/* Rule 4: not contain characters */
if (tmp_not_contains != NULL && strlen(tmp_not_contains) > 0)
{
if (str_contains(tmp_not_contains, tmp_user) == true)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("username contains the configured %s unauthorized characters: %s"),
"credcheck.username_not_contain", tmp_not_contains)));
goto clean;
}
}
check_str_counters(tmp_user, &user_total_lower, &user_total_upper,
&user_total_digit, &user_total_special);
/* Rule 5: total upper characters */
if (!username_ignore_case && user_total_upper < username_min_upper)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("username does not contain the configured %s characters (%d)",
"credcheck.username_min_upper", username_min_upper)));
goto clean;
}
/* Rule 6: total lower characters */
if (!username_ignore_case && user_total_lower < username_min_lower)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("username does not contain the configured %s characters (%d)",
"credcheck.username_min_lower", username_min_lower)));
goto clean;
}
/* Rule 7: total digits */
if (user_total_digit < username_min_digit)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("username does not contain the configured %s characters (%d)",
"credcheck.username_min_digit", username_min_digit)));
goto clean;
}
/* Rule 8: total special */
if (user_total_special < username_min_special)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("username does not contain the configured %s characters (%d)",
"credcheck.username_min_special", username_min_special)));
goto clean;
}
/* Rule 9: minimum char repeat */
if (username_min_repeat)
{
if (char_repeat_exceeds(tmp_user, username_min_repeat))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("%s characters are repeated more than the "
"configured %s times (%d)"), "username", "credcheck.username_min_repeat", username_min_repeat)));
goto clean;
}
}
clean:
free(tmp_pass);
free(tmp_user);
free(tmp_contains);
free(tmp_not_contains);
}
/* We just check that the list is valid, no username existing check */
bool
check_whitelist(char **newval, void **extra, GucSource source)
{
char *rawstring;
List *elemlist;
/* Need a modifiable copy of string */
rawstring = pstrdup(*newval);
/* Parse string into list of identifiers */
if (!SplitIdentifierString(rawstring, ',', &elemlist))
{
/* syntax error in list */
GUC_check_errdetail("List syntax is invalid.");
pfree(rawstring);
list_free(elemlist);
return false;
}
pfree(rawstring);
list_free(elemlist);
return true;
}
/* check if the username is in the whitelist */
bool
is_in_whitelist(char *username, char *whitelist)
{
char *rawstring;
List *elemlist;
ListCell *l;
int len = 0;
Assert(username != NULL);
Assert(whitelist != NULL);
len = strlen(whitelist);
if (len == 0)
return false;
/* Need a modifiable copy of string */
rawstring = palloc0(sizeof(char) * (len+1));
strcpy(rawstring, whitelist);
/* Parse string into list of identifiers */
if (!SplitIdentifierString(rawstring, ',', &elemlist))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("username list is invalid: %s", whitelist)));
list_free(elemlist);
pfree(rawstring);
return false;
}
foreach(l, elemlist)
{
char *tok = (char *) lfirst(l);
/* the username is in the list */
if (pg_strcasecmp(tok, username) == 0)
{
list_free(elemlist);
pfree(rawstring);
return true;
}
}
list_free(elemlist);
pfree(rawstring);
return false;
}
static void password_check(const char *username, const char *password)
{
int pass_total_special = 0;
int pass_total_digit = 0;
int pass_total_upper = 0;
int pass_total_lower = 0;
char *tmp_pass = NULL;
char *tmp_user = NULL;
char *tmp_contains = NULL;
char *tmp_not_contains = NULL;
Assert(username != NULL);
Assert(password != NULL);
/* checks has to be done by ignoring case */
if (password_ignore_case)
{
tmp_pass = to_nlower(password, INT_MAX);
tmp_user = to_nlower(username, INT_MAX);
tmp_contains = to_nlower(password_contain, INT_MAX);
tmp_not_contains = to_nlower(password_not_contain, INT_MAX);
}
else
{
tmp_pass = strndup(password, INT_MAX);
tmp_user = strndup(username, INT_MAX);
tmp_contains = strndup(password_contain, INT_MAX);
tmp_not_contains = strndup(password_not_contain, INT_MAX);
}
/* Rule 1: password length */
if (strnlen(tmp_pass, INT_MAX) < password_min_length)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("password length should match the configured %s (%d)"),
"credcheck.password_min_length", password_min_length)));
goto clean;
}
/* Rule 2: password contains username */
if (password_contain_username)
{
if (strstr(tmp_pass, tmp_user))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("password should not contain username"))));
goto clean;
}
}
/* Rule 3: contain characters */
if (tmp_contains != NULL && strlen(tmp_contains) > 0)
{
if (str_contains(tmp_contains, tmp_pass) == false)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("password does not contain the configured %s characters: %s"),
"credcheck.password_contain", tmp_contains)));
goto clean;
}
}
/* Rule 4: not contain characters */
if (tmp_not_contains != NULL && strlen(tmp_not_contains) > 0)
{
if (str_contains(tmp_not_contains, tmp_pass) == true)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg(gettext_noop("password contains the configured %s unauthorized characters: %s"),
"credcheck.password_not_contain", tmp_not_contains)));
goto clean;
}
}
check_str_counters(tmp_pass, &pass_total_lower, &pass_total_upper,
&pass_total_digit, &pass_total_special);
/* Rule 5: total upper characters */
if (!password_ignore_case && pass_total_upper < password_min_upper)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("password does not contain the configured %s characters (%d)",
"credcheck.password_min_upper", password_min_upper)));
goto clean;
}
/* Rule 6: total lower characters */
if (!password_ignore_case && pass_total_lower < password_min_lower)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("password does not contain the configured %s characters (%d)",
"credcheck.password_min_lower", password_min_lower)));
goto clean;
}
/* Rule 7: total digits */
if (pass_total_digit < password_min_digit)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("password does not contain the configured %s characters (%d)",
"credcheck.password_min_digit", password_min_digit)));
goto clean;
}
/* Rule 8: total special */
if (pass_total_special < password_min_special)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("password does not contain the configured %s characters (%d)",
"credcheck.password_min_special", password_min_special)));
goto clean;
}
/* Rule 9: minimum char repeat */
if (password_min_repeat)
{
if (char_repeat_exceeds(tmp_pass, password_min_repeat))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
errmsg("%s characters are repeated more than the "
"configured %s times (%d)", "password",
"credcheck.password_min_repeat", password_min_repeat)));
goto clean;
}
}
clean:
free(tmp_pass);
free(tmp_user);
free(tmp_contains);
free(tmp_not_contains);
}
static void
username_guc()
{
DefineCustomIntVariable("credcheck.username_min_length",
gettext_noop("minimum username length"), NULL,
&username_min_length, 1, 1, INT_MAX, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.username_min_special",
gettext_noop("minimum username special characters"),
NULL, &username_min_special, 0, 0, INT_MAX,
PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.username_min_digit",
gettext_noop("minimum username digits"), NULL,
&username_min_digit, 0, 0, INT_MAX, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.username_min_upper",
gettext_noop("minimum username uppercase letters"),
NULL, &username_min_upper, 0, 0, INT_MAX, PGC_SUSET,
0, NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.username_min_lower",
gettext_noop("minimum username lowercase letters"),
NULL, &username_min_lower, 0, 0, INT_MAX, PGC_SUSET,
0, NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.username_min_repeat",
gettext_noop("minimum username characters repeat"),
NULL, &username_min_repeat, 0, 0, INT_MAX,
PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomBoolVariable("credcheck.username_contain_password",
gettext_noop("username contains password"), NULL,
&username_contain_password, true, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomBoolVariable("credcheck.username_ignore_case",
gettext_noop("ignore case while username checking"),
NULL, &username_ignore_case, false, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomStringVariable(
"credcheck.username_not_contain",
gettext_noop("username should not contain these characters"), NULL,
&username_not_contain, "", PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomStringVariable(
"credcheck.username_contain",
gettext_noop("password should contain these characters"), NULL,
&username_contain, "", PGC_SUSET, 0, NULL, NULL, NULL);
}
static void
password_guc()
{
DefineCustomIntVariable("credcheck.password_min_length",
gettext_noop("minimum password length"), NULL,
&password_min_length, 1, 1, INT_MAX, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.password_min_special",
gettext_noop("minimum special characters"), NULL,
&password_min_special, 0, 0, INT_MAX, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.password_min_digit",
gettext_noop("minimum password digits"), NULL,
&password_min_digit, 0, 0, INT_MAX, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.password_min_upper",
gettext_noop("minimum password uppercase letters"),
NULL, &password_min_upper, 0, 0, INT_MAX, PGC_SUSET,
0, NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.password_min_lower",
gettext_noop("minimum password lowercase letters"),
NULL, &password_min_lower, 0, 0, INT_MAX, PGC_SUSET,
0, NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.password_min_repeat",
gettext_noop("minimum password characters repeat"),
NULL, &password_min_repeat, 0, 0, INT_MAX,
PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomBoolVariable("credcheck.password_contain_username",
gettext_noop("password contains username"), NULL,
&password_contain_username, true, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomBoolVariable("credcheck.password_ignore_case",
gettext_noop("ignore case while password checking"),
NULL, &password_ignore_case, false, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomStringVariable(
"credcheck.password_not_contain",
gettext_noop("password should not contain these characters"), NULL,
&password_not_contain, "", PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomStringVariable(
"credcheck.password_contain",
gettext_noop("password should contain these characters"), NULL,
&password_contain, "", PGC_SUSET, 0, NULL, NULL, NULL);
#if PG_VERSION_NUM >= 120000
DefineCustomIntVariable("credcheck.password_reuse_history",
gettext_noop("minimum number of password changes before permitting reuse"),
NULL, &password_reuse_history, 0, 0, 100,
PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.password_reuse_interval",
gettext_noop("minimum number of days elapsed before permitting reuse"),
NULL, &password_reuse_interval, 0, 0, 730, /* max 2 years */
PGC_SUSET, 0, NULL, NULL, NULL);
#endif
DefineCustomIntVariable("credcheck.password_valid_until",
gettext_noop("force use of VALID UNTIL clause in CREATE ROLE statement"
" with a minimum number of days"),
NULL, &password_valid_until, 0, 0, INT_MAX,
PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomIntVariable("credcheck.password_valid_max",
gettext_noop("force use of VALID UNTIL clause in CREATE ROLE statement"
" with a maximum number of days"),
NULL, &password_valid_max, 0, 0, INT_MAX,
PGC_SUSET, 0, NULL, NULL, NULL);
}
#if PG_VERSION_NUM >= 120000
static void
save_password_in_history(const char *username, const char *password)
{
char *encrypted_password;
pgphHashKey key;
pgphEntry *entry;
TimestampTz dt_now = GetCurrentTimestamp();
Assert(username != NULL);
Assert(password != NULL);
if (password_reuse_history == 0 && password_reuse_interval == 0)
return;
/* Safety check... */
if (!pgph || !pgph_hash)
return;
/* Encrypt the password to the requested format. */
encrypted_password = strdup(str_to_sha256(password, username));
/* Store the password into share memory and password history file */
/* Set up key for hashtable search */
strcpy(key.rolename, username) ;
strcpy(key.password_hash, encrypted_password);
/* Lookup the hash table entry with exclusive lock. */
LWLockAcquire(pgph->lock, LW_EXCLUSIVE);
/* Create new entry, if not present */
entry = (pgphEntry *) hash_search(pgph_hash, &key, HASH_FIND, NULL);
if (!entry)
{
dt_now = GetCurrentTimestamp();
elog(DEBUG1, "Add new entry in history hash table: (%s, '%s', '%s')",
username, encrypted_password,
timestamptz_to_str(dt_now));
/* OK to create a new hashtable entry */
entry = pgph_entry_alloc(&key, dt_now);
/* Flush the new entry to disk */
if (entry)
{
elog(DEBUG1, "entry added, flush change to disk");
flush_password_history();
}
}
LWLockRelease(pgph->lock);
free(encrypted_password);
}
static void
rename_user_in_history(const char *username, const char *newname)
{
pgphEntry *entry;
HASH_SEQ_STATUS hash_seq;
int num_changed = 0;
if (password_reuse_history == 0 && password_reuse_interval == 0)
return;
Assert(username != NULL);
Assert(newname != NULL);
/* Safety check ... shouldn't get here unless shmem is set up. */
if (!pgph || !pgph_hash)
return;
elog(DEBUG1, "renaming user %s to %s into password history", username, newname);
LWLockAcquire(pgph->lock, LW_EXCLUSIVE);
hash_seq_init(&hash_seq, pgph_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
/* update the key of matching entries */
if (strcmp(entry->key.rolename, username) == 0)
{
pgphHashKey key;
strcpy(key.rolename, newname) ;
strcpy(key.password_hash, entry->key.password_hash);
hash_update_hash_key(pgph_hash, entry, &key);
num_changed++;
}
}
if (num_changed > 0)
{
elog(DEBUG1, "%d entries in paswword history hash table have been mofidied for user %s",
num_changed,
username);
/* Flush the new entry to disk */
flush_password_history();
}
LWLockRelease(pgph->lock);
}
/*
* qsort comparator for sorting into increasing usage order
*/
#if PG_VERSION_NUM >= 120000
static int
entry_cmp(const void *lhs, const void *rhs)
{
TimestampTz l_password_date = (*(pgphEntry *const *) lhs)->password_date;
TimestampTz r_password_date = (*(pgphEntry *const *) rhs)->password_date;
if (l_password_date < r_password_date)
return -1;
else if (l_password_date > r_password_date)
return +1;
else
return 0;
}
#endif
static void
remove_password_from_history(const char *username, const char *password, int numentries)
{
char *encrypted_password;
int32 num_entries;
int32 num_user_entries = 0;
int32 num_removed = 0;
pgphEntry *entry;
HASH_SEQ_STATUS hash_seq;
pgphEntry **entries;
int i = 0;
if (password_reuse_history == 0 && password_reuse_interval == 0)
return;
Assert(username != NULL);
Assert(password != NULL);
/* Safety check ... shouldn't get here unless shmem is set up. */
if (!pgph || !pgph_hash)
return;
/* Encrypt the password to the requested format. */
encrypted_password = strdup(str_to_sha256(password, username));
elog(DEBUG1, "attempting to remove historized password = '%s' for user = '%s'", encrypted_password, username);
LWLockAcquire(pgph->lock, LW_EXCLUSIVE);
num_entries = hash_get_num_entries(pgph_hash);
hash_seq_init(&hash_seq, pgph_hash);
entries = palloc(num_entries * sizeof(pgphEntry *));
/* stores entries related to the username to be sorted by date */
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
if (strcmp(entry->key.rolename, username) == 0)
entries[i++] = entry;
}