File: credcheck.c

package info (click to toggle)
credcheck 4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 424 kB
  • sloc: ansic: 1,994; sql: 859; makefile: 21; sh: 1
file content (2819 lines) | stat: -rw-r--r-- 81,879 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
/*-------------------------------------------------------------------------
 *
 * 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/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/parallel.h"

#include "catalog/catalog.h"
#include "catalog/indexing.h"
#include "catalog/pg_auth_members.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_db_role_setting.h"
#include "commands/user.h"
#include "common/int.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/datetime.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"

#define NOT_IN_PARALLEL_WORKER (ParallelWorkerNumber < 0)

/* 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 ExecutorStart_hook_type prev_ExecutorStart = 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 cc_ExecutorStart(QueryDesc *queryDesc, int eflags);

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);
static void set_force_change_password(Oid databaseid, Oid roleid, char *valuestr);
static void reset_force_change_password(Oid databaseid, Oid roleid);

/* 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_warning = 0;
static int password_valid_max = 0;
static int auth_delay_milliseconds = 0;
static bool password_change_first_login = false;
static bool force_change_password = false;

#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) {
    char *chars_copy;
    char *token;
    /* Make a copy of chars since strtok modifies the string */
    chars_copy = pstrdup(chars);
    
    token = strtok(chars_copy, ",");
    while (token != NULL) {
        if (strstr(str, token) != NULL) {
            return true;
        }
        token = strtok(NULL, ",");
    }    
    pfree(chars_copy);
    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 or set it automatically to "
					" now() + password_valid_until days in the ALTER ROLE statement"
					" when the password is changed"),
				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, 1, NULL, NULL, NULL);

	DefineCustomIntVariable("credcheck.password_valid_warning",
				gettext_noop("throw a warning N days before the password expires"),
				NULL, &password_valid_warning, 0, 0, INT_MAX,
				PGC_SUSET, 0, NULL, NULL, NULL);

	DefineCustomBoolVariable("credcheck.password_change_first_login",
				gettext_noop("force the user to change his password at first login"),
				NULL, &password_change_first_login, false, PGC_SUSET, 0,
				NULL, NULL, NULL);

	DefineCustomBoolVariable("credcheck_internal.force_change_password",
				gettext_noop("force the user to change his password at first login"),
				NULL, &force_change_password, false, 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;
	}

	if (i == 0)
	{
		elog(DEBUG1, "no entry in the history for user: %s", username);

		LWLockRelease(pgph->lock);

		pfree(entries);

		return;
	}

	num_user_entries = i;

	/* Sort into increasing order by date */
	qsort(entries, i, sizeof(pgphEntry *), entry_cmp);

	/*
	 * Remove the oldest tuples when password_reuse_history is reached
	 * until password_reuse_history size is respected for this user,
	 * except if password_reuse_interval is enabled and not reached.
	 *
	 * A ascending index must exits on the date column of the table,
	 * we use this index to treat the oldest entries first in the scan.
	 */
	for (i = 0; i < num_user_entries; i++)
        {
		bool keep = false;

		/* if we have a retention delay remove entries that has expired */
		if (password_reuse_interval > 0)
		{
			TimestampTz     dt_now = GetCurrentTimestamp();
			float8          result;

			result = ((float8) (dt_now - entries[i]->password_date)) / 1000000.0; /* in seconds */
			result /= 86400; /* in days */

			elog(DEBUG1, "password_reuse_interval: %d, entry age: %d",
										password_reuse_interval,
										(int) result);
			/*
			 * When the delay have not expired, keep the entry if the
			 * number of entry exceed password_reuse_history
			 */
			if (password_reuse_interval >= (int) result)
				keep = true;
			else
				elog(DEBUG1, "remove_password_from_history(): this history entry has expired");
		}

		if (!keep)
		{
			/* we need to remove the entries that exceed history size */
			if ((num_user_entries - i) >= password_reuse_history)
			{
				elog(DEBUG1, "removing entry %d from the history (%s, %s)", i,
											entries[i]->key.rolename,
											entries[i]->key.password_hash);
				hash_search(pgph_hash, &entries[i]->key, HASH_REMOVE, NULL);
				num_removed++;
			}
		}
	}
	pfree(entries);

	/* Flush the new entry to disk */
	if (num_removed > 0)
		flush_password_history();

	LWLockRelease(pgph->lock);
}

static void
remove_user_from_history(const char *username)
{
        int32       num_removed = 0;
        pgphEntry  *entry;
	HASH_SEQ_STATUS hash_seq;

	if (password_reuse_history == 0 && password_reuse_interval == 0)
		return;

	Assert(username != NULL);

        /* Safety check ... shouldn't get here unless shmem is set up. */
        if (!pgph || !pgph_hash)
                return;

	elog(DEBUG1, "removing user %s from password history", username);

	/* Lookup the hash table entry with exclusive lock. */
	LWLockAcquire(pgph->lock, LW_EXCLUSIVE);

        hash_seq_init(&hash_seq, pgph_hash);

	/* Sequential scan of the hash table to find the entries to remove */
        while ((entry = hash_seq_search(&hash_seq)) != NULL)
        {
		if (strcmp(entry->key.rolename, username) == 0)
		{
			hash_search(pgph_hash, &entry->key, HASH_REMOVE, NULL);
			num_removed++;
		}
	}

	/* Flush the new entry to disk */
	if (num_removed > 0)
		flush_password_history();

	LWLockRelease(pgph->lock);
}

/* Check if the password can be reused */
static bool
check_password_reuse(const char *username, const char *password)
{
	int           count_in_history = 0;
	pgphEntry    *entry;
	bool          found = false;
	char         *encrypted_password;
	HASH_SEQ_STATUS hash_seq;

	Assert(username != NULL);

	if (password == NULL)
		return false;

	if (password_reuse_history == 0 && password_reuse_interval == 0)
		return false;

	/* Safety check... */
	if (!pgph || !pgph_hash)
		return false;

	/* Encrypt the password to the requested format. */
	encrypted_password = strdup(str_to_sha256(password, username));

	elog(DEBUG1, "Looking for registered password = '%s' for username = '%s'", encrypted_password, username);

	/* Lookup the hash table entry with shared lock. */
	LWLockAcquire(pgph->lock, LW_SHARED);

        hash_seq_init(&hash_seq, pgph_hash);
        while ((entry = hash_seq_search(&hash_seq)) != NULL)
        {
                if (strcmp(entry->key.rolename, username) == 0)
                {
			/* if the password is found in the history remove it if the interval is passed */
			if (strcmp(encrypted_password, entry->key.password_hash) == 0)
			{
				elog(DEBUG1, "password found in history, username = '%s',"
					     " password: '%s', saved at date: '%s'", username, 
									     entry->key.password_hash,
									     timestamptz_to_str(entry->password_date));

				/* mark that the password hash was found in the history */
				found = true;

				/* Check the password age against the reuse interval */
				if (password_reuse_interval > 0)
				{
					TimestampTz       dt_now = GetCurrentTimestamp();
					float8          result;
					result = ((float8) (dt_now - entry->password_date)) / 1000000.0; /* in seconds */
					result /= 86400; /* in days */
					elog(DEBUG1, "password_reuse_interval: %d, entry age: %d",
												password_reuse_interval,
												(int) result);

					/*
					 * if the delay have expired skip the entry, it will be
					 * removed later in remove_password_from_history()
					 */
					if (password_reuse_interval < (int) result)
					{
						elog(DEBUG1, "this history entry has expired");
						found = false;
						count_in_history--;
					}
				}
			}

			/*
			 * Even if the password was found we continue to count the number of
			 * password stored in the history for this user. This count is used
			 * to remove the oldest password that exceed the password_reuse_history
			 */
			count_in_history++;
                }
	}

	LWLockRelease(pgph->lock);

	free(encrypted_password);

	if (found)
		ereport(ERROR,
			(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
				errmsg(gettext_noop("Cannot use this credential following the password reuse policy"))));

	/* Password not found, remove passwords exceeding the history size */
	remove_password_from_history(username, password, count_in_history);

	/* The password was not found, add the password to the history */
	return true;
}
#endif

/* Return the number of days between current timestamp and the date given as parameter */
static int
check_valid_until(char *valid_until_date)
{
	int days = 0;

	elog(DEBUG1, "option VALID UNTIL date: %s", valid_until_date);

	if (valid_until_date)
	{
		Datum           validUntil_datum;
		TimestampTz       dt_now = GetCurrentTimestamp();
		TimestampTz       valid_date;
		float8          result;

		validUntil_datum = DirectFunctionCall3(timestamptz_in,
									CStringGetDatum(valid_until_date),
									ObjectIdGetDatum(InvalidOid),
									Int32GetDatum(-1));
		valid_date = DatumGetTimestampTz(validUntil_datum);

		result = ((float8) (valid_date - dt_now)) / 1000000.0; /* in seconds */
		result /= 86400; /* in days */
		days = (int) result;

		elog(DEBUG1, "option VALID UNTIL in days: %d", days);
	}

	return days;
}

static void
check_password(const char *username, const char *password,
                           PasswordType password_type, Datum validuntil_time,
                           bool validuntil_null)
{

	switch (password_type)
	{
		case PASSWORD_TYPE_PLAINTEXT:
		{
#ifdef USE_CRACKLIB
			const char *reason;
#endif
			if (is_in_whitelist((char *)username, username_whitelist))
				break;

			statement_has_password = true;
			username_check(username, password);
			if (password != NULL)
			{
				password_check(username, password);
#ifdef USE_CRACKLIB
				/* call cracklib to check password */
				if ((reason = FascistCheck(password, CRACKLIB_DICTPATH)))
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("password is easily cracked"),
							 errdetail_log("cracklib diagnostic: %s", reason)));
#endif
			}
			break;
		}
		default:
			if (!encrypted_password_allowed)
				ereport(ERROR,
					(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
						errmsg(gettext_noop("password type is not a plain text"))));
			break;
	}
}

void
_PG_init(void)
{
	/* Defined GUCs */
	username_guc();
	password_guc();

	if (process_shared_preload_libraries_in_progress)
	{
		DefineCustomIntVariable("credcheck.history_max_size",
					gettext_noop("maximum of entries in the password history"), NULL,
					&pgph_max, 65535, 1, (INT_MAX / 1024), PGC_POSTMASTER, 0,
					NULL, NULL, NULL);

		DefineCustomIntVariable("credcheck.auth_failure_cache_size",
					gettext_noop("maximum of entries in the auth failure cache"), NULL,
					&pgaf_max, 1024, 1, (INT_MAX / 1024), PGC_POSTMASTER, 0,
					NULL, NULL, NULL);
	}

	DefineCustomBoolVariable("credcheck.no_password_logging",
				gettext_noop("prevent exposing the password in error messages logged"),
				NULL, &no_password_logging, true, PGC_SUSET, 0,
				NULL, NULL, NULL);

	DefineCustomIntVariable("credcheck.max_auth_failure",
				gettext_noop("maximum number of authentication failure before"
				" the user loggin account be invalidated"), NULL,
				&fail_max, 0, 0, 64, PGC_SUSET, 0,
				NULL, NULL, NULL);

	DefineCustomBoolVariable("credcheck.reset_superuser",
				gettext_noop("restore superuser acces when he have been banned."),
				NULL, &reset_superuser, false, PGC_SIGHUP, 0,
				NULL, NULL, NULL);

	DefineCustomBoolVariable("credcheck.encrypted_password_allowed",
				gettext_noop("allow encrypted password to be used or throw an error"),
				NULL, &encrypted_password_allowed, false, PGC_SUSET, 0,
				NULL, NULL, NULL);

	DefineCustomStringVariable(
				"credcheck.whitelist",
				gettext_noop("comma separated list of username to exclude from password policy check"), NULL,
				&username_whitelist, "", PGC_SUSET, 0, check_whitelist, NULL, NULL);

	DefineCustomIntVariable("credcheck.auth_delay_ms",
				"Milliseconds to delay before reporting authentication failure",
				NULL,
				&auth_delay_milliseconds,
				0,
				0, INT_MAX / 1000,
				PGC_SIGHUP,
				GUC_UNIT_MS,
				NULL,
				NULL,
				NULL);

	DefineCustomStringVariable(
				"credcheck.whitelist_auth_failure",
				gettext_noop("comma separated list of username to exclude from max authentication failure check"), NULL,
				&max_auth_whitelist, "", PGC_SUSET, 0, check_whitelist, NULL, NULL);

#if PG_VERSION_NUM < 150000
	EmitWarningsOnPlaceholders("credcheck");
	EmitWarningsOnPlaceholders("credcheck_internal");

        /*
         * Request additional shared resources.  (These are no-ops if we're not in
         * the postmaster process.)  We'll allocate or attach to the shared
         * resources in pgph_shmem_startup().
         */
        RequestAddinShmemSpace(pgph_memsize());
        RequestNamedLWLockTranche(PGPH_TRANCHE_NAME, 1);
        RequestAddinShmemSpace(pgaf_memsize());
        RequestNamedLWLockTranche(PGAF_TRANCHE_NAME, 1);
#else
	MarkGUCPrefixReserved("credcheck");
	MarkGUCPrefixReserved("credcheck_internal");

#endif

	/* Install hooks */
	prev_ProcessUtility = ProcessUtility_hook;
	ProcessUtility_hook = cc_ProcessUtility;
	prev_check_password_hook = check_password_hook;
	check_password_hook = check_password;
#if PG_VERSION_NUM >= 150000
	prev_shmem_request_hook = shmem_request_hook;
	shmem_request_hook = pghist_shmem_request;
#endif
        prev_shmem_startup_hook = shmem_startup_hook;
        shmem_startup_hook = pghist_shmem_startup;

	prev_log_hook = emit_log_hook;
	emit_log_hook = fix_log;

	prev_ClientAuthentication = ClientAuthentication_hook;
	ClientAuthentication_hook = credcheck_max_auth_failure;

	prev_ExecutorStart = ExecutorStart_hook;
	ExecutorStart_hook = cc_ExecutorStart;
}

void
_PG_fini(void)
{
	/* Uninstall hooks */
	check_password_hook = prev_check_password_hook;
	ProcessUtility_hook = prev_ProcessUtility;
	emit_log_hook = prev_log_hook;
#if PG_VERSION_NUM >= 150000
	shmem_request_hook = prev_shmem_request_hook;
#endif
	shmem_startup_hook = prev_shmem_startup_hook;
	ClientAuthentication_hook = prev_ClientAuthentication;
}

static void
cc_ProcessUtility(PEL_PROCESSUTILITY_PROTO)
{
	if (NOT_IN_PARALLEL_WORKER)
	{
		Node *parsetree = pstmt->utilityStmt;

		/* at first login we don't allow anything else than password change */
		/*
		 * When first login we don't allow anything else than password change.
		 * Command \password issue a "show password_encryption" query after
		 * change password prompts, allow it. The \password command will be
		 * rejected anyway because it uses encrypted password.
		 */
		if (!is_in_whitelist(MyProcPort->user_name, username_whitelist))
		{
			if (nodeTag(parsetree) != T_AlterRoleStmt && force_change_password
				&& strcmp(debug_query_string, "show password_encryption") != 0)
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
							errmsg(gettext_noop("you must change your password first."))));
		}
		statement_has_password = false;

		switch (nodeTag(parsetree))
		{
			/* Intercept ALTER USER .. RENAME statements */
			case T_RenameStmt:
			{
				RenameStmt *stmt = (RenameStmt *)parsetree;

				/* We only take care of user renaming */
				if (stmt->renameType == OBJECT_ROLE && stmt->newname != NULL)
				{
					if (is_in_whitelist(stmt->newname, username_whitelist) || is_in_whitelist(stmt->subname, username_whitelist))
						break;
				
					/* check the validity of the username */
					username_check(stmt->newname, NULL);

#if PG_VERSION_NUM >= 120000
					/* rename the user in the history table */
					rename_user_in_history(stmt->subname, stmt->newname);
#endif
				}
				break;
			}

			case T_AlterRoleStmt:
			{
				AlterRoleStmt *stmt = (AlterRoleStmt *)parsetree;
				ListCell      *option;
				char          *password;
				bool           save_password = false;
				DefElem    *dvalidUntil = NULL;
				DefElem    *dpassword = NULL;

				if (is_in_whitelist(stmt->role->rolename, username_whitelist))
					break;

				/* Extract options from the statement node tree */
				foreach(option, stmt->options)
				{
					DefElem    *defel = (DefElem *) lfirst(option);

					if (strcmp(defel->defname, "password") == 0)
					{
						dpassword = defel;
					}
					else if (strcmp(defel->defname, "validUntil") == 0)
					{
						dvalidUntil = defel;
					}
				}

				if (dpassword == NULL && force_change_password)
						ereport(ERROR,
							(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
								errmsg(gettext_noop("you must change your password first."))));

#if PG_VERSION_NUM >= 120000
				/* check the password set */
				if (dpassword && dpassword->arg)
				{
					statement_has_password = true;
					password = strVal(dpassword->arg);
					save_password = check_password_reuse(stmt->role->rolename, password);
				}
#endif
				/*
				 * when the user change his password, automatically set the valid until
				 * date to now() + password_valid_until days if password_valid_until is set.
				 */
				if (!dvalidUntil && password_valid_until > 0)
				{
					Timestamp dt_now = GetCurrentTimestamp();
					struct pg_tm tt, *tm = &tt;
					fsec_t          fsec;
					int             julian;
					char           *validuntil;

					if (timestamp2tm(dt_now, NULL, tm, &fsec, NULL, NULL) != 0)
						ereport(ERROR,
								(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
								 errmsg("timestamp out of range")));

					/*
					 * Add credcheck.password_valid_until days by converting to and from Julian.
					 */
					julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
					if (pg_add_s32_overflow(julian, password_valid_until+1, &julian) ||
						julian < 0)
						ereport(ERROR,
								(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
								 errmsg("timestamp out of range")));
					j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
					validuntil = malloc(sizeof(char)*11);
					sprintf(validuntil, "%d-%d-%d", tm->tm_year, tm->tm_mon, tm->tm_mday);
					dvalidUntil = makeDefElem("validUntil", (Node *) makeString(validuntil), -1);
					((AlterRoleStmt *)parsetree)->options = lappend(((AlterRoleStmt *)parsetree)->options, dvalidUntil);
				}

				/* when a valid until date is set check that it is > to password_valid_until */
				if (dvalidUntil && dvalidUntil->arg && password_valid_until > 0)
				{
					int valid_until = check_valid_until(strVal(dvalidUntil->arg));
					if (valid_until < password_valid_until)
						ereport(ERROR,
							(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
								errmsg(gettext_noop("the VALID UNTIL option must have a date older than %d days"), password_valid_until)));
				}
				/* check that the valid until date is not under the limit of days */
				if (dvalidUntil && dvalidUntil->arg && password_valid_max > 0)
				{
					int valid_max = check_valid_until(strVal(dvalidUntil->arg));
					if (valid_max > password_valid_max)
						ereport(ERROR,
							(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
								errmsg(gettext_noop("the VALID UNTIL option must NOT have a date beyond %d days"), password_valid_max)));
				}

#if PG_VERSION_NUM >= 120000
				/* The password can be saved into the history */
				if (save_password)
					save_password_in_history(stmt->role->rolename, password);
#endif
				if (force_change_password)
				{
					reset_force_change_password(0, get_role_oid(stmt->role->rolename, true));
					force_change_password = false;
				}

				break;
			}

			case T_CreateRoleStmt:
			{
				CreateRoleStmt *stmt = (CreateRoleStmt *)parsetree;
				ListCell       *option;
				int             valid_until = 0;
				int             valid_max = 0;
				bool            has_valid_until = false; 
				bool            save_password = false;
				char           *password;
				DefElem    *dpassword = NULL;
				DefElem    *dvalidUntil = NULL;

				if (is_in_whitelist(stmt->role, username_whitelist))
					break;

				/* check the validity of the username */
				username_check(stmt->role, NULL);

				/* Extract options from the statement node tree */
				foreach(option, stmt->options)
				{
					DefElem    *defel = (DefElem *) lfirst(option);

					if (strcmp(defel->defname, "password") == 0)
					{
						dpassword = defel;
					}
					else if (strcmp(defel->defname, "validUntil") == 0)
					{
						dvalidUntil = defel;
					}
				}
#if PG_VERSION_NUM >= 120000
				if (dpassword && dpassword->arg)
				{
					statement_has_password = true;
					password = strVal(dpassword->arg);
					save_password = check_password_reuse(stmt->role, password);
				}
#endif
				/*
				 * At user creation automatically set the valid until date to now() + password_valid_until
				 * days if password_valid_until is set.
				 */
				if (!dvalidUntil && password_valid_until > 0)
				{
					Timestamp dt_now = GetCurrentTimestamp();
					struct pg_tm tt, *tm = &tt;
					fsec_t          fsec;
					int             julian;
					char            *validuntil;

					if (timestamp2tm(dt_now, NULL, tm, &fsec, NULL, NULL) != 0)
						ereport(ERROR,
								(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
								 errmsg("timestamp out of range")));

					/*
					 * Add credcheck.password_valid_until days by converting to and from Julian.
					 */
					julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
					if (pg_add_s32_overflow(julian, password_valid_until+1, &julian) ||
						julian < 0)
						ereport(ERROR,
								(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
								 errmsg("timestamp out of range")));
					j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
					validuntil = malloc(sizeof(char)*11);
					sprintf(validuntil, "%d-%d-%d", tm->tm_year, tm->tm_mon, tm->tm_mday);
					dvalidUntil = makeDefElem("validUntil", (Node *) makeString(validuntil), 1);
					((CreateRoleStmt *)parsetree)->options = lappend(((CreateRoleStmt *)parsetree)->options, dvalidUntil);
				}

				if (dvalidUntil && dvalidUntil->arg && password_valid_until > 0)
				{
					valid_until = check_valid_until(strVal(dvalidUntil->arg));
					has_valid_until = true;
				}
				if (dvalidUntil && dvalidUntil->arg && password_valid_max > 0)
				{
					valid_max = check_valid_until(strVal(dvalidUntil->arg));
					has_valid_until = true;
				}

				/* check that a VALID UNTIL option is present */
				if ( !has_valid_until && (password_valid_until > 0 || password_valid_max > 0) )
					ereport(ERROR,
						(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
							errmsg(gettext_noop("require a VALID UNTIL option"))));

				/* check that a minimum number of days for password validity is defined */
				if (password_valid_until > 0 && valid_until < password_valid_until)
					ereport(ERROR,
						(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
							errmsg(gettext_noop("require a VALID UNTIL option with a date older than %d days"), password_valid_until)));

				/* check that a maximum number of days for password validity is defined */
				if (password_valid_max > 0 && valid_max < password_valid_max)
					ereport(ERROR,
						(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
							errmsg(gettext_noop("require a VALID UNTIL option with a date beyond %d days"), password_valid_max)));

				/* set force change password option if password_change_first_login is set */
				if (password_change_first_login)
					set_force_change_password(0, get_role_oid(stmt->role, true), "true");

#if PG_VERSION_NUM >= 120000
				/* The password can be saved into the history */
				if (save_password)
					save_password_in_history(stmt->role, password);
#endif
				break;
			}

#if PG_VERSION_NUM >= 120000
			case T_DropRoleStmt:
			{
				DropRoleStmt *stmt = (DropRoleStmt *)parsetree;
				ListCell   *item;

				foreach(item, stmt->roles)
				{
					RoleSpec   *rolspec = lfirst(item);

					remove_user_from_history(rolspec->rolename);
				}
				break;
			}
#endif
			default:
				break;
		}
	}

	/* Execute the utility command now */
	if (prev_ProcessUtility)
		prev_ProcessUtility(PEL_PROCESSUTILITY_ARGS);
	else
		standard_ProcessUtility(PEL_PROCESSUTILITY_ARGS);

}

#if PG_VERSION_NUM >= 120000
#if PG_VERSION_NUM >= 140000
char *
str_to_sha256(const char *password, const char *salt)
{
	int          password_len = strlen(password);
	int          saltlen = strlen(salt);
	uint8        checksumbuf[PG_SHA256_DIGEST_LENGTH];
	char        *result = palloc0(sizeof (char) * PG_SHA256_DIGEST_STRING_LENGTH);
	pg_hmac_ctx *hmac_ctx = pg_hmac_create(PG_SHA256);

	if (hmac_ctx == NULL)
	{
		pfree(result);
		elog(ERROR, gettext_noop("credcheck could not initialize checksum context"));
	}

	if (pg_hmac_init(hmac_ctx, (uint8 *) password, password_len) < 0 ||
			pg_hmac_update(hmac_ctx, (uint8 *) salt, saltlen) < 0 ||
			pg_hmac_final(hmac_ctx, checksumbuf, sizeof(checksumbuf)) < 0)
	{
		pfree(result);
		pg_hmac_free(hmac_ctx);
		elog(ERROR, gettext_noop("credcheck could not initialize checksum"));
	}
	hex_encode((char *) checksumbuf, sizeof checksumbuf, result);
	result[PG_SHA256_DIGEST_STRING_LENGTH - 1] = '\0';

	pg_hmac_free(hmac_ctx);

	return result;
}
#else
char *
str_to_sha256(const char *password, const char *salt)
{
	int          password_len = strlen(password);
	uint8        checksumbuf[PG_SHA256_DIGEST_LENGTH];
	char        *result = palloc0(sizeof (char) * PG_SHA256_DIGEST_STRING_LENGTH);
	pg_sha256_ctx sha256_ctx;

	pg_sha256_init(&sha256_ctx);
	pg_sha256_update(&sha256_ctx, (uint8 *) password, password_len);
	pg_sha256_final(&sha256_ctx, checksumbuf);
	hex_encode((char *) checksumbuf, sizeof checksumbuf, result);
	result[PG_SHA256_DIGEST_STRING_LENGTH - 1] = '\0';

	return result;
}
#endif
#endif

/****
 * Password history feature
 ****/

/*
 * Estimate shared memory space needed for password history.
 */
static Size
pgph_memsize(void)
{
	Size            size;

	size = MAXALIGN(sizeof(pgphSharedState));
	size = add_size(size, hash_estimate_size(pgph_max, sizeof(pgphEntry)));

	return size;
}

/*
 * Estimate shared memory space needed for auth failure history.
 */
static Size
pgaf_memsize(void)
{
	Size            size;

	size = MAXALIGN(sizeof(pgafSharedState));
	size = add_size(size, hash_estimate_size(pgaf_max, sizeof(pgafEntry)));

	return size;
}


#if PG_VERSION_NUM >= 150000
static void
pghist_shmem_request(void)
{
	if (prev_shmem_request_hook)
		prev_shmem_request_hook();

	/*
	 * If you change code here, don't forget to also report the modifications in
	 * _PG_init() for pg14 and below.
	 */
	RequestAddinShmemSpace(pgph_memsize());
	RequestNamedLWLockTranche(PGPH_TRANCHE_NAME, 1);
	RequestAddinShmemSpace(pgaf_memsize());
	RequestNamedLWLockTranche(PGAF_TRANCHE_NAME, 1);
}
#endif


static void
pghist_shmem_startup(void)
{
	if (prev_shmem_startup_hook)
		prev_shmem_startup_hook();

	pgph_shmem_startup();

	pgaf_shmem_startup();
}

/*
 * shmem_startup hook: allocate or attach to shared memory,
 * then load any pre-existing password history from text file
 * or create it (even if empty) while the module is enabled.
 */
static void
pgph_shmem_startup(void)
{
	bool        found;
	HASHCTL     info;
	FILE       *file = NULL;
	uint32      header;
	int32       pgphver;
	int32       num;
	int32       i;

	/* reset in case this is a restart within the postmaster */
	pgph = NULL;
	pgph_hash = NULL;

	/*
	 * Create or attach to the shared memory state, including hash table
	 */
	LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);

	pgph = ShmemInitStruct("pg_password_history",
						   sizeof(pgphSharedState),
						   &found);

	if (!found)
	{
		/* First time through ... */
		pgph->lock = &(GetNamedLWLockTranche(PGPH_TRANCHE_NAME))->lock;
	}

	memset(&info, 0, sizeof(info));
	info.keysize = sizeof(pgphHashKey);
	info.entrysize = sizeof(pgphEntry);
	pgph_hash = ShmemInitHash("pg_password_history hash",
							  pgph_max, pgph_max,
							  &info,
							  HASH_ELEM | HASH_BLOBS);

	LWLockRelease(AddinShmemInitLock);

	/*
	 * Done if some other process already completed our initialization.
	 */
	if (found)
		return;

	/*
	 * Note: we don't bother with locks here, because there should be no other
	 * processes running when this code is reached.
	 */

        /*
	 * Assume backward compatibility with old location of the file,
         * move file to PGDATA
         */
	file = AllocateFile(PGPH_DUMP_FILE_OLD, PG_BINARY_R);
	if (file != NULL)
	{
		FreeFile(file);
		(void) durable_rename(PGPH_DUMP_FILE_OLD, PGPH_DUMP_FILE, LOG);
	}

	/*
	 * Attempt to load old history from the dump file.
	 */
	file = AllocateFile(PGPH_DUMP_FILE, PG_BINARY_R);
	if (file == NULL)
	{
		if (errno != ENOENT)
			goto read_error;
		/* No existing persisted stats file, so we're done */
		return;
	}

	if (fread(&header, sizeof(uint32), 1, file) != 1 ||
		fread(&pgphver, sizeof(uint32), 1, file) != 1 ||
		fread(&num, sizeof(int32), 1, file) != 1)
		goto read_error;

	if (header != PGPH_FILE_HEADER || pgphver != PGPH_VERSION)
		goto data_error;

	for (i = 0; i < num; i++)
	{
		pgphEntry   temp;
		pgphEntry  *entry;

		if (fread(&temp, sizeof(pgphEntry), 1, file) != 1)
		{
			ereport(LOG,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("ignoring invalid data in pg_password_history file \"%s\"",
							PGPH_DUMP_FILE)));
			goto fail;
		}

		/* make the hashtable entry (discards old entries if too many) */
		entry = pgph_entry_alloc(&temp.key, temp.password_date);
		if (!entry)
			goto fail;
	}
	FreeFile(file);
 
	pgph->num_entries = i + 1;

	return;

read_error:
	ereport(LOG,
			(errcode_for_file_access(),
			 errmsg("could not read pg_password_history file \"%s\": %m",
					PGPH_DUMP_FILE)));
	goto fail;
data_error:
	ereport(LOG,
			(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
			 errmsg("ignoring invalid data in file \"%s\"",
					PGPH_DUMP_FILE)));
fail:
	if (file)
		FreeFile(file);
}

static pgphEntry *
pgph_entry_alloc(pgphHashKey *key, TimestampTz password_date)
{
	pgphEntry  *entry;
	bool        found;

	if (hash_get_num_entries(pgph_hash) >= pgph_max)
	{
		ereport(LOG,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("can not allocate enough memory for new entry in password history cache."),
				 errhint("You shoul increase credcheck.history_max_size.")));
		return NULL;
	}

	/* Find or create an entry with desired hash code */
	entry = (pgphEntry *) hash_search(pgph_hash, key, HASH_ENTER, &found);

	/* New entry, set the timestamp */
	if (!found)
		entry->password_date = password_date;

	return entry;
}

static pgafEntry *
pgaf_entry_alloc(pgafHashKey *key, float failure_count)
{
	pgafEntry  *entry;
	bool        found;

	if (hash_get_num_entries(pgaf_hash) >= pgph_max)
	{
		ereport(LOG,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("can not allocate enough memory for new entry in auth failure cache."),
				 errhint("You shoul increase credcheck.history_max_size.")));
		return NULL;
	}

	/* Find or create an entry with desired hash code */
	entry = (pgafEntry *) hash_search(pgaf_hash, key, HASH_ENTER, &found);

	/* New entry */
	if (!found)
	{
		entry->failure_count = failure_count;
		if (failure_count >= fail_max)
			entry->banned_date = GetCurrentTimestamp();
	}

	return entry;
}


/*
 * Flush password history to disk.
 *
 * IMPORTANT: the caller is responsible to emit
 * an exclusive lock on pgph->lock otherwise the
 * file can be corrupted.
 */
static void
flush_password_history(void)
{
        FILE       *file;
        int32       num_entries;
        pgphEntry  *entry;
	HASH_SEQ_STATUS hash_seq;

        /* Safety check ... shouldn't get here unless shmem is set up. */
        if (!pgph || !pgph_hash)
                return;

	elog(DEBUG1, "flushing password history to file %s", PGPH_DUMP_FILE);

        file = AllocateFile(PGPH_DUMP_FILE ".tmp", PG_BINARY_W);
        if (file == NULL)
                goto error;

        if (fwrite(&PGPH_FILE_HEADER, sizeof(uint32), 1, file) != 1)
                goto error;
        if (fwrite(&PGPH_VERSION, sizeof(uint32), 1, file) != 1)
                goto error;
        num_entries = hash_get_num_entries(pgph_hash);
        if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
                goto error;

        hash_seq_init(&hash_seq, pgph_hash);
        while ((entry = hash_seq_search(&hash_seq)) != NULL)
        {
                if (fwrite(entry, sizeof(pgphEntry), 1, file) != 1)
                {
                        /* note: we assume hash_seq_term won't change errno */
                        hash_seq_term(&hash_seq);
                        goto error;
                }
        }
	/*
	 * Fill the file until a size divisible by page size 8192
	 * to fix a complain of pgBackRest backup: file size X is
	 * not divisible by page size 8192
	 */
	fseek(file, 0, SEEK_END);
	while ((ftell(file) % BLCKSZ) != 0)
		putc(0, file);

	/* close the file */
        if (FreeFile(file))
        {
                file = NULL;
                goto error;
        }

	elog(DEBUG1, "history hash table written to disk");

        /*
         * Rename file into place, so we atomically replace any old one.
         */
        (void) durable_rename(PGPH_DUMP_FILE ".tmp", PGPH_DUMP_FILE, LOG);

        return;

error:
        ereport(LOG,
                        (errcode_for_file_access(),
                         errmsg("could not write password history file \"%s\": %m",
                                        PGPH_DUMP_FILE ".tmp")));
        if (file)
                FreeFile(file);

        unlink(PGPH_DUMP_FILE ".tmp");
}

static void
pgaf_shmem_startup(void)
{
	bool        found;
	HASHCTL     info;

	/* reset in case this is a restart within the postmaster */
	pgaf = NULL;
	pgaf_hash = NULL;

	/*
	 * Create or attach to the shared memory state, including hash table
	 */
	LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);

	pgaf = ShmemInitStruct("pg_auth_failure_history",
						   sizeof(pgafSharedState),
						   &found);

	if (!found)
	{
		/* First time through ... */
		pgaf->lock = &(GetNamedLWLockTranche(PGAF_TRANCHE_NAME))->lock;
	}

	memset(&info, 0, sizeof(info));
	info.keysize = sizeof(pgafHashKey);
	info.entrysize = sizeof(pgafEntry);
	pgaf_hash = ShmemInitHash("pg_auth_failure_history hash",
							  pgaf_max, pgaf_max,
							  &info,
							  HASH_ELEM | HASH_BLOBS);

	LWLockRelease(AddinShmemInitLock);
}

PG_FUNCTION_INFO_V1(pg_password_history_reset);

/*
 * Reset password history.
 */
Datum
pg_password_history_reset(PG_FUNCTION_ARGS)
{
	char       *username;
	int         num_removed = 0;
	HASH_SEQ_STATUS hash_seq;
        pgphEntry  *entry;

        /* Safety check... */
        if (!pgph || !pgph_hash)
                return 0;

        /* Only superusers can reset the history */
	if (!superuser())
		ereport(ERROR, (errmsg("only superuser can reset password history")));

	/* Get the username to filter the entries to remove if one specified */
	if (PG_NARGS() > 0)
		username = PG_GETARG_CSTRING(0);
	else
		username = NULL;

	/* Lookup the hash table entry with exclusive lock. */
	LWLockAcquire(pgph->lock, LW_EXCLUSIVE);

        hash_seq_init(&hash_seq, pgph_hash);

	/* Sequential scan of the hash table to find the entries to remove */
        while ((entry = hash_seq_search(&hash_seq)) != NULL)
        {
		if (username == NULL || strcmp(entry->key.rolename, username) == 0)
		{
			hash_search(pgph_hash, &entry->key, HASH_REMOVE, NULL);
			num_removed++;
		}
	}

	/* Flush the new entry to disk */
	if (num_removed > 0)
		flush_password_history();

	LWLockRelease(pgph->lock);

        PG_RETURN_INT32(num_removed);
}

PG_FUNCTION_INFO_V1(pg_password_history);

/*
 * Show content of the password history.
 */
Datum
pg_password_history(PG_FUNCTION_ARGS)
{
	pg_password_history_internal(fcinfo);

	return (Datum) 0;
}

/* Common code for all versions of pg_password_history() */
static void
pg_password_history_internal(FunctionCallInfo fcinfo)
{
	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
	TupleDesc       tupdesc;
	Tuplestorestate *tupstore;
	MemoryContext per_query_ctx;
	MemoryContext oldcontext;
	HASH_SEQ_STATUS hash_seq;
	pgphEntry  *entry;

	/* Safety check... */
	if (!pgph || !pgph_hash)
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("credcheck must be loaded via shared_preload_libraries to use password history")));

	/* check to see if caller supports us returning a tuplestore */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context that cannot accept a set")));
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("materialize mode required, but it is not allowed in this context")));

	/* Switch into long-lived context to construct returned data structures */
	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	/* Build a tuple descriptor for our result type */
	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
		elog(ERROR, "return type must be a row type");

	tupstore = tuplestore_begin_heap(true, false, work_mem);
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setResult = tupstore;
	rsinfo->setDesc = tupdesc;

	MemoryContextSwitchTo(oldcontext);

	/*
	 * Get shared lock, iterate over the hashtable entries.
	 *
	 * With a large hash table, we might be holding the lock rather longer
	 * than one could wish.  However, this only blocks creation of new hash
	 * table entries, and the larger the hash table the less likely that is to
	 * be needed.
	 */
	LWLockAcquire(pgph->lock, LW_SHARED);

	hash_seq_init(&hash_seq, pgph_hash);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		Datum           values[PG_PASSWORD_HISTORY_COLS];
		bool            nulls[PG_PASSWORD_HISTORY_COLS];
		int                     i = 0;

		memset(values, 0, sizeof(values));
		memset(nulls, 0, sizeof(nulls));

		values[i++] = CStringGetDatum(entry->key.rolename);
		values[i++] = TimestampTzGetDatum(entry->password_date);
		values[i++] = CStringGetTextDatum(entry->key.password_hash);

		tuplestore_putvalues(tupstore, tupdesc, values, nulls);
	}

	/* clean up and return the tuplestore */
	LWLockRelease(pgph->lock);
}

PG_FUNCTION_INFO_V1(pg_password_history_timestamp);

/*
 * Change the password_date of all entries in password history
 * for a specified user. Proposed for testing purpose only.
 */
Datum
pg_password_history_timestamp(PG_FUNCTION_ARGS)
{
	char       *username = PG_GETARG_CSTRING(0);
	TimestampTz new_timestamp = PG_GETARG_TIMESTAMPTZ(1);
        pgphEntry  *entry;
	int         num_changed = 0;
	HASH_SEQ_STATUS hash_seq;

        /* Safety check... */
        if (!pgph || !pgph_hash)
                return 0;

        /* Only superusers can reset the history */
	if (!superuser())
		ereport(ERROR, (errmsg("only superuser can change timestamp in password history")));

	/* Lookup the hash table entry with exclusive lock. */
	LWLockAcquire(pgph->lock, LW_EXCLUSIVE);

        hash_seq_init(&hash_seq, pgph_hash);
        while ((entry = hash_seq_search(&hash_seq)) != NULL)
        {
		if (strcmp(entry->key.rolename, username) == 0)
                {
			entry->password_date = new_timestamp;
			num_changed++;
                }
        }

	/* Flush the new entry to disk */
	if (num_changed > 0)
		flush_password_history();

	LWLockRelease(pgph->lock);

        PG_RETURN_INT32(num_changed);
}

static void
fix_log(ErrorData *edata)
{
	if (edata->elevel != ERROR)
	{
		/* Continue chain to previous hook */
		if (prev_log_hook)
			(*prev_log_hook) (edata);
		return;
	}

        /*
	 * Error should not expose the password in the log.
	 */
	if (statement_has_password && no_password_logging)
		edata->hide_stmt = true;

	statement_has_password = false;

	/* Continue chain to previous hook */
	if (prev_log_hook)
		(*prev_log_hook) (edata);
}

static void
credcheck_max_auth_failure(Port *port, int status)
{

	/* Inject a short delay if authentication failed. */
	if (status != STATUS_OK)
		pg_usleep(1000L * auth_delay_milliseconds);

	/* get out if the user is whitelisted for auth failure */
	if (is_in_whitelist(port->user_name, max_auth_whitelist))
	{
		if (prev_ClientAuthentication)
			prev_ClientAuthentication(port, status);
		return;
	}

	/* check for max auth failure */
	if (fail_max > 0 && status != STATUS_EOF)
	{
		Oid userOid =  get_role_oid(port->user_name, true);

		if (userOid != InvalidOid)
		{
			float fail_num = get_auth_failure(port->user_name, userOid, status);

			/* register the auth failure if we not reach allowed max failure */
			if (status == STATUS_ERROR && fail_num <= fail_max)
				fail_num = save_auth_failure(port, userOid);

			/* reject, this account has been banned */
			if (fail_num >= fail_max)
			{
				/*
				 * if superuser have been banned, restore the access if requested
				 * through credcheck.reset_superuser and a configuration reload
				 */
				if (reset_superuser && userOid == 10)
					remove_auth_failure(port->user_name, userOid);
				else
					ereport(FATAL, (errmsg("rejecting connection, user '%s' has been banned", port->user_name)));
			}

			/* connection is ok and we have not reach the failure limit, let's reset the counter */
			if (status == STATUS_OK  && fail_num < fail_max)
				remove_auth_failure(port->user_name, userOid);
		}
	}

	if (prev_ClientAuthentication)
		prev_ClientAuthentication(port, status);

}

static float
get_auth_failure(const char *username, Oid userid, int status)
{
	pgafHashKey key;
	pgafEntry  *entry;
	float fail_cnt = 0;

	Assert(username != NULL);

	if (fail_max == 0)
		return 0;

	/* Safety check... */
	if (!pgaf || !pgaf_hash)
		return 0;

	/* Set up key for hashtable search */
        key.roleid = userid ;

	/* Lookup the hash table entry with exclusive lock. */
	LWLockAcquire(pgaf->lock, LW_EXCLUSIVE);

	/* Create new entry, if not present */
	entry = (pgafEntry *) hash_search(pgaf_hash, &key, HASH_FIND, NULL);
	if (entry)
		fail_cnt = entry->failure_count;

	elog(DEBUG1, "Auth failure count for user %s is %f, fired by status: %d", username, fail_cnt, status);

	LWLockRelease(pgaf->lock);

	return fail_cnt;
}

static float
save_auth_failure(Port *port, Oid userid)
{
	pgafHashKey key;
	pgafEntry  *entry;
	float fail_cnt = 1;

	/*
	if (port->ssl_in_use)
		fail_cnt = 0.5;
	*/

	Assert(port->user_name != NULL);

	if (fail_max == 0)
		return 0;

	/* Safety check... */
	if (!pgaf || !pgaf_hash)
		return 0;

	/* Set up key for hashtable search */
        key.roleid = userid ;

	/* Lookup the hash table entry with exclusive lock. */
	LWLockAcquire(pgaf->lock, LW_EXCLUSIVE);

	/* Create new entry, if not present */
	entry = (pgafEntry *) hash_search(pgaf_hash, &key, HASH_FIND, NULL);
	if (entry)
	{
		/*
		if (port->ssl_in_use)
			fail_cnt = entry->failure_count + 0.5;
		else
		*/
			fail_cnt = entry->failure_count + 1;

		elog(DEBUG1, "Remove entry in auth failure hash table for user %s", port->user_name);
		hash_search(pgaf_hash, &entry->key, HASH_REMOVE, NULL);
	}
	elog(DEBUG1, "Add new entry in auth failure hash table for user %s (%d, %f)", port->user_name, userid, fail_cnt);

	/* OK to create a new hashtable entry */
	entry = pgaf_entry_alloc(&key, fail_cnt);

	LWLockRelease(pgaf->lock);

	return fail_cnt;
}

static void
remove_auth_failure(const char *username, Oid userid)
{
	pgafHashKey key;

	Assert(username != NULL);

	if (fail_max == 0)
		return;

	/* Safety check... */
	if (!pgaf || !pgaf_hash)
		return;

	/* Set up key for hashtable search */
        key.roleid = userid;

	/* Lookup the hash table entry with exclusive lock. */
	LWLockAcquire(pgaf->lock, LW_EXCLUSIVE);

	elog(DEBUG1, "Remove entry in auth failure hash table for user %s", username);
	hash_search(pgaf_hash, &key, HASH_REMOVE, NULL);

	LWLockRelease(pgaf->lock);
}

PG_FUNCTION_INFO_V1(pg_banned_role_reset);

/*
 * Reset banned role cache.
 */
Datum
pg_banned_role_reset(PG_FUNCTION_ARGS)
{
	char       *username;
	int         num_removed = 0;
	HASH_SEQ_STATUS hash_seq;
        pgafEntry  *entry;

        /* Safety check... */
        if (!pgaf || !pgaf_hash)
                return 0;

        /* Only superusers can reset the history */
	if (!superuser())
		ereport(ERROR, (errmsg("only superuser can reset banned roles cache")));

	/* Get the username to filter the entries to remove if one specified */
	if (PG_NARGS() > 0)
		username = PG_GETARG_CSTRING(0);
	else
		username = NULL;

	/* Lookup the hash table entry with exclusive lock. */
	LWLockAcquire(pgaf->lock, LW_EXCLUSIVE);

        hash_seq_init(&hash_seq, pgaf_hash);

	/* Sequential scan of the hash table to find the entries to remove */
        while ((entry = hash_seq_search(&hash_seq)) != NULL)
        {
		if (username == NULL || (entry->key.roleid == get_role_oid(username, true)))
		{
			hash_search(pgaf_hash, &entry->key, HASH_REMOVE, NULL);
			num_removed++;
		}
	}

	LWLockRelease(pgaf->lock);

        PG_RETURN_INT32(num_removed);
}

PG_FUNCTION_INFO_V1(pg_banned_role);

/*
 * Show list of the banned role
 */
Datum
pg_banned_role(PG_FUNCTION_ARGS)
{
	pg_banned_role_internal(fcinfo);

	return (Datum) 0;
}

/* Common code for all versions of pg_banned_role() */
static void
pg_banned_role_internal(FunctionCallInfo fcinfo)
{
	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
	TupleDesc       tupdesc;
	Tuplestorestate *tupstore;
	MemoryContext per_query_ctx;
	MemoryContext oldcontext;
	HASH_SEQ_STATUS hash_seq;
	pgafEntry  *entry;

	/* Safety check... */
	if (!pgaf || !pgaf_hash)
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("credcheck must be loaded via shared_preload_libraries to use auth failure feature")));

	/* check to see if caller supports us returning a tuplestore */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context that cannot accept a set")));
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("materialize mode required, but it is not allowed in this context")));

	/* Switch into long-lived context to construct returned data structures */
	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	/* Build a tuple descriptor for our result type */
	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
		elog(ERROR, "return type must be a row type");

	tupstore = tuplestore_begin_heap(true, false, work_mem);
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setResult = tupstore;
	rsinfo->setDesc = tupdesc;

	MemoryContextSwitchTo(oldcontext);

	/*
	 * Get shared lock, iterate over the hashtable entries.
	 *
	 * With a large hash table, we might be holding the lock rather longer
	 * than one could wish.  However, this only blocks creation of new hash
	 * table entries, and the larger the hash table the less likely that is to
	 * be needed.
	 */
	LWLockAcquire(pgaf->lock, LW_SHARED);

	hash_seq_init(&hash_seq, pgaf_hash);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		Datum           values[PG_BANNED_ROLE_COLS];
		bool            nulls[PG_BANNED_ROLE_COLS];
		int             i = 0;

		memset(values, 0, sizeof(values));
		memset(nulls, 0, sizeof(nulls));

		values[i++] = ObjectIdGetDatum(entry->key.roleid);
		values[i++] = Int8GetDatum(entry->failure_count);
		if (entry->banned_date)
			values[i++] = TimestampTzGetDatum(entry->banned_date);
		else
			nulls[i++] = true;

		tuplestore_putvalues(tupstore, tupdesc, values, nulls);
	}

	/* clean up and return the tuplestore */
	LWLockRelease(pgaf->lock);
}

static void
cc_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
        elog(DEBUG1, "cc_ExecutorStart()");

	if (NOT_IN_PARALLEL_WORKER)
	{
		/*
		 * When first login we don't allow anything else than password change.
		 * This rule is also checked in the ProcessUtility hook because we need
		 * to allow the ALTER ROLE command to change the password. We must allow
		 * SELECT CURRENT_USER which is sent by the \passwd command before
		 * password change.
		 */
		if (debug_query_string != NULL && strcmp(debug_query_string, "SELECT CURRENT_USER") != 0)
		{
			if (!is_in_whitelist(MyProcPort->user_name, username_whitelist))
			{
				if (queryDesc->operation != CMD_UTILITY && force_change_password)
						ereport(ERROR,
							(errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
								errmsg(gettext_noop("you must change your password first."))));
			}
		}
	}

        /* Continue the normal behavior */
        if (prev_ExecutorStart)
                prev_ExecutorStart(queryDesc, eflags);
        else
                standard_ExecutorStart(queryDesc, eflags);

	elog(DEBUG1, "End of cc_ExecutorStart()");
}

static void
set_force_change_password(Oid databaseid, Oid roleid, char *valuestr)
{
	//HeapTuple       tuple;
	Relation	rel;
	ScanKeyData scankey[2];
	SysScanDesc scan;

	/* Get the old tuple, if any. */

	rel = table_open(DbRoleSettingRelationId, RowExclusiveLock);
	ScanKeyInit(&scankey[0],
				Anum_pg_db_role_setting_setdatabase,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(databaseid));
	ScanKeyInit(&scankey[1],
				Anum_pg_db_role_setting_setrole,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(roleid));
	scan = systable_beginscan(rel, DbRoleSettingDatidRolidIndexId, true,
							  NULL, 2, scankey);
	//tuple = systable_getnext(scan);

	if (valuestr)
	{
		/* non-null valuestr means it's not RESET, so insert a new tuple */
		HeapTuple	newtuple;
		Datum		values[Natts_pg_db_role_setting];
		bool		nulls[Natts_pg_db_role_setting];
		ArrayType  *a;

		memset(nulls, false, sizeof(nulls));

		a = GUCArrayAdd(NULL, "credcheck_internal.force_change_password", valuestr);

		values[Anum_pg_db_role_setting_setdatabase - 1] = ObjectIdGetDatum(databaseid);
		values[Anum_pg_db_role_setting_setrole - 1] = ObjectIdGetDatum(roleid);
		values[Anum_pg_db_role_setting_setconfig - 1] = PointerGetDatum(a);
		newtuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);

		CatalogTupleInsert(rel, newtuple);
	}
	systable_endscan(scan);

	/* Close pg_db_role_setting, but keep lock till commit */
	table_close(rel, NoLock);
}

static void
reset_force_change_password(Oid databaseid, Oid roleid)
{
	bool need_priv_escalation = !superuser(); /* we might be a SU */
	Oid     save_userid;
	int     save_sec_context;
	HeapTuple	tuple;
	Relation	rel;
	ScanKeyData scankey[2];
	SysScanDesc scan;

	/* The setting reseet must be done as SU */
	if (need_priv_escalation)
	{
		/* Get current user's Oid and security context */
		GetUserIdAndSecContext(&save_userid, &save_sec_context);
		/* Become superuser */
		SetUserIdAndSecContext(BOOTSTRAP_SUPERUSERID, save_sec_context
							| SECURITY_LOCAL_USERID_CHANGE
							| SECURITY_RESTRICTED_OPERATION);
	}

	/* Get the old tuple, if any. */
	rel = table_open(DbRoleSettingRelationId, RowExclusiveLock);
	ScanKeyInit(&scankey[0],
				Anum_pg_db_role_setting_setdatabase,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(databaseid));
	ScanKeyInit(&scankey[1],
				Anum_pg_db_role_setting_setrole,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(roleid));
	scan = systable_beginscan(rel, DbRoleSettingDatidRolidIndexId, true,
							  NULL, 2, scankey);
	tuple = systable_getnext(scan);

	if (HeapTupleIsValid(tuple))
	{
		Datum		repl_val[Natts_pg_db_role_setting];
		bool		repl_null[Natts_pg_db_role_setting];
		bool		repl_repl[Natts_pg_db_role_setting];
		HeapTuple	newtuple;
		Datum		datum;
		bool		isnull;
		ArrayType  *a;

		memset(repl_repl, false, sizeof(repl_repl));
		repl_repl[Anum_pg_db_role_setting_setconfig - 1] = true;
		repl_null[Anum_pg_db_role_setting_setconfig - 1] = false;

		/* Extract old value of setconfig */
		datum = heap_getattr(tuple, Anum_pg_db_role_setting_setconfig,
							 RelationGetDescr(rel), &isnull);
		a = isnull ? NULL : DatumGetArrayTypeP(datum);

		a = GUCArrayDelete(a, "credcheck_internal.force_change_password");

		if (a)
		{
			repl_val[Anum_pg_db_role_setting_setconfig - 1] =
				PointerGetDatum(a);

			newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
										 repl_val, repl_null, repl_repl);
			CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
		}
		else
			CatalogTupleDelete(rel, &tuple->t_self);
	}

	systable_endscan(scan);

	/* Close pg_db_role_setting, but keep lock till commit */
	table_close(rel, NoLock);

	/* Restore user's privileges */
	if (need_priv_escalation)
		SetUserIdAndSecContext(save_userid, save_sec_context);

}