aboutsummaryrefslogtreecommitdiffstats
path: root/source4/dsdb/samdb/ldb_modules/password_hash.c
blob: bd29377b1b684c418442ed150954710764f3eddd (plain)
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
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
/* 
   ldb database module

   Copyright (C) Simo Sorce  2004-2008
   Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2006
   Copyright (C) Andrew Tridgell 2004
   Copyright (C) Stefan Metzmacher 2007-2010
   Copyright (C) Matthias Dieter Wallnöfer 2009-2010

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 *  Name: ldb
 *
 *  Component: ldb password_hash module
 *
 *  Description: correctly handle AD password changes fields
 *
 *  Author: Andrew Bartlett
 *  Author: Stefan Metzmacher
 */

#include "includes.h"
#include "ldb_module.h"
#include "libcli/auth/libcli_auth.h"
#include "libcli/security/dom_sid.h"
#include "system/kerberos.h"
#include "auth/kerberos/kerberos.h"
#include "dsdb/samdb/samdb.h"
#include "dsdb/samdb/ldb_modules/util.h"
#include "dsdb/samdb/ldb_modules/password_modules.h"
#include "librpc/gen_ndr/ndr_drsblobs.h"
#include "../lib/crypto/crypto.h"
#include "param/param.h"
#include "lib/krb5_wrap/krb5_samba.h"

#ifdef ENABLE_GPGME
#undef class
#include <gpgme.h>
#endif

/* If we have decided there is a reason to work on this request, then
 * setup all the password hash types correctly.
 *
 * If we haven't the hashes yet but the password given as plain-text (attributes
 * 'unicodePwd', 'userPassword' and 'clearTextPassword') we have to check for
 * the constraints. Once this is done, we calculate the password hashes.
 *
 * Notice: unlike the real AD which only supports the UTF16 special based
 * 'unicodePwd' and the UTF8 based 'userPassword' plaintext attribute we
 * understand also a UTF16 based 'clearTextPassword' one.
 * The latter is also accessible through LDAP so it can also be set by external
 * tools and scripts. But be aware that this isn't portable on non SAMBA 4 ADs!
 *
 * Also when the module receives only the password hashes (possible through
 * specifying an internal LDB control - for security reasons) some checks are
 * performed depending on the operation mode (see below) (e.g. if the password
 * has been in use before if the password memory policy was activated).
 *
 * Attention: There is a difference between "modify" and "reset" operations
 * (see MS-ADTS 3.1.1.3.1.5). If the client sends a "add" and "remove"
 * operation for a password attribute we thread this as a "modify"; if it sends
 * only a "replace" one we have an (administrative) reset.
 *
 * Finally, if the administrator has requested that a password history
 * be maintained, then this should also be written out.
 *
 */

/* TODO: [consider always MS-ADTS 3.1.1.3.1.5]
 * - Check for right connection encryption
 */

/* Notice: Definition of "dsdb_control_password_change_status" moved into
 * "samdb.h" */

struct ph_context {
	struct ldb_module *module;
	struct ldb_request *req;

	struct ldb_request *dom_req;
	struct ldb_reply *dom_res;

	struct ldb_reply *search_res;

	struct ldb_message *update_msg;

	struct dsdb_control_password_change_status *status;
	struct dsdb_control_password_change *change;

	const char **gpg_key_ids;

	bool pwd_reset;
	bool change_status;
	bool hash_values;
	bool userPassword;
	bool update_password;
	bool update_lastset;
	bool pwd_last_set_bypass;
	bool pwd_last_set_default;
	bool smartcard_reset;
};


struct setup_password_fields_io {
	struct ph_context *ac;

	struct smb_krb5_context *smb_krb5_context;

	/* infos about the user account */
	struct {
		uint32_t userAccountControl;
		NTTIME pwdLastSet;
		const char *sAMAccountName;
		const char *user_principal_name;
		bool is_computer;
		bool is_krbtgt;
		uint32_t restrictions;
	} u;

	/* new credentials and old given credentials */
	struct setup_password_fields_given {
		const struct ldb_val *cleartext_utf8;
		const struct ldb_val *cleartext_utf16;
		struct samr_Password *nt_hash;
		struct samr_Password *lm_hash;
	} n, og;

	/* old credentials */
	struct {
		struct samr_Password *nt_hash;
		struct samr_Password *lm_hash;
		uint32_t nt_history_len;
		struct samr_Password *nt_history;
		uint32_t lm_history_len;
		struct samr_Password *lm_history;
		const struct ldb_val *supplemental;
		struct supplementalCredentialsBlob scb;
	} o;

	/* generated credentials */
	struct {
		struct samr_Password *nt_hash;
		struct samr_Password *lm_hash;
		uint32_t nt_history_len;
		struct samr_Password *nt_history;
		uint32_t lm_history_len;
		struct samr_Password *lm_history;
		const char *salt;
		DATA_BLOB aes_256;
		DATA_BLOB aes_128;
		DATA_BLOB des_md5;
		DATA_BLOB des_crc;
		struct ldb_val supplemental;
		NTTIME last_set;
	} g;
};

static int msg_find_old_and_new_pwd_val(const struct ldb_message *msg,
					const char *name,
					enum ldb_request_type operation,
					const struct ldb_val **new_val,
					const struct ldb_val **old_val);

static int password_hash_bypass(struct ldb_module *module, struct ldb_request *request)
{
	struct ldb_context *ldb = ldb_module_get_ctx(module);
	const struct ldb_message *msg;
	struct ldb_message_element *nte;
	struct ldb_message_element *lme;
	struct ldb_message_element *nthe;
	struct ldb_message_element *lmhe;
	struct ldb_message_element *sce;

	switch (request->operation) {
	case LDB_ADD:
		msg = request->op.add.message;
		break;
	case LDB_MODIFY:
		msg = request->op.mod.message;
		break;
	default:
		return ldb_next_request(module, request);
	}

	/* nobody must touch password histories and 'supplementalCredentials' */
	nte = dsdb_get_single_valued_attr(msg, "unicodePwd",
					  request->operation);
	lme = dsdb_get_single_valued_attr(msg, "dBCSPwd",
					  request->operation);
	nthe = dsdb_get_single_valued_attr(msg, "ntPwdHistory",
					   request->operation);
	lmhe = dsdb_get_single_valued_attr(msg, "lmPwdHistory",
					   request->operation);
	sce = dsdb_get_single_valued_attr(msg, "supplementalCredentials",
					  request->operation);

#define CHECK_HASH_ELEMENT(e, min, max) do {\
	if (e && e->num_values) { \
		unsigned int _count; \
		if (e->num_values != 1) { \
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, \
					 "num_values != 1"); \
		} \
		if ((e->values[0].length % 16) != 0) { \
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, \
					 "length % 16 != 0"); \
		} \
		_count = e->values[0].length / 16; \
		if (_count < min) { \
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, \
					 "count < min"); \
		} \
		if (_count > max) { \
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION, \
					 "count > max"); \
		} \
	} \
} while (0)

	CHECK_HASH_ELEMENT(nte, 1, 1);
	CHECK_HASH_ELEMENT(lme, 1, 1);
	CHECK_HASH_ELEMENT(nthe, 1, INT32_MAX);
	CHECK_HASH_ELEMENT(lmhe, 1, INT32_MAX);

	if (sce && sce->num_values) {
		enum ndr_err_code ndr_err;
		struct supplementalCredentialsBlob *scb;
		struct supplementalCredentialsPackage *scpp = NULL;
		struct supplementalCredentialsPackage *scpk = NULL;
		struct supplementalCredentialsPackage *scpkn = NULL;
		struct supplementalCredentialsPackage *scpct = NULL;
		DATA_BLOB scpbp = data_blob_null;
		DATA_BLOB scpbk = data_blob_null;
		DATA_BLOB scpbkn = data_blob_null;
		DATA_BLOB scpbct = data_blob_null;
		DATA_BLOB blob;
		uint32_t i;

		if (sce->num_values != 1) {
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
					 "num_values != 1");
		}

		scb = talloc_zero(request, struct supplementalCredentialsBlob);
		if (!scb) {
			return ldb_module_oom(module);
		}

		ndr_err = ndr_pull_struct_blob_all(&sce->values[0], scb, scb,
				(ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
		if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
					 "ndr_pull_struct_blob_all");
		}

		if (scb->sub.num_packages < 2) {
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
					 "num_packages < 2");
		}

		for (i=0; i < scb->sub.num_packages; i++) {
			DATA_BLOB subblob;

			subblob = strhex_to_data_blob(scb, scb->sub.packages[i].data);
			if (subblob.data == NULL) {
				return ldb_module_oom(module);
			}

			if (strcmp(scb->sub.packages[i].name, "Packages") == 0) {
				if (scpp) {
					return ldb_error(ldb,
							 LDB_ERR_CONSTRAINT_VIOLATION,
							 "Packages twice");
				}
				scpp = &scb->sub.packages[i];
				scpbp = subblob;
				continue;
			}
			if (strcmp(scb->sub.packages[i].name, "Primary:Kerberos") == 0) {
				if (scpk) {
					return ldb_error(ldb,
							 LDB_ERR_CONSTRAINT_VIOLATION,
							 "Primary:Kerberos twice");
				}
				scpk = &scb->sub.packages[i];
				scpbk = subblob;
				continue;
			}
			if (strcmp(scb->sub.packages[i].name, "Primary:Kerberos-Newer-Keys") == 0) {
				if (scpkn) {
					return ldb_error(ldb,
							 LDB_ERR_CONSTRAINT_VIOLATION,
							 "Primary:Kerberos-Newer-Keys twice");
				}
				scpkn = &scb->sub.packages[i];
				scpbkn = subblob;
				continue;
			}
			if (strcmp(scb->sub.packages[i].name, "Primary:CLEARTEXT") == 0) {
				if (scpct) {
					return ldb_error(ldb,
							 LDB_ERR_CONSTRAINT_VIOLATION,
							 "Primary:CLEARTEXT twice");
				}
				scpct = &scb->sub.packages[i];
				scpbct = subblob;
				continue;
			}

			data_blob_free(&subblob);
		}

		if (scpp == NULL) {
			return ldb_error(ldb,
					 LDB_ERR_CONSTRAINT_VIOLATION,
					 "Primary:Packages missing");
		}

		if (scpk == NULL) {
			/*
			 * If Primary:Kerberos is missing w2k8r2 reboots
			 * when a password is changed.
			 */
			return ldb_error(ldb,
					 LDB_ERR_CONSTRAINT_VIOLATION,
					 "Primary:Kerberos missing");
		}

		if (scpp) {
			struct package_PackagesBlob *p;
			uint32_t n;

			p = talloc_zero(scb, struct package_PackagesBlob);
			if (p == NULL) {
				return ldb_module_oom(module);
			}

			ndr_err = ndr_pull_struct_blob(&scpbp, p, p,
					(ndr_pull_flags_fn_t)ndr_pull_package_PackagesBlob);
			if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "ndr_pull_struct_blob Packages");
			}

			if (p->names == NULL) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "Packages names == NULL");
			}

			for (n = 0; p->names[n]; n++) {
				/* noop */
			}

			if (scb->sub.num_packages != (n + 1)) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "Packages num_packages != num_names + 1");
			}

			talloc_free(p);
		}

		if (scpk) {
			struct package_PrimaryKerberosBlob *k;

			k = talloc_zero(scb, struct package_PrimaryKerberosBlob);
			if (k == NULL) {
				return ldb_module_oom(module);
			}

			ndr_err = ndr_pull_struct_blob(&scpbk, k, k,
					(ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
			if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "ndr_pull_struct_blob PrimaryKerberos");
			}

			if (k->version != 3) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos version != 3");
			}

			if (k->ctr.ctr3.salt.string == NULL) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos salt == NULL");
			}

			if (strlen(k->ctr.ctr3.salt.string) == 0) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos strlen(salt) == 0");
			}

			if (k->ctr.ctr3.num_keys != 2) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos num_keys != 2");
			}

			if (k->ctr.ctr3.num_old_keys > k->ctr.ctr3.num_keys) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos num_old_keys > num_keys");
			}

			if (k->ctr.ctr3.keys[0].keytype != ENCTYPE_DES_CBC_MD5) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos key[0] != DES_CBC_MD5");
			}
			if (k->ctr.ctr3.keys[1].keytype != ENCTYPE_DES_CBC_CRC) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos key[1] != DES_CBC_CRC");
			}

			if (k->ctr.ctr3.keys[0].value_len != 8) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos key[0] value_len != 8");
			}
			if (k->ctr.ctr3.keys[1].value_len != 8) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos key[1] value_len != 8");
			}

			for (i = 0; i < k->ctr.ctr3.num_old_keys; i++) {
				if (k->ctr.ctr3.old_keys[i].keytype ==
				    k->ctr.ctr3.keys[i].keytype &&
				    k->ctr.ctr3.old_keys[i].value_len ==
				    k->ctr.ctr3.keys[i].value_len) {
					continue;
				}

				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryKerberos old_keys type/value_len doesn't match");
			}

			talloc_free(k);
		}

		if (scpkn) {
			struct package_PrimaryKerberosBlob *k;

			k = talloc_zero(scb, struct package_PrimaryKerberosBlob);
			if (k == NULL) {
				return ldb_module_oom(module);
			}

			ndr_err = ndr_pull_struct_blob(&scpbkn, k, k,
					(ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
			if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "ndr_pull_struct_blob PrimaryKerberosNeverKeys");
			}

			if (k->version != 4) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNerverKeys version != 4");
			}

			if (k->ctr.ctr4.salt.string == NULL) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys salt == NULL");
			}

			if (strlen(k->ctr.ctr4.salt.string) == 0) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys strlen(salt) == 0");
			}

			if (k->ctr.ctr4.num_keys != 4) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys num_keys != 2");
			}

			if (k->ctr.ctr4.num_old_keys > k->ctr.ctr4.num_keys) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys num_old_keys > num_keys");
			}

			if (k->ctr.ctr4.num_older_keys > k->ctr.ctr4.num_old_keys) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys num_older_keys > num_old_keys");
			}

			if (k->ctr.ctr4.keys[0].keytype != ENCTYPE_AES256_CTS_HMAC_SHA1_96) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys key[0] != AES256");
			}
			if (k->ctr.ctr4.keys[1].keytype != ENCTYPE_AES128_CTS_HMAC_SHA1_96) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys key[1] != AES128");
			}
			if (k->ctr.ctr4.keys[2].keytype != ENCTYPE_DES_CBC_MD5) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys key[2] != DES_CBC_MD5");
			}
			if (k->ctr.ctr4.keys[3].keytype != ENCTYPE_DES_CBC_CRC) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys key[3] != DES_CBC_CRC");
			}

			if (k->ctr.ctr4.keys[0].value_len != 32) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys key[0] value_len != 32");
			}
			if (k->ctr.ctr4.keys[1].value_len != 16) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys key[1] value_len != 16");
			}
			if (k->ctr.ctr4.keys[2].value_len != 8) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys key[2] value_len != 8");
			}
			if (k->ctr.ctr4.keys[3].value_len != 8) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "KerberosNewerKeys key[3] value_len != 8");
			}

			/*
			 * TODO:
			 * Maybe we can check old and older keys here.
			 * But we need to do some tests, if the old keys
			 * can be taken from the PrimaryKerberos blob
			 * (with only des keys), when the domain was upgraded
			 * from w2k3 to w2k8.
			 */

			talloc_free(k);
		}

		if (scpct) {
			struct package_PrimaryCLEARTEXTBlob *ct;

			ct = talloc_zero(scb, struct package_PrimaryCLEARTEXTBlob);
			if (ct == NULL) {
				return ldb_module_oom(module);
			}

			ndr_err = ndr_pull_struct_blob(&scpbct, ct, ct,
					(ndr_pull_flags_fn_t)ndr_pull_package_PrimaryCLEARTEXTBlob);
			if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "ndr_pull_struct_blob PrimaryCLEARTEXT");
			}

			if ((ct->cleartext.length % 2) != 0) {
				return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
						 "PrimaryCLEARTEXT length % 2 != 0");
			}

			talloc_free(ct);
		}

		ndr_err = ndr_push_struct_blob(&blob, scb, scb,
				(ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
		if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
					 "ndr_pull_struct_blob_all");
		}

		if (sce->values[0].length != blob.length) {
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
					 "supplementalCredentialsBlob length differ");
		}

		if (memcmp(sce->values[0].data, blob.data, blob.length) != 0) {
			return ldb_error(ldb, LDB_ERR_CONSTRAINT_VIOLATION,
					 "supplementalCredentialsBlob memcmp differ");
		}

		talloc_free(scb);
	}

	ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_bypass - validated\n");
	return ldb_next_request(module, request);
}

/* Get the NT hash, and fill it in as an entry in the password history, 
   and specify it into io->g.nt_hash */

static int setup_nt_fields(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb;
	uint32_t i;

	io->g.nt_hash = io->n.nt_hash;
	ldb = ldb_module_get_ctx(io->ac->module);

	if (io->ac->status->domain_data.pwdHistoryLength == 0) {
		return LDB_SUCCESS;
	}

	/* We might not have an old NT password */
	io->g.nt_history = talloc_array(io->ac,
					struct samr_Password,
					io->ac->status->domain_data.pwdHistoryLength);
	if (!io->g.nt_history) {
		return ldb_oom(ldb);
	}

	for (i = 0; i < MIN(io->ac->status->domain_data.pwdHistoryLength-1,
			    io->o.nt_history_len); i++) {
		io->g.nt_history[i+1] = io->o.nt_history[i];
	}
	io->g.nt_history_len = i + 1;

	if (io->g.nt_hash) {
		io->g.nt_history[0] = *io->g.nt_hash;
	} else {
		/* 
		 * TODO: is this correct?
		 * the simular behavior is correct for the lm history case
		 */
		E_md4hash("", io->g.nt_history[0].hash);
	}

	return LDB_SUCCESS;
}

/* Get the LANMAN hash, and fill it in as an entry in the password history, 
   and specify it into io->g.lm_hash */

static int setup_lm_fields(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb;
	uint32_t i;

	io->g.lm_hash = io->n.lm_hash;
	ldb = ldb_module_get_ctx(io->ac->module);

	if (io->ac->status->domain_data.pwdHistoryLength == 0) {
		return LDB_SUCCESS;
	}

	/* We might not have an old LM password */
	io->g.lm_history = talloc_array(io->ac,
					struct samr_Password,
					io->ac->status->domain_data.pwdHistoryLength);
	if (!io->g.lm_history) {
		return ldb_oom(ldb);
	}

	for (i = 0; i < MIN(io->ac->status->domain_data.pwdHistoryLength-1,
			    io->o.lm_history_len); i++) {
		io->g.lm_history[i+1] = io->o.lm_history[i];
	}
	io->g.lm_history_len = i + 1;

	if (io->g.lm_hash) {
		io->g.lm_history[0] = *io->g.lm_hash;
	} else {
		E_deshash("", io->g.lm_history[0].hash);
	}

	return LDB_SUCCESS;
}

static int setup_kerberos_keys(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb;
	krb5_error_code krb5_ret;
	krb5_principal salt_principal;
	krb5_data salt;
	krb5_keyblock key;
	krb5_data cleartext_data;

	ldb = ldb_module_get_ctx(io->ac->module);
	cleartext_data.data = (char *)io->n.cleartext_utf8->data;
	cleartext_data.length = io->n.cleartext_utf8->length;

	/* Many, many thanks to lukeh@padl.com for this
	 * algorithm, described in his Nov 10 2004 mail to
	 * samba-technical@lists.samba.org */

	/*
	 * Determine a salting principal
	 */
	if (io->u.is_computer) {
		char *name;
		char *saltbody;

		name = strlower_talloc(io->ac, io->u.sAMAccountName);
		if (!name) {
			return ldb_oom(ldb);
		}

		if (name[strlen(name)-1] == '$') {
			name[strlen(name)-1] = '\0';
		}

		saltbody = talloc_asprintf(io->ac, "%s.%s", name,
					   io->ac->status->domain_data.dns_domain);
		if (!saltbody) {
			return ldb_oom(ldb);
		}
		
		krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
					       &salt_principal,
					       io->ac->status->domain_data.realm,
					       "host", saltbody, NULL);
	} else if (io->u.user_principal_name) {
		char *user_principal_name;
		char *p;

		user_principal_name = talloc_strdup(io->ac, io->u.user_principal_name);
		if (!user_principal_name) {
			return ldb_oom(ldb);
		}

		p = strchr(user_principal_name, '@');
		if (p) {
			p[0] = '\0';
		}

		krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
					       &salt_principal,
					       io->ac->status->domain_data.realm,
					       user_principal_name, NULL);
	} else {
		krb5_ret = smb_krb5_make_principal(io->smb_krb5_context->krb5_context,
					       &salt_principal,
					       io->ac->status->domain_data.realm,
					       io->u.sAMAccountName, NULL);
	}
	if (krb5_ret) {
		ldb_asprintf_errstring(ldb,
				       "setup_kerberos_keys: "
				       "generation of a salting principal failed: %s",
				       smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
								  krb5_ret, io->ac));
		return LDB_ERR_OPERATIONS_ERROR;
	}

	/*
	 * create salt from salt_principal
	 */
	krb5_ret = smb_krb5_get_pw_salt(io->smb_krb5_context->krb5_context,
				    salt_principal, &salt);
	krb5_free_principal(io->smb_krb5_context->krb5_context, salt_principal);
	if (krb5_ret) {
		ldb_asprintf_errstring(ldb,
				       "setup_kerberos_keys: "
				       "generation of krb5_salt failed: %s",
				       smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
								  krb5_ret, io->ac));
		return LDB_ERR_OPERATIONS_ERROR;
	}
	/* create a talloc copy */
	io->g.salt = talloc_strndup(io->ac,
				    (char *)salt.data,
				    salt.length);
	smb_krb5_free_data_contents(io->smb_krb5_context->krb5_context, &salt);
	if (!io->g.salt) {
		return ldb_oom(ldb);
	}
	/* now use the talloced copy of the salt */
	salt.data	= discard_const(io->g.salt);
	salt.length	= strlen(io->g.salt);

	/*
	 * create ENCTYPE_AES256_CTS_HMAC_SHA1_96 key out of
	 * the salt and the cleartext password
	 */
	krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
						   NULL,
						   &salt,
						   &cleartext_data,
						   ENCTYPE_AES256_CTS_HMAC_SHA1_96,
						   &key);
	if (krb5_ret) {
		ldb_asprintf_errstring(ldb,
				       "setup_kerberos_keys: "
				       "generation of a aes256-cts-hmac-sha1-96 key failed: %s",
				       smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
								  krb5_ret, io->ac));
		return LDB_ERR_OPERATIONS_ERROR;
	}
	io->g.aes_256 = data_blob_talloc(io->ac,
					 KRB5_KEY_DATA(&key),
					 KRB5_KEY_LENGTH(&key));
	krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
	if (!io->g.aes_256.data) {
		return ldb_oom(ldb);
	}

	/*
	 * create ENCTYPE_AES128_CTS_HMAC_SHA1_96 key out of
	 * the salt and the cleartext password
	 */
	krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
						   NULL,
						   &salt,
						   &cleartext_data,
						   ENCTYPE_AES128_CTS_HMAC_SHA1_96,
						   &key);
	if (krb5_ret) {
		ldb_asprintf_errstring(ldb,
				       "setup_kerberos_keys: "
				       "generation of a aes128-cts-hmac-sha1-96 key failed: %s",
				       smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
								  krb5_ret, io->ac));
		return LDB_ERR_OPERATIONS_ERROR;
	}
	io->g.aes_128 = data_blob_talloc(io->ac,
					 KRB5_KEY_DATA(&key),
					 KRB5_KEY_LENGTH(&key));
	krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
	if (!io->g.aes_128.data) {
		return ldb_oom(ldb);
	}

	/*
	 * create ENCTYPE_DES_CBC_MD5 key out of
	 * the salt and the cleartext password
	 */
	krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
						   NULL,
						   &salt,
						   &cleartext_data,
						   ENCTYPE_DES_CBC_MD5,
						   &key);
	if (krb5_ret) {
		ldb_asprintf_errstring(ldb,
				       "setup_kerberos_keys: "
				       "generation of a des-cbc-md5 key failed: %s",
				       smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
								  krb5_ret, io->ac));
		return LDB_ERR_OPERATIONS_ERROR;
	}
	io->g.des_md5 = data_blob_talloc(io->ac,
					 KRB5_KEY_DATA(&key),
					 KRB5_KEY_LENGTH(&key));
	krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
	if (!io->g.des_md5.data) {
		return ldb_oom(ldb);
	}

	/*
	 * create ENCTYPE_DES_CBC_CRC key out of
	 * the salt and the cleartext password
	 */
	krb5_ret = smb_krb5_create_key_from_string(io->smb_krb5_context->krb5_context,
						   NULL,
						   &salt,
						   &cleartext_data,
						   ENCTYPE_DES_CBC_CRC,
						   &key);
	if (krb5_ret) {
		ldb_asprintf_errstring(ldb,
				       "setup_kerberos_keys: "
				       "generation of a des-cbc-crc key failed: %s",
				       smb_get_krb5_error_message(io->smb_krb5_context->krb5_context,
								  krb5_ret, io->ac));
		return LDB_ERR_OPERATIONS_ERROR;
	}
	io->g.des_crc = data_blob_talloc(io->ac,
					 KRB5_KEY_DATA(&key),
					 KRB5_KEY_LENGTH(&key));
	krb5_free_keyblock_contents(io->smb_krb5_context->krb5_context, &key);
	if (!io->g.des_crc.data) {
		return ldb_oom(ldb);
	}

	return LDB_SUCCESS;
}

static int setup_primary_kerberos(struct setup_password_fields_io *io,
				  const struct supplementalCredentialsBlob *old_scb,
				  struct package_PrimaryKerberosBlob *pkb)
{
	struct ldb_context *ldb;
	struct package_PrimaryKerberosCtr3 *pkb3 = &pkb->ctr.ctr3;
	struct supplementalCredentialsPackage *old_scp = NULL;
	struct package_PrimaryKerberosBlob _old_pkb;
	struct package_PrimaryKerberosCtr3 *old_pkb3 = NULL;
	uint32_t i;
	enum ndr_err_code ndr_err;

	ldb = ldb_module_get_ctx(io->ac->module);

	/*
	 * prepare generation of keys
	 *
	 * ENCTYPE_DES_CBC_MD5
	 * ENCTYPE_DES_CBC_CRC
	 */
	pkb->version		= 3;
	pkb3->salt.string	= io->g.salt;
	pkb3->num_keys		= 2;
	pkb3->keys		= talloc_array(io->ac,
					       struct package_PrimaryKerberosKey3,
					       pkb3->num_keys);
	if (!pkb3->keys) {
		return ldb_oom(ldb);
	}

	pkb3->keys[0].keytype	= ENCTYPE_DES_CBC_MD5;
	pkb3->keys[0].value	= &io->g.des_md5;
	pkb3->keys[1].keytype	= ENCTYPE_DES_CBC_CRC;
	pkb3->keys[1].value	= &io->g.des_crc;

	/* initialize the old keys to zero */
	pkb3->num_old_keys	= 0;
	pkb3->old_keys		= NULL;

	/* if there're no old keys, then we're done */
	if (!old_scb) {
		return LDB_SUCCESS;
	}

	for (i=0; i < old_scb->sub.num_packages; i++) {
		if (strcmp("Primary:Kerberos", old_scb->sub.packages[i].name) != 0) {
			continue;
		}

		if (!old_scb->sub.packages[i].data || !old_scb->sub.packages[i].data[0]) {
			continue;
		}

		old_scp = &old_scb->sub.packages[i];
		break;
	}
	/* Primary:Kerberos element of supplementalCredentials */
	if (old_scp) {
		DATA_BLOB blob;

		blob = strhex_to_data_blob(io->ac, old_scp->data);
		if (!blob.data) {
			return ldb_oom(ldb);
		}

		/* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
		ndr_err = ndr_pull_struct_blob(&blob, io->ac, &_old_pkb,
					       (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
		if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
			NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
			ldb_asprintf_errstring(ldb,
					       "setup_primary_kerberos: "
					       "failed to pull old package_PrimaryKerberosBlob: %s",
					       nt_errstr(status));
			return LDB_ERR_OPERATIONS_ERROR;
		}

		if (_old_pkb.version != 3) {
			ldb_asprintf_errstring(ldb,
					       "setup_primary_kerberos: "
					       "package_PrimaryKerberosBlob version[%u] expected[3]",
					       _old_pkb.version);
			return LDB_ERR_OPERATIONS_ERROR;
		}

		old_pkb3 = &_old_pkb.ctr.ctr3;
	}

	/* if we didn't found the old keys we're done */
	if (!old_pkb3) {
		return LDB_SUCCESS;
	}

	/* fill in the old keys */
	pkb3->num_old_keys	= old_pkb3->num_keys;
	pkb3->old_keys		= old_pkb3->keys;

	return LDB_SUCCESS;
}

static int setup_primary_kerberos_newer(struct setup_password_fields_io *io,
					const struct supplementalCredentialsBlob *old_scb,
					struct package_PrimaryKerberosBlob *pkb)
{
	struct ldb_context *ldb;
	struct package_PrimaryKerberosCtr4 *pkb4 = &pkb->ctr.ctr4;
	struct supplementalCredentialsPackage *old_scp = NULL;
	struct package_PrimaryKerberosBlob _old_pkb;
	struct package_PrimaryKerberosCtr4 *old_pkb4 = NULL;
	uint32_t i;
	enum ndr_err_code ndr_err;

	ldb = ldb_module_get_ctx(io->ac->module);

	/*
	 * prepare generation of keys
	 *
	 * ENCTYPE_AES256_CTS_HMAC_SHA1_96
	 * ENCTYPE_AES128_CTS_HMAC_SHA1_96
	 * ENCTYPE_DES_CBC_MD5
	 * ENCTYPE_DES_CBC_CRC
	 */
	pkb->version			= 4;
	pkb4->salt.string		= io->g.salt;
	pkb4->default_iteration_count	= 4096;
	pkb4->num_keys			= 4;

	pkb4->keys = talloc_array(io->ac,
				  struct package_PrimaryKerberosKey4,
				  pkb4->num_keys);
	if (!pkb4->keys) {
		return ldb_oom(ldb);
	}

	pkb4->keys[0].iteration_count	= 4096;
	pkb4->keys[0].keytype		= ENCTYPE_AES256_CTS_HMAC_SHA1_96;
	pkb4->keys[0].value		= &io->g.aes_256;
	pkb4->keys[1].iteration_count	= 4096;
	pkb4->keys[1].keytype		= ENCTYPE_AES128_CTS_HMAC_SHA1_96;
	pkb4->keys[1].value		= &io->g.aes_128;
	pkb4->keys[2].iteration_count	= 4096;
	pkb4->keys[2].keytype		= ENCTYPE_DES_CBC_MD5;
	pkb4->keys[2].value		= &io->g.des_md5;
	pkb4->keys[3].iteration_count	= 4096;
	pkb4->keys[3].keytype		= ENCTYPE_DES_CBC_CRC;
	pkb4->keys[3].value		= &io->g.des_crc;

	/* initialize the old keys to zero */
	pkb4->num_old_keys	= 0;
	pkb4->old_keys		= NULL;
	pkb4->num_older_keys	= 0;
	pkb4->older_keys	= NULL;

	/* if there're no old keys, then we're done */
	if (!old_scb) {
		return LDB_SUCCESS;
	}

	for (i=0; i < old_scb->sub.num_packages; i++) {
		if (strcmp("Primary:Kerberos-Newer-Keys", old_scb->sub.packages[i].name) != 0) {
			continue;
		}

		if (!old_scb->sub.packages[i].data || !old_scb->sub.packages[i].data[0]) {
			continue;
		}

		old_scp = &old_scb->sub.packages[i];
		break;
	}
	/* Primary:Kerberos-Newer-Keys element of supplementalCredentials */
	if (old_scp) {
		DATA_BLOB blob;

		blob = strhex_to_data_blob(io->ac, old_scp->data);
		if (!blob.data) {
			return ldb_oom(ldb);
		}

		/* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
		ndr_err = ndr_pull_struct_blob(&blob, io->ac,
					       &_old_pkb,
					       (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
		if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
			NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
			ldb_asprintf_errstring(ldb,
					       "setup_primary_kerberos_newer: "
					       "failed to pull old package_PrimaryKerberosBlob: %s",
					       nt_errstr(status));
			return LDB_ERR_OPERATIONS_ERROR;
		}

		if (_old_pkb.version != 4) {
			ldb_asprintf_errstring(ldb,
					       "setup_primary_kerberos_newer: "
					       "package_PrimaryKerberosBlob version[%u] expected[4]",
					       _old_pkb.version);
			return LDB_ERR_OPERATIONS_ERROR;
		}

		old_pkb4 = &_old_pkb.ctr.ctr4;
	}

	/* if we didn't found the old keys we're done */
	if (!old_pkb4) {
		return LDB_SUCCESS;
	}

	/* fill in the old keys */
	pkb4->num_old_keys	= old_pkb4->num_keys;
	pkb4->old_keys		= old_pkb4->keys;
	pkb4->num_older_keys	= old_pkb4->num_old_keys;
	pkb4->older_keys	= old_pkb4->old_keys;

	return LDB_SUCCESS;
}

static int setup_primary_wdigest(struct setup_password_fields_io *io,
				 const struct supplementalCredentialsBlob *old_scb,
				 struct package_PrimaryWDigestBlob *pdb)
{
	struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
	DATA_BLOB sAMAccountName;
	DATA_BLOB sAMAccountName_l;
	DATA_BLOB sAMAccountName_u;
	const char *user_principal_name = io->u.user_principal_name;
	DATA_BLOB userPrincipalName;
	DATA_BLOB userPrincipalName_l;
	DATA_BLOB userPrincipalName_u;
	DATA_BLOB netbios_domain;
	DATA_BLOB netbios_domain_l;
	DATA_BLOB netbios_domain_u;
	DATA_BLOB dns_domain;
	DATA_BLOB dns_domain_l;
	DATA_BLOB dns_domain_u;
	DATA_BLOB digest;
	DATA_BLOB delim;
	DATA_BLOB backslash;
	uint8_t i;
	struct {
		DATA_BLOB *user;
		DATA_BLOB *realm;
		DATA_BLOB *nt4dom;
	} wdigest[] = {
	/*
	 * See
	 * http://technet2.microsoft.com/WindowsServer/en/library/717b450c-f4a0-4cc9-86f4-cc0633aae5f91033.mspx?mfr=true
	 * for what precalculated hashes are supposed to be stored...
	 *
	 * I can't reproduce all values which should contain "Digest" as realm,
	 * am I doing something wrong or is w2k3 just broken...?
	 *
	 * W2K3 fills in following for a user:
	 *
	 * dn: CN=NewUser,OU=newtop,DC=sub1,DC=w2k3,DC=vmnet1,DC=vm,DC=base
	 * sAMAccountName: NewUser2Sam
	 * userPrincipalName: NewUser2Princ@sub1.w2k3.vmnet1.vm.base
	 *
	 * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
	 * b7ec9da91062199aee7d121e6710fe23 => newuser2sam:sub1:TestPwd2007
	 * 17d290bc5c9f463fac54c37a8cea134d => NEWUSER2SAM:SUB1:TestPwd2007
	 * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
	 * 5d57e7823938348127322e08cd81bcb5 => NewUser2Sam:sub1:TestPwd2007
	 * 07dd701bf8a011ece585de3d47237140 => NEWUSER2SAM:sub1:TestPwd2007
	 * e14fb0eb401498d2cb33c9aae1cc7f37 => newuser2sam:SUB1:TestPwd2007
	 * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
	 * f52da1266a6bdd290ffd48b2c823dda7 => newuser2sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
	 * d2b42f171248cec37a3c5c6b55404062 => NEWUSER2SAM:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
	 * fff8d790ff6c152aaeb6ebe17b4021de => NewUser2Sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
	 * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
	 * 2a7563c3715bc418d626dabef378c008 => NEWUSER2SAM:sub1.w2k3.vmnet1.vm.base:TestPwd2007
	 * c8e9557a87cd4200fda0c11d2fa03f96 => newuser2sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
	 * 221c55284451ae9b3aacaa2a3c86f10f => NewUser2Princ@sub1.w2k3.vmnet1.vm.base::TestPwd2007
	 * 74e1be668853d4324d38c07e2acfb8ea => (w2k3 has a bug here!) newuser2princ@sub1.w2k3.vmnet1.vm.base::TestPwd2007
	 * e1e244ab7f098e3ae1761be7f9229bbb => NEWUSER2PRINC@SUB1.W2K3.VMNET1.VM.BASE::TestPwd2007
	 * 86db637df42513039920e605499c3af6 => SUB1\NewUser2Sam::TestPwd2007
	 * f5e43474dfaf067fee8197a253debaa2 => sub1\newuser2sam::TestPwd2007
	 * 2ecaa8382e2518e4b77a52422b279467 => SUB1\NEWUSER2SAM::TestPwd2007
	 * 31dc704d3640335b2123d4ee28aa1f11 => ??? changes with NewUser2Sam => NewUser1Sam
	 * 36349f5cecd07320fb3bb0e119230c43 => ??? changes with NewUser2Sam => NewUser1Sam
	 * 12adf019d037fb535c01fd0608e78d9d => ??? changes with NewUser2Sam => NewUser1Sam
	 * 6feecf8e724906f3ee1105819c5105a1 => ??? changes with NewUser2Princ => NewUser1Princ
	 * 6c6911f3de6333422640221b9c51ff1f => ??? changes with NewUser2Princ => NewUser1Princ
	 * 4b279877e742895f9348ac67a8de2f69 => ??? changes with NewUser2Princ => NewUser1Princ
	 * db0c6bff069513e3ebb9870d29b57490 => ??? changes with NewUser2Sam => NewUser1Sam
	 * 45072621e56b1c113a4e04a8ff68cd0e => ??? changes with NewUser2Sam => NewUser1Sam
	 * 11d1220abc44a9c10cf91ef4a9c1de02 => ??? changes with NewUser2Sam => NewUser1Sam
	 *
	 * dn: CN=NewUser,OU=newtop,DC=sub1,DC=w2k3,DC=vmnet1,DC=vm,DC=base
	 * sAMAccountName: NewUser2Sam
	 *
	 * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
	 * b7ec9da91062199aee7d121e6710fe23 => newuser2sam:sub1:TestPwd2007
	 * 17d290bc5c9f463fac54c37a8cea134d => NEWUSER2SAM:SUB1:TestPwd2007
	 * 4279815024bda54fc074a5f8bd0a6e6f => NewUser2Sam:SUB1:TestPwd2007
	 * 5d57e7823938348127322e08cd81bcb5 => NewUser2Sam:sub1:TestPwd2007
	 * 07dd701bf8a011ece585de3d47237140 => NEWUSER2SAM:sub1:TestPwd2007
	 * e14fb0eb401498d2cb33c9aae1cc7f37 => newuser2sam:SUB1:TestPwd2007
	 * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
	 * f52da1266a6bdd290ffd48b2c823dda7 => newuser2sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
	 * d2b42f171248cec37a3c5c6b55404062 => NEWUSER2SAM:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
	 * fff8d790ff6c152aaeb6ebe17b4021de => NewUser2Sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
	 * 8dadc90250f873d8b883f79d890bef82 => NewUser2Sam:sub1.w2k3.vmnet1.vm.base:TestPwd2007
	 * 2a7563c3715bc418d626dabef378c008 => NEWUSER2SAM:sub1.w2k3.vmnet1.vm.base:TestPwd2007
	 * c8e9557a87cd4200fda0c11d2fa03f96 => newuser2sam:SUB1.W2K3.VMNET1.VM.BASE:TestPwd2007
	 * 8a140d30b6f0a5912735dc1e3bc993b4 => NewUser2Sam@sub1.w2k3.vmnet1.vm.base::TestPwd2007
	 * 86d95b2faae6cae4ec261e7fbaccf093 => (here w2k3 is correct) newuser2sam@sub1.w2k3.vmnet1.vm.base::TestPwd2007
	 * dfeff1493110220efcdfc6362e5f5450 => NEWUSER2SAM@SUB1.W2K3.VMNET1.VM.BASE::TestPwd2007
	 * 86db637df42513039920e605499c3af6 => SUB1\NewUser2Sam::TestPwd2007
	 * f5e43474dfaf067fee8197a253debaa2 => sub1\newuser2sam::TestPwd2007
	 * 2ecaa8382e2518e4b77a52422b279467 => SUB1\NEWUSER2SAM::TestPwd2007
	 * 31dc704d3640335b2123d4ee28aa1f11 => ???M1   changes with NewUser2Sam => NewUser1Sam
	 * 36349f5cecd07320fb3bb0e119230c43 => ???M1.L changes with newuser2sam => newuser1sam
	 * 12adf019d037fb535c01fd0608e78d9d => ???M1.U changes with NEWUSER2SAM => NEWUSER1SAM
	 * 569b4533f2d9e580211dd040e5e360a8 => ???M2   changes with NewUser2Princ => NewUser1Princ
	 * 52528bddf310a587c5d7e6a9ae2cbb20 => ???M2.L changes with newuser2princ => newuser1princ
	 * 4f629a4f0361289ca4255ab0f658fcd5 => ???M3 changes with NewUser2Princ => NewUser1Princ (doesn't depend on case of userPrincipal )
	 * db0c6bff069513e3ebb9870d29b57490 => ???M4 changes with NewUser2Sam => NewUser1Sam
	 * 45072621e56b1c113a4e04a8ff68cd0e => ???M5 changes with NewUser2Sam => NewUser1Sam (doesn't depend on case of sAMAccountName)
	 * 11d1220abc44a9c10cf91ef4a9c1de02 => ???M4.U changes with NEWUSER2SAM => NEWUSER1SAM
	 */

	/*
	 * sAMAccountName, netbios_domain
	 */
		{
		.user	= &sAMAccountName,
		.realm	= &netbios_domain,
		},
		{
		.user	= &sAMAccountName_l,
		.realm	= &netbios_domain_l,
		},
		{
		.user	= &sAMAccountName_u,
		.realm	= &netbios_domain_u,
		},
		{
		.user	= &sAMAccountName,
		.realm	= &netbios_domain_u,
		},
		{
		.user	= &sAMAccountName,
		.realm	= &netbios_domain_l,
		},
		{
		.user	= &sAMAccountName_u,
		.realm	= &netbios_domain_l,
		},
		{
		.user	= &sAMAccountName_l,
		.realm	= &netbios_domain_u,
		},
	/* 
	 * sAMAccountName, dns_domain
	 */
		{
		.user	= &sAMAccountName,
		.realm	= &dns_domain,
		},
		{
		.user	= &sAMAccountName_l,
		.realm	= &dns_domain_l,
		},
		{
		.user	= &sAMAccountName_u,
		.realm	= &dns_domain_u,
		},
		{
		.user	= &sAMAccountName,
		.realm	= &dns_domain_u,
		},
		{
		.user	= &sAMAccountName,
		.realm	= &dns_domain_l,
		},
		{
		.user	= &sAMAccountName_u,
		.realm	= &dns_domain_l,
		},
		{
		.user	= &sAMAccountName_l,
		.realm	= &dns_domain_u,
		},
	/* 
	 * userPrincipalName, no realm
	 */
		{
		.user	= &userPrincipalName,
		},
		{
		/* 
		 * NOTE: w2k3 messes this up, if the user has a real userPrincipalName,
		 *       the fallback to the sAMAccountName based userPrincipalName is correct
		 */
		.user	= &userPrincipalName_l,
		},
		{
		.user	= &userPrincipalName_u,
		},
	/* 
	 * nt4dom\sAMAccountName, no realm
	 */
		{
		.user	= &sAMAccountName,
		.nt4dom	= &netbios_domain
		},
		{
		.user	= &sAMAccountName_l,
		.nt4dom	= &netbios_domain_l
		},
		{
		.user	= &sAMAccountName_u,
		.nt4dom	= &netbios_domain_u
		},

	/*
	 * the following ones are guessed depending on the technet2 article
	 * but not reproducable on a w2k3 server
	 */
	/* sAMAccountName with "Digest" realm */
		{
		.user 	= &sAMAccountName,
		.realm	= &digest
		},
		{
		.user 	= &sAMAccountName_l,
		.realm	= &digest
		},
		{
		.user 	= &sAMAccountName_u,
		.realm	= &digest
		},
	/* userPrincipalName with "Digest" realm */
		{
		.user	= &userPrincipalName,
		.realm	= &digest
		},
		{
		.user	= &userPrincipalName_l,
		.realm	= &digest
		},
		{
		.user	= &userPrincipalName_u,
		.realm	= &digest
		},
	/* nt4dom\\sAMAccountName with "Digest" realm */
		{
		.user 	= &sAMAccountName,
		.nt4dom	= &netbios_domain,
		.realm	= &digest
		},
		{
		.user 	= &sAMAccountName_l,
		.nt4dom	= &netbios_domain_l,
		.realm	= &digest
		},
		{
		.user 	= &sAMAccountName_u,
		.nt4dom	= &netbios_domain_u,
		.realm	= &digest
		},
	};

	/* prepare DATA_BLOB's used in the combinations array */
	sAMAccountName		= data_blob_string_const(io->u.sAMAccountName);
	sAMAccountName_l	= data_blob_string_const(strlower_talloc(io->ac, io->u.sAMAccountName));
	if (!sAMAccountName_l.data) {
		return ldb_oom(ldb);
	}
	sAMAccountName_u	= data_blob_string_const(strupper_talloc(io->ac, io->u.sAMAccountName));
	if (!sAMAccountName_u.data) {
		return ldb_oom(ldb);
	}

	/* if the user doesn't have a userPrincipalName, create one (with lower case realm) */
	if (!user_principal_name) {
		user_principal_name = talloc_asprintf(io->ac, "%s@%s",
						      io->u.sAMAccountName,
						      io->ac->status->domain_data.dns_domain);
		if (!user_principal_name) {
			return ldb_oom(ldb);
		}	
	}
	userPrincipalName	= data_blob_string_const(user_principal_name);
	userPrincipalName_l	= data_blob_string_const(strlower_talloc(io->ac, user_principal_name));
	if (!userPrincipalName_l.data) {
		return ldb_oom(ldb);
	}
	userPrincipalName_u	= data_blob_string_const(strupper_talloc(io->ac, user_principal_name));
	if (!userPrincipalName_u.data) {
		return ldb_oom(ldb);
	}

	netbios_domain		= data_blob_string_const(io->ac->status->domain_data.netbios_domain);
	netbios_domain_l	= data_blob_string_const(strlower_talloc(io->ac,
									 io->ac->status->domain_data.netbios_domain));
	if (!netbios_domain_l.data) {
		return ldb_oom(ldb);
	}
	netbios_domain_u	= data_blob_string_const(strupper_talloc(io->ac,
									 io->ac->status->domain_data.netbios_domain));
	if (!netbios_domain_u.data) {
		return ldb_oom(ldb);
	}

	dns_domain		= data_blob_string_const(io->ac->status->domain_data.dns_domain);
	dns_domain_l		= data_blob_string_const(io->ac->status->domain_data.dns_domain);
	dns_domain_u		= data_blob_string_const(io->ac->status->domain_data.realm);

	digest			= data_blob_string_const("Digest");

	delim			= data_blob_string_const(":");
	backslash		= data_blob_string_const("\\");

	pdb->num_hashes	= ARRAY_SIZE(wdigest);
	pdb->hashes	= talloc_array(io->ac, struct package_PrimaryWDigestHash,
				       pdb->num_hashes);
	if (!pdb->hashes) {
		return ldb_oom(ldb);
	}

	for (i=0; i < ARRAY_SIZE(wdigest); i++) {
		MD5_CTX md5;
		MD5Init(&md5);
		if (wdigest[i].nt4dom) {
			MD5Update(&md5, wdigest[i].nt4dom->data, wdigest[i].nt4dom->length);
			MD5Update(&md5, backslash.data, backslash.length);
		}
		MD5Update(&md5, wdigest[i].user->data, wdigest[i].user->length);
		MD5Update(&md5, delim.data, delim.length);
		if (wdigest[i].realm) {
			MD5Update(&md5, wdigest[i].realm->data, wdigest[i].realm->length);
		}
		MD5Update(&md5, delim.data, delim.length);
		MD5Update(&md5, io->n.cleartext_utf8->data, io->n.cleartext_utf8->length);
		MD5Final(pdb->hashes[i].hash, &md5);
	}

	return LDB_SUCCESS;
}

static int setup_primary_samba_gpg(struct setup_password_fields_io *io,
				   struct package_PrimarySambaGPGBlob *pgb)
{
	struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
#ifdef ENABLE_GPGME
	gpgme_error_t gret;
	gpgme_ctx_t ctx = NULL;
	size_t num_keys = str_list_length(io->ac->gpg_key_ids);
	gpgme_key_t keys[num_keys+1];
	size_t ki = 0;
	size_t kr = 0;
	gpgme_data_t plain_data = NULL;
	gpgme_data_t crypt_data = NULL;
	size_t crypt_length = 0;
	char *crypt_mem = NULL;

	gret = gpgme_new(&ctx);
	if (gret != GPG_ERR_NO_ERROR) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "%s:%s: gret[%u] %s\n",
			  __location__, __func__,
			  gret, gpgme_strerror(gret));
		return ldb_module_operr(io->ac->module);
	}

	gpgme_set_armor(ctx, 1);

	gret = gpgme_data_new_from_mem(&plain_data,
				       (const char *)io->n.cleartext_utf16->data,
				       io->n.cleartext_utf16->length,
				       0 /* no copy */);
	if (gret != GPG_ERR_NO_ERROR) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "%s:%s: gret[%u] %s\n",
			  __location__, __func__,
			  gret, gpgme_strerror(gret));
		gpgme_release(ctx);
		return ldb_module_operr(io->ac->module);
	}
	gret = gpgme_data_new(&crypt_data);
	if (gret != GPG_ERR_NO_ERROR) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "%s:%s: gret[%u] %s\n",
			  __location__, __func__,
			  gret, gpgme_strerror(gret));
		gpgme_data_release(plain_data);
		gpgme_release(ctx);
		return ldb_module_operr(io->ac->module);
	}

	for (ki = 0; ki < num_keys; ki++) {
		const char *key_id = io->ac->gpg_key_ids[ki];
		size_t len = strlen(key_id);

		keys[ki] = NULL;

		if (len < 16) {
			ldb_debug(ldb, LDB_DEBUG_FATAL,
				  "%s:%s: ki[%zu] key_id[%s] strlen < 16, "
				  "please specifiy at least the 64bit key id\n",
				  __location__, __func__,
				  ki, key_id);
			for (kr = 0; keys[kr] != NULL; kr++) {
				gpgme_key_release(keys[kr]);
			}
			gpgme_data_release(crypt_data);
			gpgme_data_release(plain_data);
			gpgme_release(ctx);
			return ldb_module_operr(io->ac->module);
		}

		gret = gpgme_get_key(ctx, key_id, &keys[ki], 0 /* public key */);
		if (gret != GPG_ERR_NO_ERROR) {
			keys[ki] = NULL;
			ldb_debug(ldb, LDB_DEBUG_ERROR,
				  "%s:%s: ki[%zu] key_id[%s] gret[%u] %s\n",
				  __location__, __func__,
				  ki, key_id,
				  gret, gpgme_strerror(gret));
			for (kr = 0; keys[kr] != NULL; kr++) {
				gpgme_key_release(keys[kr]);
			}
			gpgme_data_release(crypt_data);
			gpgme_data_release(plain_data);
			gpgme_release(ctx);
			return ldb_module_operr(io->ac->module);
		}
	}
	keys[ki] = NULL;

	gret = gpgme_op_encrypt(ctx, keys,
				GPGME_ENCRYPT_ALWAYS_TRUST,
				plain_data, crypt_data);
	gpgme_data_release(plain_data);
	plain_data = NULL;
	for (kr = 0; keys[kr] != NULL; kr++) {
		gpgme_key_release(keys[kr]);
		keys[kr] = NULL;
	}
	gpgme_release(ctx);
	ctx = NULL;
	if (gret != GPG_ERR_NO_ERROR) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "%s:%s: gret[%u] %s\n",
			  __location__, __func__,
			  gret, gpgme_strerror(gret));
		gpgme_data_release(crypt_data);
		return ldb_module_operr(io->ac->module);
	}

	crypt_mem = gpgme_data_release_and_get_mem(crypt_data, &crypt_length);
	crypt_data = NULL;
	if (crypt_mem == NULL) {
		return ldb_module_oom(io->ac->module);
	}

	pgb->gpg_blob = data_blob_talloc(io->ac,
					 (const uint8_t *)crypt_mem,
					 crypt_length);
	gpgme_free(crypt_mem);
	crypt_mem = NULL;
	crypt_length = 0;
	if (pgb->gpg_blob.data == NULL) {
		return ldb_module_oom(io->ac->module);
	}

	return LDB_SUCCESS;
#else /* ENABLE_GPGME */
	ldb_debug_set(ldb, LDB_DEBUG_FATAL,
		      "You configured 'password hash gpg key ids', "
		      "but GPGME support is missing. (%s:%d)",
		      __FILE__, __LINE__);
	return LDB_ERR_UNWILLING_TO_PERFORM;
#endif /* else ENABLE_GPGME */
}

static int setup_supplemental_field(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb;
	struct supplementalCredentialsBlob scb;
	struct supplementalCredentialsBlob *old_scb = NULL;
	/* Packages + (Kerberos-Newer-Keys, Kerberos, WDigest, CLEARTEXT, SambaGPG) */
	uint32_t num_names = 0;
	const char *names[1+5];
	uint32_t num_packages = 0;
	struct supplementalCredentialsPackage packages[1+5];
	/* Packages */
	struct supplementalCredentialsPackage *pp = NULL;
	struct package_PackagesBlob pb;
	DATA_BLOB pb_blob;
	char *pb_hexstr;
	/* Primary:Kerberos-Newer-Keys */
	const char **nkn = NULL;
	struct supplementalCredentialsPackage *pkn = NULL;
	struct package_PrimaryKerberosBlob pknb;
	DATA_BLOB pknb_blob;
	char *pknb_hexstr;
	/* Primary:Kerberos */
	const char **nk = NULL;
	struct supplementalCredentialsPackage *pk = NULL;
	struct package_PrimaryKerberosBlob pkb;
	DATA_BLOB pkb_blob;
	char *pkb_hexstr;
	/* Primary:WDigest */
	const char **nd = NULL;
	struct supplementalCredentialsPackage *pd = NULL;
	struct package_PrimaryWDigestBlob pdb;
	DATA_BLOB pdb_blob;
	char *pdb_hexstr;
	/* Primary:CLEARTEXT */
	const char **nc = NULL;
	struct supplementalCredentialsPackage *pc = NULL;
	struct package_PrimaryCLEARTEXTBlob pcb;
	DATA_BLOB pcb_blob;
	char *pcb_hexstr;
	/* Primary:SambaGPG */
	const char **ng = NULL;
	struct supplementalCredentialsPackage *pg = NULL;
	struct package_PrimarySambaGPGBlob pgb;
	DATA_BLOB pgb_blob;
	char *pgb_hexstr;
	int ret;
	enum ndr_err_code ndr_err;
	uint8_t zero16[16];
	bool do_newer_keys = false;
	bool do_cleartext = false;
	bool do_samba_gpg = false;

	ZERO_STRUCT(zero16);
	ZERO_STRUCT(names);
	ZERO_STRUCT(packages);

	ldb = ldb_module_get_ctx(io->ac->module);

	if (!io->n.cleartext_utf8) {
		/* 
		 * when we don't have a cleartext password
		 * we can't setup a supplementalCredential value
		 */
		return LDB_SUCCESS;
	}

	/* if there's an old supplementaCredentials blob then use it */
	if (io->o.supplemental) {
		if (io->o.scb.sub.signature == SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
			old_scb = &io->o.scb;
		} else {
			ldb_debug(ldb, LDB_DEBUG_ERROR,
				  "setup_supplemental_field: "
				  "supplementalCredentialsBlob "
				  "signature[0x%04X] expected[0x%04X]",
				  io->o.scb.sub.signature,
				  SUPPLEMENTAL_CREDENTIALS_SIGNATURE);
		}
	}
	/* Per MS-SAMR 3.1.1.8.11.6 we create AES keys if our domain functionality level is 2008 or higher */
	do_newer_keys = (dsdb_functional_level(ldb) >= DS_DOMAIN_FUNCTION_2008);

	if (io->ac->status->domain_data.store_cleartext &&
	    (io->u.userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED)) {
		do_cleartext = true;
	}

	if (io->ac->gpg_key_ids != NULL) {
		do_samba_gpg = true;
	}

	/*
	 * The ordering is this
	 *
	 * Primary:Kerberos-Newer-Keys (optional)
	 * Primary:Kerberos
	 * Primary:WDigest
	 * Primary:CLEARTEXT (optional)
	 * Primary:SambaGPG (optional)
	 *
	 * And the 'Packages' package is insert before the last
	 * other package.
	 *
	 * Note: it's important that Primary:SambaGPG is added as
	 * the last element. This is the indication that it matches
	 * the current password. When a password change happens on
	 * a Windows DC, it will keep the old Primary:SambaGPG value,
	 * but as the first element.
	 */
	if (do_newer_keys) {
		/* Primary:Kerberos-Newer-Keys */
		nkn = &names[num_names++];
		pkn = &packages[num_packages++];
	}

	/* Primary:Kerberos */
	nk = &names[num_names++];
	pk = &packages[num_packages++];

	if (!do_cleartext && !do_samba_gpg) {
		/* Packages */
		pp = &packages[num_packages++];
	}

	/* Primary:WDigest */
	nd = &names[num_names++];
	pd = &packages[num_packages++];

	if (do_cleartext) {
		if (!do_samba_gpg) {
			/* Packages */
			pp = &packages[num_packages++];
		}

		/* Primary:CLEARTEXT */
		nc = &names[num_names++];
		pc = &packages[num_packages++];
	}

	if (do_samba_gpg) {
		/* Packages */
		pp = &packages[num_packages++];

		/* Primary:SambaGPG */
		ng = &names[num_names++];
		pg = &packages[num_packages++];
	}

	if (pkn) {
		/*
		 * setup 'Primary:Kerberos-Newer-Keys' element
		 */
		*nkn = "Kerberos-Newer-Keys";

		ret = setup_primary_kerberos_newer(io, old_scb, &pknb);
		if (ret != LDB_SUCCESS) {
			return ret;
		}

		ndr_err = ndr_push_struct_blob(&pknb_blob, io->ac,
					       &pknb,
					       (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
		if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
			NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
			ldb_asprintf_errstring(ldb,
					       "setup_supplemental_field: "
					       "failed to push package_PrimaryKerberosNeverBlob: %s",
					       nt_errstr(status));
			return LDB_ERR_OPERATIONS_ERROR;
		}
		pknb_hexstr = data_blob_hex_string_upper(io->ac, &pknb_blob);
		if (!pknb_hexstr) {
			return ldb_oom(ldb);
		}
		pkn->name	= "Primary:Kerberos-Newer-Keys";
		pkn->reserved	= 1;
		pkn->data	= pknb_hexstr;
	}

	/*
	 * setup 'Primary:Kerberos' element
	 */
	*nk = "Kerberos";

	ret = setup_primary_kerberos(io, old_scb, &pkb);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ndr_err = ndr_push_struct_blob(&pkb_blob, io->ac, 
				       &pkb,
				       (ndr_push_flags_fn_t)ndr_push_package_PrimaryKerberosBlob);
	if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
		NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
		ldb_asprintf_errstring(ldb,
				       "setup_supplemental_field: "
				       "failed to push package_PrimaryKerberosBlob: %s",
				       nt_errstr(status));
		return LDB_ERR_OPERATIONS_ERROR;
	}
	pkb_hexstr = data_blob_hex_string_upper(io->ac, &pkb_blob);
	if (!pkb_hexstr) {
		return ldb_oom(ldb);
	}
	pk->name	= "Primary:Kerberos";
	pk->reserved	= 1;
	pk->data	= pkb_hexstr;

	/*
	 * setup 'Primary:WDigest' element
	 */
	*nd = "WDigest";

	ret = setup_primary_wdigest(io, old_scb, &pdb);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ndr_err = ndr_push_struct_blob(&pdb_blob, io->ac, 
				       &pdb,
				       (ndr_push_flags_fn_t)ndr_push_package_PrimaryWDigestBlob);
	if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
		NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
		ldb_asprintf_errstring(ldb,
				       "setup_supplemental_field: "
				       "failed to push package_PrimaryWDigestBlob: %s",
				       nt_errstr(status));
		return LDB_ERR_OPERATIONS_ERROR;
	}
	pdb_hexstr = data_blob_hex_string_upper(io->ac, &pdb_blob);
	if (!pdb_hexstr) {
		return ldb_oom(ldb);
	}
	pd->name	= "Primary:WDigest";
	pd->reserved	= 1;
	pd->data	= pdb_hexstr;

	/*
	 * setup 'Primary:CLEARTEXT' element
	 */
	if (pc) {
		*nc		= "CLEARTEXT";

		pcb.cleartext	= *io->n.cleartext_utf16;

		ndr_err = ndr_push_struct_blob(&pcb_blob, io->ac, 
					       &pcb,
					       (ndr_push_flags_fn_t)ndr_push_package_PrimaryCLEARTEXTBlob);
		if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
			NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
			ldb_asprintf_errstring(ldb,
					       "setup_supplemental_field: "
					       "failed to push package_PrimaryCLEARTEXTBlob: %s",
					       nt_errstr(status));
			return LDB_ERR_OPERATIONS_ERROR;
		}
		pcb_hexstr = data_blob_hex_string_upper(io->ac, &pcb_blob);
		if (!pcb_hexstr) {
			return ldb_oom(ldb);
		}
		pc->name	= "Primary:CLEARTEXT";
		pc->reserved	= 1;
		pc->data	= pcb_hexstr;
	}

	/*
	 * setup 'Primary:SambaGPG' element
	 */
	if (pg) {
		*ng		= "SambaGPG";

		ret = setup_primary_samba_gpg(io, &pgb);
		if (ret != LDB_SUCCESS) {
			return ret;
		}

		ndr_err = ndr_push_struct_blob(&pgb_blob, io->ac, &pgb,
			(ndr_push_flags_fn_t)ndr_push_package_PrimarySambaGPGBlob);
		if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
			NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
			ldb_asprintf_errstring(ldb,
					"setup_supplemental_field: failed to "
					"push package_PrimarySambaGPGBlob: %s",
					nt_errstr(status));
			return LDB_ERR_OPERATIONS_ERROR;
		}
		pgb_hexstr = data_blob_hex_string_upper(io->ac, &pgb_blob);
		if (!pgb_hexstr) {
			return ldb_oom(ldb);
		}
		pg->name	= "Primary:SambaGPG";
		pg->reserved	= 1;
		pg->data	= pgb_hexstr;
	}

	/*
	 * setup 'Packages' element
	 */
	pb.names = names;
	ndr_err = ndr_push_struct_blob(&pb_blob, io->ac, 
				       &pb,
				       (ndr_push_flags_fn_t)ndr_push_package_PackagesBlob);
	if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
		NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
		ldb_asprintf_errstring(ldb,
				       "setup_supplemental_field: "
				       "failed to push package_PackagesBlob: %s",
				       nt_errstr(status));
		return LDB_ERR_OPERATIONS_ERROR;
	}
	pb_hexstr = data_blob_hex_string_upper(io->ac, &pb_blob);
	if (!pb_hexstr) {
		return ldb_oom(ldb);
	}
	pp->name	= "Packages";
	pp->reserved	= 2;
	pp->data	= pb_hexstr;

	/*
	 * setup 'supplementalCredentials' value
	 */
	ZERO_STRUCT(scb);
	scb.sub.signature	= SUPPLEMENTAL_CREDENTIALS_SIGNATURE;
	scb.sub.num_packages	= num_packages;
	scb.sub.packages	= packages;

	ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac, 
				       &scb,
				       (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
	if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
		NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
		ldb_asprintf_errstring(ldb,
				       "setup_supplemental_field: "
				       "failed to push supplementalCredentialsBlob: %s",
				       nt_errstr(status));
		return LDB_ERR_OPERATIONS_ERROR;
	}

	return LDB_SUCCESS;
}

static int setup_last_set_field(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
	const struct ldb_message *msg = NULL;
	struct timeval tv = { .tv_sec = 0 };
	const struct ldb_val *old_val = NULL;
	const struct ldb_val *new_val = NULL;
	int ret;

	switch (io->ac->req->operation) {
	case LDB_ADD:
		msg = io->ac->req->op.add.message;
		break;
	case LDB_MODIFY:
		msg = io->ac->req->op.mod.message;
		break;
	default:
		return LDB_ERR_OPERATIONS_ERROR;
		break;
	}

	if (io->ac->pwd_last_set_bypass) {
		struct ldb_message_element *el1 = NULL;
		struct ldb_message_element *el2 = NULL;

		if (msg == NULL) {
			return LDB_ERR_CONSTRAINT_VIOLATION;
		}

		el1 = dsdb_get_single_valued_attr(msg, "pwdLastSet",
						  io->ac->req->operation);
		if (el1 == NULL) {
			return LDB_ERR_CONSTRAINT_VIOLATION;
		}
		el2 = ldb_msg_find_element(msg, "pwdLastSet");
		if (el2 == NULL) {
			return LDB_ERR_CONSTRAINT_VIOLATION;
		}
		if (el1 != el2) {
			return LDB_ERR_CONSTRAINT_VIOLATION;
		}

		io->g.last_set = samdb_result_nttime(msg, "pwdLastSet", 0);
		return LDB_SUCCESS;
	}

	ret = msg_find_old_and_new_pwd_val(msg, "pwdLastSet",
					   io->ac->req->operation,
					   &new_val, &old_val);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	if (old_val != NULL && new_val == NULL) {
		ldb_set_errstring(ldb,
				  "'pwdLastSet' deletion is not allowed!");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	io->g.last_set = UINT64_MAX;
	if (new_val != NULL) {
		struct ldb_message *tmp_msg = NULL;

		tmp_msg = ldb_msg_new(io->ac);
		if (tmp_msg == NULL) {
			return ldb_module_oom(io->ac->module);
		}

		if (old_val != NULL) {
			NTTIME old_last_set = 0;

			ret = ldb_msg_add_value(tmp_msg, "oldval",
						old_val, NULL);
			if (ret != LDB_SUCCESS) {
				return ret;
			}

			old_last_set = samdb_result_nttime(tmp_msg,
							   "oldval",
							   1);
			if (io->u.pwdLastSet != old_last_set) {
				return dsdb_module_werror(io->ac->module,
					LDB_ERR_NO_SUCH_ATTRIBUTE,
					WERR_DS_CANT_REM_MISSING_ATT_VAL,
					"setup_last_set_field: old pwdLastSet "
					"value not found!");
			}
		}

		ret = ldb_msg_add_value(tmp_msg, "newval",
					new_val, NULL);
		if (ret != LDB_SUCCESS) {
			return ret;
		}

		io->g.last_set = samdb_result_nttime(tmp_msg,
						     "newval",
						     1);
	} else if (ldb_msg_find_element(msg, "pwdLastSet")) {
		ldb_set_errstring(ldb,
				  "'pwdLastSet' deletion is not allowed!");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	} else if (io->ac->smartcard_reset) {
		/*
		 * adding UF_SMARTCARD_REQUIRED doesn't update
		 * pwdLastSet implicitly.
		 */
		io->ac->update_lastset = false;
	}

	/* only 0 or -1 (0xFFFFFFFFFFFFFFFF) are allowed */
	switch (io->g.last_set) {
	case 0:
		if (!io->ac->pwd_last_set_default) {
			break;
		}
		if (!io->ac->update_password) {
			break;
		}
		/* fall through */
	case UINT64_MAX:
		if (!io->ac->update_password &&
		    io->u.pwdLastSet != 0 &&
		    io->u.pwdLastSet != UINT64_MAX)
		{
			/*
			 * Just setting pwdLastSet to -1, while not changing
			 * any password field has no effect if pwdLastSet
			 * is already non-zero.
			 */
			io->ac->update_lastset = false;
			break;
		}
		/* -1 means set it as now */
		GetTimeOfDay(&tv);
		io->g.last_set = timeval_to_nttime(&tv);
		break;
	default:
		return dsdb_module_werror(io->ac->module,
					  LDB_ERR_OTHER,
					  WERR_INVALID_PARAMETER,
					  "setup_last_set_field: "
					  "pwdLastSet must be 0 or -1 only!");
	}

	if (io->ac->req->operation == LDB_ADD) {
		/*
		 * We always need to store the value on add
		 * operations.
		 */
		return LDB_SUCCESS;
	}

	if (io->g.last_set == io->u.pwdLastSet) {
		/*
		 * Just setting pwdLastSet to 0, is no-op if it's already 0.
		 */
		io->ac->update_lastset = false;
	}

	return LDB_SUCCESS;
}

static int setup_given_passwords(struct setup_password_fields_io *io,
				 struct setup_password_fields_given *g)
{
	struct ldb_context *ldb;
	bool ok;

	ldb = ldb_module_get_ctx(io->ac->module);

	if (g->cleartext_utf8) {
		struct ldb_val *cleartext_utf16_blob;

		cleartext_utf16_blob = talloc(io->ac, struct ldb_val);
		if (!cleartext_utf16_blob) {
			return ldb_oom(ldb);
		}
		if (!convert_string_talloc(io->ac,
					   CH_UTF8, CH_UTF16,
					   g->cleartext_utf8->data,
					   g->cleartext_utf8->length,
					   (void *)&cleartext_utf16_blob->data,
					   &cleartext_utf16_blob->length)) {
			if (g->cleartext_utf8->length != 0) {
				talloc_free(cleartext_utf16_blob);
				ldb_asprintf_errstring(ldb,
						       "setup_password_fields: "
						       "failed to generate UTF16 password from cleartext UTF8 one for user '%s'!",
						       io->u.sAMAccountName);
				return LDB_ERR_CONSTRAINT_VIOLATION;
			} else {
				/* passwords with length "0" are valid! */
				cleartext_utf16_blob->data = NULL;
				cleartext_utf16_blob->length = 0;
			}
		}
		g->cleartext_utf16 = cleartext_utf16_blob;
	} else if (g->cleartext_utf16) {
		struct ldb_val *cleartext_utf8_blob;

		cleartext_utf8_blob = talloc(io->ac, struct ldb_val);
		if (!cleartext_utf8_blob) {
			return ldb_oom(ldb);
		}
		if (!convert_string_talloc(io->ac,
					   CH_UTF16MUNGED, CH_UTF8,
					   g->cleartext_utf16->data,
					   g->cleartext_utf16->length,
					   (void *)&cleartext_utf8_blob->data,
					   &cleartext_utf8_blob->length)) {
			if (g->cleartext_utf16->length != 0) {
				/* We must bail out here, the input wasn't even
				 * a multiple of 2 bytes */
				talloc_free(cleartext_utf8_blob);
				ldb_asprintf_errstring(ldb,
						       "setup_password_fields: "
						       "failed to generate UTF8 password from cleartext UTF 16 one for user '%s' - the latter had odd length (length must be a multiple of 2)!",
						       io->u.sAMAccountName);
				return LDB_ERR_CONSTRAINT_VIOLATION;
			} else {
				/* passwords with length "0" are valid! */
				cleartext_utf8_blob->data = NULL;
				cleartext_utf8_blob->length = 0;
			}
		}
		g->cleartext_utf8 = cleartext_utf8_blob;
	}

	if (g->cleartext_utf16) {
		struct samr_Password *nt_hash;

		nt_hash = talloc(io->ac, struct samr_Password);
		if (!nt_hash) {
			return ldb_oom(ldb);
		}
		g->nt_hash = nt_hash;

		/* compute the new nt hash */
		mdfour(nt_hash->hash,
		       g->cleartext_utf16->data,
		       g->cleartext_utf16->length);
	}

	if (g->cleartext_utf8) {
		struct samr_Password *lm_hash;

		lm_hash = talloc(io->ac, struct samr_Password);
		if (!lm_hash) {
			return ldb_oom(ldb);
		}

		/* compute the new lm hash */
		ok = E_deshash((char *)g->cleartext_utf8->data, lm_hash->hash);
		if (ok) {
			g->lm_hash = lm_hash;
		} else {
			talloc_free(lm_hash);
		}
	}

	return LDB_SUCCESS;
}

static int setup_password_fields(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
	struct loadparm_context *lp_ctx =
		lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
					 struct loadparm_context);
	int ret;

	ret = setup_last_set_field(io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	if (!io->ac->update_password) {
		return LDB_SUCCESS;
	}

	/* transform the old password (for password changes) */
	ret = setup_given_passwords(io, &io->og);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	/* transform the new password */
	ret = setup_given_passwords(io, &io->n);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	if (io->n.cleartext_utf8) {
		ret = setup_kerberos_keys(io);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}

	ret = setup_nt_fields(io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	if (lpcfg_lanman_auth(lp_ctx)) {
		ret = setup_lm_fields(io);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	} else {
		io->g.lm_hash = NULL;
		io->g.lm_history_len = 0;
	}

	ret = setup_supplemental_field(io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	return LDB_SUCCESS;
}

static int setup_smartcard_reset(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
	struct loadparm_context *lp_ctx = talloc_get_type(
		ldb_get_opaque(ldb, "loadparm"), struct loadparm_context);
	struct supplementalCredentialsBlob scb = { .__ndr_size = 0 };
	enum ndr_err_code ndr_err;

	if (!io->ac->smartcard_reset) {
		return LDB_SUCCESS;
	}

	io->g.nt_hash = talloc(io->ac, struct samr_Password);
	if (io->g.nt_hash == NULL) {
		return ldb_module_oom(io->ac->module);
	}
	generate_secret_buffer(io->g.nt_hash->hash,
			       sizeof(io->g.nt_hash->hash));
	io->g.nt_history_len = 0;

	if (lpcfg_lanman_auth(lp_ctx)) {
		io->g.lm_hash = talloc(io->ac, struct samr_Password);
		if (io->g.lm_hash == NULL) {
			return ldb_module_oom(io->ac->module);
		}
		generate_secret_buffer(io->g.lm_hash->hash,
				       sizeof(io->g.lm_hash->hash));
	} else {
		io->g.lm_hash = NULL;
	}
	io->g.lm_history_len = 0;

	/*
	 * We take the "old" value and store it
	 * with num_packages = 0.
	 *
	 * On "add" we have scb.sub.signature == 0, which
	 * results in:
	 *
	 * [0000] 00 00 00 00 00 00 00 00   00 00 00 00 00
	 *
	 * On modify it's likely to be scb.sub.signature ==
	 * SUPPLEMENTAL_CREDENTIALS_SIGNATURE (0x0050), which results in
	 * something like:
	 *
	 * [0000] 00 00 00 00 62 00 00 00   00 00 00 00 20 00 20 00
	 * [0010] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
	 * [0020] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
	 * [0030] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
	 * [0040] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
	 * [0050] 20 00 20 00 20 00 20 00   20 00 20 00 20 00 20 00
	 * [0060] 20 00 20 00 20 00 20 00   20 00 20 00 50 00 00
	 *
	 * See https://bugzilla.samba.org/show_bug.cgi?id=11441
	 * and ndr_{push,pull}_supplementalCredentialsSubBlob().
	 */
	scb = io->o.scb;
	scb.sub.num_packages = 0;

	/*
	 * setup 'supplementalCredentials' value without packages
	 */
	ndr_err = ndr_push_struct_blob(&io->g.supplemental, io->ac,
				       &scb,
				       (ndr_push_flags_fn_t)ndr_push_supplementalCredentialsBlob);
	if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
		NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
		ldb_asprintf_errstring(ldb,
				       "setup_smartcard_reset: "
				       "failed to push supplementalCredentialsBlob: %s",
				       nt_errstr(status));
		return LDB_ERR_OPERATIONS_ERROR;
	}

	io->ac->update_password = true;
	return LDB_SUCCESS;
}

static int make_error_and_update_badPwdCount(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
	struct ldb_message *mod_msg = NULL;
	NTSTATUS status;
	int ret;

	status = dsdb_update_bad_pwd_count(io->ac, ldb,
					   io->ac->search_res->message,
					   io->ac->dom_res->message,
					   &mod_msg);
	if (!NT_STATUS_IS_OK(status)) {
		goto done;
	}

	if (mod_msg == NULL) {
		goto done;
	}

	/*
	 * OK, horrible semantics ahead.
	 *
	 * - We need to abort any existing transaction
	 * - create a transaction arround the badPwdCount update
	 * - re-open the transaction so the upper layer
	 *   doesn't know what happened.
	 *
	 * This is needed because returning an error to the upper
	 * layer will cancel the transaction and undo the badPwdCount
	 * update.
	 */

	/*
	 * Checking errors here is a bit pointless.
	 * What can we do if we can't end the transaction?
	 */
	ret = ldb_next_del_trans(io->ac->module);
	if (ret != LDB_SUCCESS) {
		ldb_debug(ldb, LDB_DEBUG_FATAL,
			  "Failed to abort transaction prior to update of badPwdCount of %s: %s",
			  ldb_dn_get_linearized(io->ac->search_res->message->dn),
			  ldb_errstring(ldb));
		/*
		 * just return the original error
		 */
		goto done;
	}

	/* Likewise, what should we do if we can't open a new transaction? */
	ret = ldb_next_start_trans(io->ac->module);
	if (ret != LDB_SUCCESS) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "Failed to open transaction to update badPwdCount of %s: %s",
			  ldb_dn_get_linearized(io->ac->search_res->message->dn),
			  ldb_errstring(ldb));
		/*
		 * just return the original error
		 */
		goto done;
	}

	ret = dsdb_module_modify(io->ac->module, mod_msg,
				 DSDB_FLAG_NEXT_MODULE,
				 io->ac->req);
	if (ret != LDB_SUCCESS) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "Failed to update badPwdCount of %s: %s",
			  ldb_dn_get_linearized(io->ac->search_res->message->dn),
			  ldb_errstring(ldb));
		/*
		 * We can only ignore this...
		 */
	}

	ret = ldb_next_end_trans(io->ac->module);
	if (ret != LDB_SUCCESS) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "Failed to close transaction to update badPwdCount of %s: %s",
			  ldb_dn_get_linearized(io->ac->search_res->message->dn),
			  ldb_errstring(ldb));
		/*
		 * We can only ignore this...
		 */
	}

	ret = ldb_next_start_trans(io->ac->module);
	if (ret != LDB_SUCCESS) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "Failed to open transaction after update of badPwdCount of %s: %s",
			  ldb_dn_get_linearized(io->ac->search_res->message->dn),
			  ldb_errstring(ldb));
		/*
		 * We can only ignore this...
		 */
	}

done:
	ret = LDB_ERR_CONSTRAINT_VIOLATION;
	ldb_asprintf_errstring(ldb,
			       "%08X: %s - check_password_restrictions: "
			       "The old password specified doesn't match!",
			       W_ERROR_V(WERR_INVALID_PASSWORD),
			       ldb_strerror(ret));
	return ret;
}

static int check_password_restrictions(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
	int ret;
	struct loadparm_context *lp_ctx =
		lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
					 struct loadparm_context);

	if (!io->ac->update_password) {
		return LDB_SUCCESS;
	}

	/* First check the old password is correct, for password changes */
	if (!io->ac->pwd_reset) {
		bool nt_hash_checked = false;

		/* we need the old nt or lm hash given by the client */
		if (!io->og.nt_hash && !io->og.lm_hash) {
			ldb_asprintf_errstring(ldb,
				"check_password_restrictions: "
				"You need to provide the old password in order "
				"to change it!");
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}

		/* The password modify through the NT hash is encouraged and
		   has no problems at all */
		if (io->og.nt_hash) {
			if (!io->o.nt_hash || memcmp(io->og.nt_hash->hash, io->o.nt_hash->hash, 16) != 0) {
				return make_error_and_update_badPwdCount(io);
			}

			nt_hash_checked = true;
		}

		/* But it is also possible to change a password by the LM hash
		 * alone for compatibility reasons. This check is optional if
		 * the NT hash was already checked - otherwise it's mandatory.
		 * (as the SAMR operations request it). */
		if (io->og.lm_hash) {
			if ((!io->o.lm_hash && !nt_hash_checked)
			    || (io->o.lm_hash && memcmp(io->og.lm_hash->hash, io->o.lm_hash->hash, 16) != 0)) {
				return make_error_and_update_badPwdCount(io);
			}
		}
	}

	if (io->u.restrictions == 0) {
		/* FIXME: Is this right? */
		return LDB_SUCCESS;
	}

	/* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
	if ((io->u.pwdLastSet - io->ac->status->domain_data.minPwdAge > io->g.last_set) &&
	    !io->ac->pwd_reset)
	{
		ret = LDB_ERR_CONSTRAINT_VIOLATION;
		ldb_asprintf_errstring(ldb,
			"%08X: %s - check_password_restrictions: "
			"password is too young to change!",
			W_ERROR_V(WERR_PASSWORD_RESTRICTION),
			ldb_strerror(ret));
		return ret;
	}

	/*
	 * Fundamental password checks done by the call
	 * "samdb_check_password".
	 * It is also in use by "dcesrv_samr_ValidatePassword".
	 */
	if (io->n.cleartext_utf8 != NULL) {
		enum samr_ValidationStatus vstat;
		vstat = samdb_check_password(io->ac, lp_ctx,
					     io->n.cleartext_utf8,
					     io->ac->status->domain_data.pwdProperties,
					     io->ac->status->domain_data.minPwdLength);
		switch (vstat) {
		case SAMR_VALIDATION_STATUS_SUCCESS:
				/* perfect -> proceed! */
			break;

		case SAMR_VALIDATION_STATUS_PWD_TOO_SHORT:
			ret = LDB_ERR_CONSTRAINT_VIOLATION;
			ldb_asprintf_errstring(ldb,
				"%08X: %s - check_password_restrictions: "
				"the password is too short. It should be equal or longer than %u characters!",
				W_ERROR_V(WERR_PASSWORD_RESTRICTION),
				ldb_strerror(ret),
				io->ac->status->domain_data.minPwdLength);
			io->ac->status->reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
			return ret;

		case SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH:
			ret = LDB_ERR_CONSTRAINT_VIOLATION;
			ldb_asprintf_errstring(ldb,
				"%08X: %s - check_password_restrictions: "
				"the password does not meet the complexity criteria!",
				W_ERROR_V(WERR_PASSWORD_RESTRICTION),
				ldb_strerror(ret));
			io->ac->status->reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
			return ret;

		default:
			ret = LDB_ERR_CONSTRAINT_VIOLATION;
			ldb_asprintf_errstring(ldb,
				"%08X: %s - check_password_restrictions: "
				"the password doesn't fit due to a miscellaneous restriction!",
				W_ERROR_V(WERR_PASSWORD_RESTRICTION),
				ldb_strerror(ret));
			return ret;
		}
	}

	if (io->ac->pwd_reset) {
		return LDB_SUCCESS;
	}

	if (io->n.nt_hash) {
		uint32_t i;

		/* checks the NT hash password history */
		for (i = 0; i < io->o.nt_history_len; i++) {
			ret = memcmp(io->n.nt_hash, io->o.nt_history[i].hash, 16);
			if (ret == 0) {
				ret = LDB_ERR_CONSTRAINT_VIOLATION;
				ldb_asprintf_errstring(ldb,
					"%08X: %s - check_password_restrictions: "
					"the password was already used (in history)!",
					W_ERROR_V(WERR_PASSWORD_RESTRICTION),
					ldb_strerror(ret));
				io->ac->status->reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
				return ret;
			}
		}
	}

	if (io->n.lm_hash) {
		uint32_t i;

		/* checks the LM hash password history */
		for (i = 0; i < io->o.lm_history_len; i++) {
			ret = memcmp(io->n.lm_hash, io->o.lm_history[i].hash, 16);
			if (ret == 0) {
				ret = LDB_ERR_CONSTRAINT_VIOLATION;
				ldb_asprintf_errstring(ldb,
					"%08X: %s - check_password_restrictions: "
					"the password was already used (in history)!",
					W_ERROR_V(WERR_PASSWORD_RESTRICTION),
					ldb_strerror(ret));
				io->ac->status->reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
				return ret;
			}
		}
	}

	/* are all password changes disallowed? */
	if (io->ac->status->domain_data.pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) {
		ret = LDB_ERR_CONSTRAINT_VIOLATION;
		ldb_asprintf_errstring(ldb,
			"%08X: %s - check_password_restrictions: "
			"password changes disabled!",
			W_ERROR_V(WERR_PASSWORD_RESTRICTION),
			ldb_strerror(ret));
		return ret;
	}

	/* can this user change the password? */
	if (io->u.userAccountControl & UF_PASSWD_CANT_CHANGE) {
		ret = LDB_ERR_CONSTRAINT_VIOLATION;
		ldb_asprintf_errstring(ldb,
			"%08X: %s - check_password_restrictions: "
			"password can't be changed on this account!",
			W_ERROR_V(WERR_PASSWORD_RESTRICTION),
			ldb_strerror(ret));
		return ret;
	}

	return LDB_SUCCESS;
}

static int update_final_msg(struct setup_password_fields_io *io)
{
	struct ldb_context *ldb = ldb_module_get_ctx(io->ac->module);
	int ret;
	int el_flags = 0;
	bool update_password = io->ac->update_password;
	bool update_scb = io->ac->update_password;

	/*
	 * If we add a user without initial password,
	 * we need to add replication meta data for
	 * following attributes:
	 * - unicodePwd
	 * - dBCSPwd
	 * - ntPwdHistory
	 * - lmPwdHistory
	 *
	 * If we add a user with initial password or a
	 * password is changed of an existing user,
	 * we need to replace the following attributes
	 * with a forced meta data update, e.g. also
	 * when updating an empty attribute with an empty value:
	 * - unicodePwd
	 * - dBCSPwd
	 * - ntPwdHistory
	 * - lmPwdHistory
	 * - supplementalCredentials
	 */

	switch (io->ac->req->operation) {
	case LDB_ADD:
		update_password = true;
		el_flags |= DSDB_FLAG_INTERNAL_FORCE_META_DATA;
		break;
	case LDB_MODIFY:
		el_flags |= LDB_FLAG_MOD_REPLACE;
		el_flags |= DSDB_FLAG_INTERNAL_FORCE_META_DATA;
		break;
	default:
		return ldb_module_operr(io->ac->module);
	}

	if (update_password) {
		ret = ldb_msg_add_empty(io->ac->update_msg,
					"unicodePwd",
					el_flags, NULL);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
		ret = ldb_msg_add_empty(io->ac->update_msg,
					"dBCSPwd",
					el_flags, NULL);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
		ret = ldb_msg_add_empty(io->ac->update_msg,
					"ntPwdHistory",
					el_flags, NULL);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
		ret = ldb_msg_add_empty(io->ac->update_msg,
					"lmPwdHistory",
					el_flags, NULL);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}
	if (update_scb) {
		ret = ldb_msg_add_empty(io->ac->update_msg,
					"supplementalCredentials",
					el_flags, NULL);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}
	if (io->ac->update_lastset) {
		ret = ldb_msg_add_empty(io->ac->update_msg,
					"pwdLastSet",
					el_flags, NULL);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}

	if (io->g.nt_hash != NULL) {
		ret = samdb_msg_add_hash(ldb, io->ac,
					 io->ac->update_msg,
					 "unicodePwd",
					 io->g.nt_hash);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}
	if (io->g.lm_hash != NULL) {
		ret = samdb_msg_add_hash(ldb, io->ac,
					 io->ac->update_msg,
					 "dBCSPwd",
					 io->g.lm_hash);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}
	if (io->g.nt_history_len > 0) {
		ret = samdb_msg_add_hashes(ldb, io->ac,
					   io->ac->update_msg,
					   "ntPwdHistory",
					   io->g.nt_history,
					   io->g.nt_history_len);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}
	if (io->g.lm_history_len > 0) {
		ret = samdb_msg_add_hashes(ldb, io->ac,
					   io->ac->update_msg,
					   "lmPwdHistory",
					   io->g.lm_history,
					   io->g.lm_history_len);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}
	if (io->g.supplemental.length > 0) {
		ret = ldb_msg_add_value(io->ac->update_msg,
					"supplementalCredentials",
					&io->g.supplemental, NULL);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}
	if (io->ac->update_lastset) {
		ret = samdb_msg_add_uint64(ldb, io->ac,
					   io->ac->update_msg,
					   "pwdLastSet",
					   io->g.last_set);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}

	return LDB_SUCCESS;
}

/*
 * This is intended for use by the "password_hash" module since there
 * password changes can be specified through one message element with the
 * new password (to set) and another one with the old password (to unset).
 *
 * The first which sets a password (new value) can have flags
 * (LDB_FLAG_MOD_ADD, LDB_FLAG_MOD_REPLACE) but also none (on "add" operations
 * for entries). The latter (old value) has always specified
 * LDB_FLAG_MOD_DELETE.
 *
 * Returns LDB_ERR_CONSTRAINT_VIOLATION and LDB_ERR_UNWILLING_TO_PERFORM if
 * matching message elements are malformed in respect to the set/change rules.
 * Otherwise it returns LDB_SUCCESS.
 */
static int msg_find_old_and_new_pwd_val(const struct ldb_message *msg,
					const char *name,
					enum ldb_request_type operation,
					const struct ldb_val **new_val,
					const struct ldb_val **old_val)
{
	unsigned int i;

	*new_val = NULL;
	*old_val = NULL;

	if (msg == NULL) {
		return LDB_SUCCESS;
	}

	for (i = 0; i < msg->num_elements; i++) {
		if (ldb_attr_cmp(msg->elements[i].name, name) != 0) {
			continue;
		}

		if ((operation == LDB_MODIFY) &&
		    (LDB_FLAG_MOD_TYPE(msg->elements[i].flags) == LDB_FLAG_MOD_DELETE)) {
			/* 0 values are allowed */
			if (msg->elements[i].num_values == 1) {
				*old_val = &msg->elements[i].values[0];
			} else if (msg->elements[i].num_values > 1) {
				return LDB_ERR_CONSTRAINT_VIOLATION;
			}
		} else if ((operation == LDB_MODIFY) &&
			   (LDB_FLAG_MOD_TYPE(msg->elements[i].flags) == LDB_FLAG_MOD_REPLACE)) {
			if (msg->elements[i].num_values > 0) {
				*new_val = &msg->elements[i].values[msg->elements[i].num_values - 1];
			} else {
				return LDB_ERR_UNWILLING_TO_PERFORM;
			}
		} else {
			/* Add operations and LDB_FLAG_MOD_ADD */
			if (msg->elements[i].num_values > 0) {
				*new_val = &msg->elements[i].values[msg->elements[i].num_values - 1];
			} else {
				return LDB_ERR_CONSTRAINT_VIOLATION;
			}
		}
	}

	return LDB_SUCCESS;
}

static int setup_io(struct ph_context *ac, 
		    const struct ldb_message *client_msg,
		    const struct ldb_message *existing_msg,
		    struct setup_password_fields_io *io) 
{ 
	const struct ldb_val *quoted_utf16, *old_quoted_utf16, *lm_hash, *old_lm_hash;
	struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
	struct loadparm_context *lp_ctx = talloc_get_type(
		ldb_get_opaque(ldb, "loadparm"), struct loadparm_context);
	int ret;
	const struct ldb_message *info_msg = NULL;
	struct dom_sid *account_sid = NULL;
	int rodc_krbtgt = 0;

	ZERO_STRUCTP(io);

	/* Some operations below require kerberos contexts */

	if (existing_msg != NULL) {
		/*
		 * This is a modify operation
		 */
		info_msg = existing_msg;
	} else {
		/*
		 * This is an add operation
		 */
		info_msg = client_msg;
	}

	if (smb_krb5_init_context(ac,
				  (struct loadparm_context *)ldb_get_opaque(ldb, "loadparm"),
				  &io->smb_krb5_context) != 0) {
		return ldb_operr(ldb);
	}

	io->ac				= ac;

	io->u.userAccountControl	= ldb_msg_find_attr_as_uint(info_msg,
								    "userAccountControl", 0);
	if (info_msg == existing_msg) {
		/*
		 * We only take pwdLastSet from the existing object
		 * otherwise we leave it as 0.
		 *
		 * If no attribute is available, e.g. on deleted objects
		 * we remember that as UINT64_MAX.
		 */
		io->u.pwdLastSet = samdb_result_nttime(info_msg, "pwdLastSet",
						       UINT64_MAX);
	}
	io->u.sAMAccountName		= ldb_msg_find_attr_as_string(info_msg,
								      "sAMAccountName", NULL);
	io->u.user_principal_name	= ldb_msg_find_attr_as_string(info_msg,
								      "userPrincipalName", NULL);
	io->u.is_computer		= ldb_msg_check_string_attribute(info_msg, "objectClass", "computer");

	/* Ensure it has an objectSID too */
	account_sid = samdb_result_dom_sid(ac, info_msg, "objectSid");
	if (account_sid != NULL) {
		NTSTATUS status;
		uint32_t rid = 0;

		status = dom_sid_split_rid(account_sid, account_sid, NULL, &rid);
		if (NT_STATUS_IS_OK(status)) {
			if (rid == DOMAIN_RID_KRBTGT) {
				io->u.is_krbtgt = true;
			}
		}
	}

	rodc_krbtgt = ldb_msg_find_attr_as_int(info_msg,
			"msDS-SecondaryKrbTgtNumber", 0);
	if (rodc_krbtgt != 0) {
		io->u.is_krbtgt = true;
	}

	if (io->u.sAMAccountName == NULL) {
		ldb_asprintf_errstring(ldb,
				       "setup_io: sAMAccountName attribute is missing on %s for attempted password set/change",
				       ldb_dn_get_linearized(info_msg->dn));

		return LDB_ERR_CONSTRAINT_VIOLATION;
	}

	if (io->u.userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
		struct ldb_control *permit_trust = ldb_request_get_control(ac->req,
				DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID);

		if (permit_trust == NULL) {
			ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
			ldb_asprintf_errstring(ldb,
				"%08X: %s - setup_io: changing the interdomain trust password "
				"on %s not allowed via LDAP. Use LSA or NETLOGON",
				W_ERROR_V(WERR_ACCESS_DENIED),
				ldb_strerror(ret),
				ldb_dn_get_linearized(info_msg->dn));
			return ret;
		}
	}

	/* Only non-trust accounts have restrictions (possibly this test is the
	 * wrong way around, but we like to be restrictive if possible */
	io->u.restrictions = !(io->u.userAccountControl
		& (UF_INTERDOMAIN_TRUST_ACCOUNT | UF_WORKSTATION_TRUST_ACCOUNT
			| UF_SERVER_TRUST_ACCOUNT));

	if (io->u.is_krbtgt) {
		io->u.restrictions = 0;
		io->ac->status->domain_data.pwdHistoryLength =
			MAX(io->ac->status->domain_data.pwdHistoryLength, 3);
	}

	if (ac->userPassword) {
		ret = msg_find_old_and_new_pwd_val(client_msg, "userPassword",
						   ac->req->operation,
						   &io->n.cleartext_utf8,
						   &io->og.cleartext_utf8);
		if (ret != LDB_SUCCESS) {
			ldb_asprintf_errstring(ldb,
				"setup_io: "
				"it's only allowed to set the old password once!");
			return ret;
		}
	}

	if (io->n.cleartext_utf8 != NULL) {
		struct ldb_val *cleartext_utf8_blob;
		char *p;

		cleartext_utf8_blob = talloc(io->ac, struct ldb_val);
		if (!cleartext_utf8_blob) {
			return ldb_oom(ldb);
		}

		*cleartext_utf8_blob = *io->n.cleartext_utf8;

		/* make sure we have a null terminated string */
		p = talloc_strndup(cleartext_utf8_blob,
				   (const char *)io->n.cleartext_utf8->data,
				   io->n.cleartext_utf8->length);
		if ((p == NULL) && (io->n.cleartext_utf8->length > 0)) {
			return ldb_oom(ldb);
		}
		cleartext_utf8_blob->data = (uint8_t *)p;

		io->n.cleartext_utf8 = cleartext_utf8_blob;
	}

	ret = msg_find_old_and_new_pwd_val(client_msg, "clearTextPassword",
					   ac->req->operation,
					   &io->n.cleartext_utf16,
					   &io->og.cleartext_utf16);
	if (ret != LDB_SUCCESS) {
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"it's only allowed to set the old password once!");
		return ret;
	}

	/* this rather strange looking piece of code is there to
	   handle a ldap client setting a password remotely using the
	   unicodePwd ldap field. The syntax is that the password is
	   in UTF-16LE, with a " at either end. Unfortunately the
	   unicodePwd field is also used to store the nt hashes
	   internally in Samba, and is used in the nt hash format on
	   the wire in DRS replication, so we have a single name for
	   two distinct values. The code below leaves us with a small
	   chance (less than 1 in 2^32) of a mixup, if someone manages
	   to create a MD4 hash which starts and ends in 0x22 0x00, as
	   that would then be treated as a UTF16 password rather than
	   a nthash */

	ret = msg_find_old_and_new_pwd_val(client_msg, "unicodePwd",
					   ac->req->operation,
					   &quoted_utf16,
					   &old_quoted_utf16);
	if (ret != LDB_SUCCESS) {
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"it's only allowed to set the old password once!");
		return ret;
	}

	/* Checks and converts the actual "unicodePwd" attribute */
	if (!ac->hash_values &&
	    quoted_utf16 &&
	    quoted_utf16->length >= 4 &&
	    quoted_utf16->data[0] == '"' &&
	    quoted_utf16->data[1] == 0 &&
	    quoted_utf16->data[quoted_utf16->length-2] == '"' &&
	    quoted_utf16->data[quoted_utf16->length-1] == 0) {
		struct ldb_val *quoted_utf16_2;

		if (io->n.cleartext_utf16) {
			/* refuse the change if someone wants to change with
			   with both UTF16 possibilities at the same time... */
			ldb_asprintf_errstring(ldb,
				"setup_io: "
				"it's only allowed to set the cleartext password as 'unicodePwd' or as 'clearTextPassword'");
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}

		/*
		 * adapt the quoted UTF16 string to be a real
		 * cleartext one
		 */
		quoted_utf16_2 = talloc(io->ac, struct ldb_val);
		if (quoted_utf16_2 == NULL) {
			return ldb_oom(ldb);
		}

		quoted_utf16_2->data = quoted_utf16->data + 2;
		quoted_utf16_2->length = quoted_utf16->length-4;
		io->n.cleartext_utf16 = quoted_utf16_2;
		io->n.nt_hash = NULL;

	} else if (quoted_utf16) {
		/* We have only the hash available -> so no plaintext here */
		if (!ac->hash_values) {
			/* refuse the change if someone wants to change
			   the hash without control specified... */
			ldb_asprintf_errstring(ldb,
				"setup_io: "
				"it's not allowed to set the NT hash password directly'");
			/* this looks odd but this is what Windows does:
			   returns "UNWILLING_TO_PERFORM" on wrong
			   password sets and "CONSTRAINT_VIOLATION" on
			   wrong password changes. */
			if (old_quoted_utf16 == NULL) {
				return LDB_ERR_UNWILLING_TO_PERFORM;
			}

			return LDB_ERR_CONSTRAINT_VIOLATION;
		}

		io->n.nt_hash = talloc(io->ac, struct samr_Password);
		memcpy(io->n.nt_hash->hash, quoted_utf16->data,
		       MIN(quoted_utf16->length, sizeof(io->n.nt_hash->hash)));
	}

	/* Checks and converts the previous "unicodePwd" attribute */
	if (!ac->hash_values &&
	    old_quoted_utf16 &&
	    old_quoted_utf16->length >= 4 &&
	    old_quoted_utf16->data[0] == '"' &&
	    old_quoted_utf16->data[1] == 0 &&
	    old_quoted_utf16->data[old_quoted_utf16->length-2] == '"' &&
	    old_quoted_utf16->data[old_quoted_utf16->length-1] == 0) {
		struct ldb_val *old_quoted_utf16_2;

		if (io->og.cleartext_utf16) {
			/* refuse the change if someone wants to change with
			   both UTF16 possibilities at the same time... */
			ldb_asprintf_errstring(ldb,
				"setup_io: "
				"it's only allowed to set the cleartext password as 'unicodePwd' or as 'clearTextPassword'");
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}

		/*
		 * adapt the quoted UTF16 string to be a real
		 * cleartext one
		 */
		old_quoted_utf16_2 = talloc(io->ac, struct ldb_val);
		if (old_quoted_utf16_2 == NULL) {
			return ldb_oom(ldb);
		}

		old_quoted_utf16_2->data = old_quoted_utf16->data + 2;
		old_quoted_utf16_2->length = old_quoted_utf16->length-4;

		io->og.cleartext_utf16 = old_quoted_utf16_2;
		io->og.nt_hash = NULL;
	} else if (old_quoted_utf16) {
		/* We have only the hash available -> so no plaintext here */
		if (!ac->hash_values) {
			/* refuse the change if someone wants to change
			   the hash without control specified... */
			ldb_asprintf_errstring(ldb,
				"setup_io: "
				"it's not allowed to set the NT hash password directly'");
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}

		io->og.nt_hash = talloc(io->ac, struct samr_Password);
		memcpy(io->og.nt_hash->hash, old_quoted_utf16->data,
		       MIN(old_quoted_utf16->length, sizeof(io->og.nt_hash->hash)));
	}

	/* Handles the "dBCSPwd" attribute (LM hash) */
	io->n.lm_hash = NULL; io->og.lm_hash = NULL;
	ret = msg_find_old_and_new_pwd_val(client_msg, "dBCSPwd",
					   ac->req->operation,
					   &lm_hash, &old_lm_hash);
	if (ret != LDB_SUCCESS) {
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"it's only allowed to set the old password once!");
		return ret;
	}

	if (((lm_hash != NULL) || (old_lm_hash != NULL)) && (!ac->hash_values)) {
		/* refuse the change if someone wants to change the hash
		   without control specified... */
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"it's not allowed to set the LM hash password directly'");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	if (lpcfg_lanman_auth(lp_ctx) && (lm_hash != NULL)) {
		io->n.lm_hash = talloc(io->ac, struct samr_Password);
		memcpy(io->n.lm_hash->hash, lm_hash->data, MIN(lm_hash->length,
		       sizeof(io->n.lm_hash->hash)));
	}
	if (lpcfg_lanman_auth(lp_ctx) && (old_lm_hash != NULL)) {
		io->og.lm_hash = talloc(io->ac, struct samr_Password);
		memcpy(io->og.lm_hash->hash, old_lm_hash->data, MIN(old_lm_hash->length,
		       sizeof(io->og.lm_hash->hash)));
	}

	/*
	 * Handles the password change control if it's specified. It has the
	 * precedance and overrides already specified old password values of
	 * change requests (but that shouldn't happen since the control is
	 * fully internal and only used in conjunction with replace requests!).
	 */
	if (ac->change != NULL) {
		io->og.nt_hash = NULL;
		if (ac->change->old_nt_pwd_hash != NULL) {
			io->og.nt_hash = talloc_memdup(io->ac,
						       ac->change->old_nt_pwd_hash,
						       sizeof(struct samr_Password));
		}
		io->og.lm_hash = NULL;
		if (lpcfg_lanman_auth(lp_ctx) && (ac->change->old_lm_pwd_hash != NULL)) {
			io->og.lm_hash = talloc_memdup(io->ac,
						       ac->change->old_lm_pwd_hash,
						       sizeof(struct samr_Password));
		}
	}

	/* refuse the change if someone wants to change the clear-
	   text and supply his own hashes at the same time... */
	if ((io->n.cleartext_utf8 || io->n.cleartext_utf16)
			&& (io->n.nt_hash || io->n.lm_hash)) {
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"it's only allowed to set the password in form of cleartext attributes or as hashes");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* refuse the change if someone wants to change the password
	   using both plaintext methods (UTF8 and UTF16) at the same time... */
	if (io->n.cleartext_utf8 && io->n.cleartext_utf16) {
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"it's only allowed to set the cleartext password as 'unicodePwd' or as 'userPassword' or as 'clearTextPassword'");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* refuse the change if someone tries to set/change the password by
	 * the lanman hash alone and we've deactivated that mechanism. This
	 * would end in an account without any password! */
	if (io->ac->update_password
	    && (!io->n.cleartext_utf8) && (!io->n.cleartext_utf16)
	    && (!io->n.nt_hash) && (!io->n.lm_hash)) {
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"It's not possible to delete the password (changes using the LAN Manager hash alone could be deactivated)!");
		/* on "userPassword" and "clearTextPassword" we've to return
		 * something different, since these are virtual attributes */
		if ((ldb_msg_find_element(client_msg, "userPassword") != NULL) ||
		    (ldb_msg_find_element(client_msg, "clearTextPassword") != NULL)) {
			return LDB_ERR_CONSTRAINT_VIOLATION;
		}
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* refuse the change if someone wants to compare against a plaintext
	   or hash at the same time for a "password modify" operation... */
	if ((io->og.cleartext_utf8 || io->og.cleartext_utf16)
	    && (io->og.nt_hash || io->og.lm_hash)) {
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"it's only allowed to provide the old password in form of cleartext attributes or as hashes");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* refuse the change if someone wants to compare against both
	 * plaintexts at the same time for a "password modify" operation... */
	if (io->og.cleartext_utf8 && io->og.cleartext_utf16) {
		ldb_asprintf_errstring(ldb,
			"setup_io: "
			"it's only allowed to provide the old cleartext password as 'unicodePwd' or as 'userPassword' or as 'clearTextPassword'");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* Decides if we have a password modify or password reset operation */
	if (ac->req->operation == LDB_ADD) {
		/* On "add" we have only "password reset" */
		ac->pwd_reset = true;
	} else if (ac->req->operation == LDB_MODIFY) {
		if (io->og.cleartext_utf8 || io->og.cleartext_utf16
		    || io->og.nt_hash || io->og.lm_hash) {
			/* If we have an old password specified then for sure it
			 * is a user "password change" */
			ac->pwd_reset = false;
		} else {
			/* Otherwise we have also here a "password reset" */
			ac->pwd_reset = true;
		}
	} else {
		/* this shouldn't happen */
		return ldb_operr(ldb);
	}

	if (io->u.is_krbtgt) {
		size_t min = 196;
		size_t max = 255;
		size_t diff = max - min;
		size_t len = max;
		struct ldb_val *krbtgt_utf16 = NULL;

		if (!ac->pwd_reset) {
			return dsdb_module_werror(ac->module,
					LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS,
					WERR_DS_ATT_ALREADY_EXISTS,
					"Password change on krbtgt not permitted!");
		}

		if (io->n.cleartext_utf16 == NULL) {
			return dsdb_module_werror(ac->module,
					LDB_ERR_UNWILLING_TO_PERFORM,
					WERR_DS_INVALID_ATTRIBUTE_SYNTAX,
					"Password reset on krbtgt requires UTF16!");
		}

		/*
		 * Instead of taking the callers value,
		 * we just generate a new random value here.
		 *
		 * Include null termination in the array.
		 */
		if (diff > 0) {
			size_t tmp;

			generate_random_buffer((uint8_t *)&tmp, sizeof(tmp));

			tmp %= diff;

			len = min + tmp;
		}

		krbtgt_utf16 = talloc_zero(io->ac, struct ldb_val);
		if (krbtgt_utf16 == NULL) {
			return ldb_oom(ldb);
		}

		*krbtgt_utf16 = data_blob_talloc_zero(krbtgt_utf16,
						      (len+1)*2);
		if (krbtgt_utf16->data == NULL) {
			return ldb_oom(ldb);
		}
		krbtgt_utf16->length = len * 2;
		generate_secret_buffer(krbtgt_utf16->data,
				       krbtgt_utf16->length);
		io->n.cleartext_utf16 = krbtgt_utf16;
	}

	if (existing_msg != NULL) {
		NTSTATUS status;

		if (ac->pwd_reset) {
			/* Get the old password from the database */
			status = samdb_result_passwords_no_lockout(ac,
								   lp_ctx,
								   existing_msg,
								   &io->o.lm_hash,
								   &io->o.nt_hash);
		} else {
			/* Get the old password from the database */
			status = samdb_result_passwords(ac,
							lp_ctx,
							existing_msg,
							&io->o.lm_hash,
							&io->o.nt_hash);
		}

		if (NT_STATUS_EQUAL(status, NT_STATUS_ACCOUNT_LOCKED_OUT)) {
			return dsdb_module_werror(ac->module,
						  LDB_ERR_CONSTRAINT_VIOLATION,
						  WERR_ACCOUNT_LOCKED_OUT,
						  "Password change not permitted,"
						  " account locked out!");
		}

		if (!NT_STATUS_IS_OK(status)) {
			/*
			 * This only happens if the database has gone weird,
			 * not if we are just missing the passwords
			 */
			return ldb_operr(ldb);
		}

		io->o.nt_history_len = samdb_result_hashes(ac, existing_msg,
							   "ntPwdHistory",
							   &io->o.nt_history);
		io->o.lm_history_len = samdb_result_hashes(ac, existing_msg,
							   "lmPwdHistory",
							   &io->o.lm_history);
		io->o.supplemental = ldb_msg_find_ldb_val(existing_msg,
							  "supplementalCredentials");

		if (io->o.supplemental != NULL) {
			enum ndr_err_code ndr_err;

			ndr_err = ndr_pull_struct_blob_all(io->o.supplemental, io->ac,
					&io->o.scb,
					(ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
			if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
				status = ndr_map_error2ntstatus(ndr_err);
				ldb_asprintf_errstring(ldb,
						"setup_io: failed to pull "
						"old supplementalCredentialsBlob: %s",
						nt_errstr(status));
				return LDB_ERR_OPERATIONS_ERROR;
			}
		}
	}

	return LDB_SUCCESS;
}

static struct ph_context *ph_init_context(struct ldb_module *module,
					  struct ldb_request *req,
					  bool userPassword,
					  bool update_password)
{
	struct ldb_context *ldb;
	struct ph_context *ac;
	struct loadparm_context *lp_ctx = NULL;

	ldb = ldb_module_get_ctx(module);

	ac = talloc_zero(req, struct ph_context);
	if (ac == NULL) {
		ldb_set_errstring(ldb, "Out of Memory");
		return NULL;
	}

	ac->module = module;
	ac->req = req;
	ac->userPassword = userPassword;
	ac->update_password = update_password;
	ac->update_lastset = true;

	lp_ctx = talloc_get_type_abort(ldb_get_opaque(ldb, "loadparm"),
				       struct loadparm_context);
	ac->gpg_key_ids = lpcfg_password_hash_gpg_key_ids(lp_ctx);

	return ac;
}

static void ph_apply_controls(struct ph_context *ac)
{
	struct ldb_control *ctrl;

	ac->change_status = false;
	ctrl = ldb_request_get_control(ac->req,
				       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID);
	if (ctrl != NULL) {
		ac->change_status = true;

		/* Mark the "change status" control as uncritical (done) */
		ctrl->critical = false;
	}

	ac->hash_values = false;
	ctrl = ldb_request_get_control(ac->req,
				       DSDB_CONTROL_PASSWORD_HASH_VALUES_OID);
	if (ctrl != NULL) {
		ac->hash_values = true;

		/* Mark the "hash values" control as uncritical (done) */
		ctrl->critical = false;
	}

	ctrl = ldb_request_get_control(ac->req,
				       DSDB_CONTROL_PASSWORD_CHANGE_OID);
	if (ctrl != NULL) {
		ac->change = (struct dsdb_control_password_change *) ctrl->data;

		/* Mark the "change" control as uncritical (done) */
		ctrl->critical = false;
	}

	ac->pwd_last_set_bypass = false;
	ctrl = ldb_request_get_control(ac->req,
				DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID);
	if (ctrl != NULL) {
		ac->pwd_last_set_bypass = true;

		/* Mark the "bypass pwdLastSet" control as uncritical (done) */
		ctrl->critical = false;
	}

	ac->pwd_last_set_default = false;
	ctrl = ldb_request_get_control(ac->req,
				DSDB_CONTROL_PASSWORD_DEFAULT_LAST_SET_OID);
	if (ctrl != NULL) {
		ac->pwd_last_set_default = true;

		/* Mark the "bypass pwdLastSet" control as uncritical (done) */
		ctrl->critical = false;
	}

	ac->smartcard_reset = false;
	ctrl = ldb_request_get_control(ac->req,
				DSDB_CONTROL_PASSWORD_USER_ACCOUNT_CONTROL_OID);
	if (ctrl != NULL) {
		struct dsdb_control_password_user_account_control *uac = NULL;
		uint32_t added_flags = 0;

		uac = talloc_get_type_abort(ctrl->data,
			struct dsdb_control_password_user_account_control);

		added_flags = uac->new_flags & ~uac->old_flags;

		if (added_flags & UF_SMARTCARD_REQUIRED) {
			ac->smartcard_reset = true;
		}

		/* Mark the "smartcard required" control as uncritical (done) */
		ctrl->critical = false;
	}
}

static int ph_op_callback(struct ldb_request *req, struct ldb_reply *ares)
{
	struct ph_context *ac;

	ac = talloc_get_type(req->context, struct ph_context);

	if (!ares) {
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}

	if (ares->type == LDB_REPLY_REFERRAL) {
		return ldb_module_send_referral(ac->req, ares->referral);
	}

	if ((ares->error != LDB_ERR_OPERATIONS_ERROR) && (ac->change_status)) {
		/* On success and trivial errors a status control is being
		 * added (used for example by the "samdb_set_password" call) */
		ldb_reply_add_control(ares,
				      DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
				      false,
				      ac->status);
	}

	if (ares->error != LDB_SUCCESS) {
		return ldb_module_done(ac->req, ares->controls,
					ares->response, ares->error);
	}

	if (ares->type != LDB_REPLY_DONE) {
		talloc_free(ares);
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}

	return ldb_module_done(ac->req, ares->controls,
				ares->response, ares->error);
}

static int password_hash_add_do_add(struct ph_context *ac);
static int ph_modify_callback(struct ldb_request *req, struct ldb_reply *ares);
static int password_hash_mod_search_self(struct ph_context *ac);
static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares);
static int password_hash_mod_do_mod(struct ph_context *ac);

static int get_domain_data_callback(struct ldb_request *req,
				    struct ldb_reply *ares)
{
	struct ldb_context *ldb;
	struct ph_context *ac;
	struct loadparm_context *lp_ctx;
	int ret = LDB_SUCCESS;

	ac = talloc_get_type(req->context, struct ph_context);
	ldb = ldb_module_get_ctx(ac->module);

	if (!ares) {
		ret = LDB_ERR_OPERATIONS_ERROR;
		goto done;
	}
	if (ares->error != LDB_SUCCESS) {
		return ldb_module_done(ac->req, ares->controls,
					ares->response, ares->error);
	}

	switch (ares->type) {
	case LDB_REPLY_ENTRY:
		if (ac->status != NULL) {
			talloc_free(ares);

			ldb_set_errstring(ldb, "Too many results");
			ret = LDB_ERR_OPERATIONS_ERROR;
			goto done;
		}

		/* Setup the "status" structure (used as control later) */
		ac->status = talloc_zero(ac->req,
					 struct dsdb_control_password_change_status);
		if (ac->status == NULL) {
			talloc_free(ares);

			ldb_oom(ldb);
			ret = LDB_ERR_OPERATIONS_ERROR;
			goto done;
		}

		/* Setup the "domain data" structure */
		ac->status->domain_data.pwdProperties =
			ldb_msg_find_attr_as_uint(ares->message, "pwdProperties", -1);
		ac->status->domain_data.pwdHistoryLength =
			ldb_msg_find_attr_as_uint(ares->message, "pwdHistoryLength", -1);
		ac->status->domain_data.maxPwdAge =
			ldb_msg_find_attr_as_int64(ares->message, "maxPwdAge", -1);
		ac->status->domain_data.minPwdAge =
			ldb_msg_find_attr_as_int64(ares->message, "minPwdAge", -1);
		ac->status->domain_data.minPwdLength =
			ldb_msg_find_attr_as_uint(ares->message, "minPwdLength", -1);
		ac->status->domain_data.store_cleartext =
			ac->status->domain_data.pwdProperties & DOMAIN_PASSWORD_STORE_CLEARTEXT;

		/* For a domain DN, this puts things in dotted notation */
		/* For builtin domains, this will give details for the host,
		 * but that doesn't really matter, as it's just used for salt
		 * and kerberos principals, which don't exist here */

		lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
					 struct loadparm_context);

		ac->status->domain_data.dns_domain = lpcfg_dnsdomain(lp_ctx);
		ac->status->domain_data.realm = lpcfg_realm(lp_ctx);
		ac->status->domain_data.netbios_domain = lpcfg_sam_name(lp_ctx);

		ac->status->reject_reason = SAM_PWD_CHANGE_NO_ERROR;

		if (ac->dom_res != NULL) {
			talloc_free(ares);

			ldb_set_errstring(ldb, "Too many results");
			ret = LDB_ERR_OPERATIONS_ERROR;
			goto done;
		}

		ac->dom_res = talloc_steal(ac, ares);
		ret = LDB_SUCCESS;
		break;

	case LDB_REPLY_REFERRAL:
		/* ignore */
		talloc_free(ares);
		ret = LDB_SUCCESS;
		break;

	case LDB_REPLY_DONE:
		talloc_free(ares);
		/* call the next step */
		switch (ac->req->operation) {
		case LDB_ADD:
			ret = password_hash_add_do_add(ac);
			break;

		case LDB_MODIFY:
			ret = password_hash_mod_do_mod(ac);
			break;

		default:
			ret = LDB_ERR_OPERATIONS_ERROR;
			break;
		}
		break;
	}

done:
	if (ret != LDB_SUCCESS) {
		struct ldb_reply *new_ares;

		new_ares = talloc_zero(ac->req, struct ldb_reply);
		if (new_ares == NULL) {
			ldb_oom(ldb);
			return ldb_module_done(ac->req, NULL, NULL,
					       LDB_ERR_OPERATIONS_ERROR);
		}

		new_ares->error = ret;
		if ((ret != LDB_ERR_OPERATIONS_ERROR) && (ac->change_status)) {
			/* On success and trivial errors a status control is being
			 * added (used for example by the "samdb_set_password" call) */
			ldb_reply_add_control(new_ares,
					      DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
					      false,
					      ac->status);
		}

		return ldb_module_done(ac->req, new_ares->controls,
				       new_ares->response, new_ares->error);
	}

	return LDB_SUCCESS;
}

static int build_domain_data_request(struct ph_context *ac)
{
	/* attrs[] is returned from this function in
	   ac->dom_req->op.search.attrs, so it must be static, as
	   otherwise the compiler can put it on the stack */
	struct ldb_context *ldb;
	static const char * const attrs[] = { "pwdProperties",
					      "pwdHistoryLength",
					      "maxPwdAge",
					      "minPwdAge",
					      "minPwdLength",
					      "lockoutThreshold",
					      "lockOutObservationWindow",
					      NULL };
	int ret;

	ldb = ldb_module_get_ctx(ac->module);

	ret = ldb_build_search_req(&ac->dom_req, ldb, ac,
				   ldb_get_default_basedn(ldb),
				   LDB_SCOPE_BASE,
				   NULL, attrs,
				   NULL,
				   ac, get_domain_data_callback,
				   ac->req);
	LDB_REQ_SET_LOCATION(ac->dom_req);
	return ret;
}

static int password_hash_needed(struct ldb_module *module,
				struct ldb_request *req,
				struct ph_context **_ac)
{
	struct ldb_context *ldb = ldb_module_get_ctx(module);
	const char *operation = NULL;
	const struct ldb_message *msg = NULL;
	struct ph_context *ac = NULL;
	const char *passwordAttrs[] = {
		"userPassword",
		"clearTextPassword",
		"unicodePwd",
		"dBCSPwd",
		NULL
	};
	const char **a = NULL;
	unsigned int attr_cnt = 0;
	struct ldb_control *bypass = NULL;
	struct ldb_control *uac_ctrl = NULL;
	bool userPassword = dsdb_user_password_support(module, req, req);
	bool update_password = false;
	bool processing_needed = false;

	*_ac = NULL;

	ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_needed\n");

	switch (req->operation) {
	case LDB_ADD:
		operation = "add";
		msg = req->op.add.message;
		break;
	case LDB_MODIFY:
		operation = "modify";
		msg = req->op.mod.message;
		break;
	default:
		return ldb_next_request(module, req);
	}

	if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
		return ldb_next_request(module, req);
	}

	bypass = ldb_request_get_control(req,
					 DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID);
	if (bypass != NULL) {
		/* Mark the "bypass" control as uncritical (done) */
		bypass->critical = false;
		ldb_debug(ldb, LDB_DEBUG_TRACE,
			  "password_hash_needed(%s) (bypassing)\n",
			  operation);
		return password_hash_bypass(module, req);
	}

	/* nobody must touch password histories and 'supplementalCredentials' */
	if (ldb_msg_find_element(msg, "ntPwdHistory")) {
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}
	if (ldb_msg_find_element(msg, "lmPwdHistory")) {
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}
	if (ldb_msg_find_element(msg, "supplementalCredentials")) {
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/*
	 * If no part of this touches the 'userPassword' OR 'clearTextPassword'
	 * OR 'unicodePwd' OR 'dBCSPwd' we don't need to make any changes.
	 * For password changes/set there should be a 'delete' or a 'modify'
	 * on these attributes.
	 */
	for (a = passwordAttrs; *a != NULL; a++) {
		if ((!userPassword) && (ldb_attr_cmp(*a, "userPassword") == 0)) {
			continue;
		}

		if (ldb_msg_find_element(msg, *a) != NULL) {
			/* MS-ADTS 3.1.1.3.1.5.2 */
			if ((ldb_attr_cmp(*a, "userPassword") == 0) &&
			    (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003)) {
				return LDB_ERR_CONSTRAINT_VIOLATION;
			}

			++attr_cnt;
		}
	}

	if (attr_cnt > 0) {
		update_password = true;
		processing_needed = true;
	}

	if (ldb_msg_find_element(msg, "pwdLastSet")) {
		processing_needed = true;
	}

	uac_ctrl = ldb_request_get_control(req,
				DSDB_CONTROL_PASSWORD_USER_ACCOUNT_CONTROL_OID);
	if (uac_ctrl != NULL) {
		struct dsdb_control_password_user_account_control *uac = NULL;
		uint32_t added_flags = 0;

		uac = talloc_get_type_abort(uac_ctrl->data,
			struct dsdb_control_password_user_account_control);

		added_flags = uac->new_flags & ~uac->old_flags;

		if (added_flags & UF_SMARTCARD_REQUIRED) {
			processing_needed = true;
		}
	}

	if (!processing_needed) {
		return ldb_next_request(module, req);
	}

	ac = ph_init_context(module, req, userPassword, update_password);
	if (!ac) {
		DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb)));
		return ldb_operr(ldb);
	}
	ph_apply_controls(ac);

	/*
	 * Make a copy in order to apply our modifications
	 * to the final update
	 */
	ac->update_msg = ldb_msg_copy_shallow(ac, msg);
	if (ac->update_msg == NULL) {
		return ldb_oom(ldb);
	}

	/*
	 * Remove all password related attributes.
	 */
	if (ac->userPassword) {
		ldb_msg_remove_attr(ac->update_msg, "userPassword");
	}
	ldb_msg_remove_attr(ac->update_msg, "clearTextPassword");
	ldb_msg_remove_attr(ac->update_msg, "unicodePwd");
	ldb_msg_remove_attr(ac->update_msg, "ntPwdHistory");
	ldb_msg_remove_attr(ac->update_msg, "dBCSPwd");
	ldb_msg_remove_attr(ac->update_msg, "lmPwdHistory");
	ldb_msg_remove_attr(ac->update_msg, "supplementalCredentials");
	ldb_msg_remove_attr(ac->update_msg, "pwdLastSet");

	*_ac = ac;
	return LDB_SUCCESS;
}

static int password_hash_add(struct ldb_module *module, struct ldb_request *req)
{
	struct ldb_context *ldb = ldb_module_get_ctx(module);
	struct ph_context *ac = NULL;
	int ret;

	ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_add\n");

	ret = password_hash_needed(module, req, &ac);
	if (ret != LDB_SUCCESS) {
		return ret;
	}
	if (ac == NULL) {
		return ret;
	}

	/* Make sure we are performing the password set action on a (for us)
	 * valid object. Those are instances of either "user" and/or
	 * "inetOrgPerson". Otherwise continue with the submodules. */
	if ((!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "user"))
		&& (!ldb_msg_check_string_attribute(req->op.add.message, "objectClass", "inetOrgPerson"))) {

		TALLOC_FREE(ac);

		if (ldb_msg_find_element(req->op.add.message, "clearTextPassword") != NULL) {
			ldb_set_errstring(ldb,
					  "'clearTextPassword' is only allowed on objects of class 'user' and/or 'inetOrgPerson'!");
			return LDB_ERR_NO_SUCH_ATTRIBUTE;
		}

		return ldb_next_request(module, req);
	}

	/* get user domain data */
	ret = build_domain_data_request(ac);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	return ldb_next_request(module, ac->dom_req);
}

static int password_hash_add_do_add(struct ph_context *ac)
{
	struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
	struct ldb_request *down_req;
	struct setup_password_fields_io io;
	int ret;

	/* Prepare the internal data structure containing the passwords */
	ret = setup_io(ac, ac->req->op.add.message, NULL, &io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = setup_password_fields(&io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = check_password_restrictions(&io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = setup_smartcard_reset(&io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = update_final_msg(&io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = ldb_build_add_req(&down_req, ldb, ac,
				ac->update_msg,
				ac->req->controls,
				ac, ph_op_callback,
				ac->req);
	LDB_REQ_SET_LOCATION(down_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	return ldb_next_request(ac->module, down_req);
}

static int password_hash_modify(struct ldb_module *module, struct ldb_request *req)
{
	struct ldb_context *ldb = ldb_module_get_ctx(module);
	struct ph_context *ac = NULL;
	const char *passwordAttrs[] = { "userPassword", "clearTextPassword",
		"unicodePwd", "dBCSPwd", NULL }, **l;
	unsigned int del_attr_cnt, add_attr_cnt, rep_attr_cnt;
	struct ldb_message_element *passwordAttr;
	struct ldb_message *msg;
	struct ldb_request *down_req;
	struct ldb_control *restore = NULL;
	int ret;
	unsigned int i = 0;

	ldb_debug(ldb, LDB_DEBUG_TRACE, "password_hash_modify\n");

	ret = password_hash_needed(module, req, &ac);
	if (ret != LDB_SUCCESS) {
		return ret;
	}
	if (ac == NULL) {
		return ret;
	}

	/* use a new message structure so that we can modify it */
	msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
	if (msg == NULL) {
		return ldb_oom(ldb);
	}

	/* - check for single-valued password attributes
	 *   (if not return "CONSTRAINT_VIOLATION")
	 * - check that for a password change operation one add and one delete
	 *   operation exists
	 *   (if not return "CONSTRAINT_VIOLATION" or "UNWILLING_TO_PERFORM")
	 * - check that a password change and a password set operation cannot
	 *   be mixed
	 *   (if not return "UNWILLING_TO_PERFORM")
	 * - remove all password attributes modifications from the first change
	 *   operation (anything without the passwords) - we will make the real
	 *   modification later */
	del_attr_cnt = 0;
	add_attr_cnt = 0;
	rep_attr_cnt = 0;
	for (l = passwordAttrs; *l != NULL; l++) {
		if ((!ac->userPassword) &&
		    (ldb_attr_cmp(*l, "userPassword") == 0)) {
			continue;
		}

		while ((passwordAttr = ldb_msg_find_element(msg, *l)) != NULL) {
			if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_DELETE) {
				++del_attr_cnt;
			}
			if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_ADD) {
				++add_attr_cnt;
			}
			if (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_REPLACE) {
				++rep_attr_cnt;
			}
			if ((passwordAttr->num_values != 1) &&
			    (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_ADD)) {
				talloc_free(ac);
				ldb_asprintf_errstring(ldb,
						       "'%s' attribute must have exactly one value on add operations!",
						       *l);
				return LDB_ERR_CONSTRAINT_VIOLATION;
			}
			if ((passwordAttr->num_values > 1) &&
			    (LDB_FLAG_MOD_TYPE(passwordAttr->flags) == LDB_FLAG_MOD_DELETE)) {
				talloc_free(ac);
				ldb_asprintf_errstring(ldb,
						       "'%s' attribute must have zero or one value(s) on delete operations!",
						       *l);
				return LDB_ERR_CONSTRAINT_VIOLATION;
			}
			ldb_msg_remove_element(msg, passwordAttr);
		}
	}
	if ((del_attr_cnt == 0) && (add_attr_cnt > 0)) {
		talloc_free(ac);
		ldb_set_errstring(ldb,
				  "Only the add action for a password change specified!");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}
	if ((del_attr_cnt > 1) || (add_attr_cnt > 1)) {
		talloc_free(ac);
		ldb_set_errstring(ldb,
				  "Only one delete and one add action for a password change allowed!");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}
	if ((rep_attr_cnt > 0) && ((del_attr_cnt > 0) || (add_attr_cnt > 0))) {
		talloc_free(ac);
		ldb_set_errstring(ldb,
				  "Either a password change or a password set operation is allowed!");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	restore = ldb_request_get_control(req,
					DSDB_CONTROL_RESTORE_TOMBSTONE_OID);
	if (restore == NULL) {
		/*
		 * A tomstone reanimation generates a double update
		 * of pwdLastSet.
		 *
		 * So we only remove it without the
		 * DSDB_CONTROL_RESTORE_TOMBSTONE_OID control.
		 */
		ldb_msg_remove_attr(msg, "pwdLastSet");
	}


	/* if there was nothing else to be modified skip to next step */
	if (msg->num_elements == 0) {
		return password_hash_mod_search_self(ac);
	}

	/*
	 * Now we apply all changes remaining in msg
	 * and remove them from our final update_msg
	 */

	for (i = 0; i < msg->num_elements; i++) {
		ldb_msg_remove_attr(ac->update_msg,
				    msg->elements[i].name);
	}

	ret = ldb_build_mod_req(&down_req, ldb, ac,
				msg,
				req->controls,
				ac, ph_modify_callback,
				req);
	LDB_REQ_SET_LOCATION(down_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	return ldb_next_request(module, down_req);
}

static int ph_modify_callback(struct ldb_request *req, struct ldb_reply *ares)
{
	struct ph_context *ac;

	ac = talloc_get_type(req->context, struct ph_context);

	if (!ares) {
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}

	if (ares->type == LDB_REPLY_REFERRAL) {
		return ldb_module_send_referral(ac->req, ares->referral);
	}

	if (ares->error != LDB_SUCCESS) {
		return ldb_module_done(ac->req, ares->controls,
					ares->response, ares->error);
	}

	if (ares->type != LDB_REPLY_DONE) {
		talloc_free(ares);
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}

	talloc_free(ares);

	return password_hash_mod_search_self(ac);
}

static int ph_mod_search_callback(struct ldb_request *req, struct ldb_reply *ares)
{
	struct ldb_context *ldb;
	struct ph_context *ac;
	int ret = LDB_SUCCESS;

	ac = talloc_get_type(req->context, struct ph_context);
	ldb = ldb_module_get_ctx(ac->module);

	if (!ares) {
		ret = LDB_ERR_OPERATIONS_ERROR;
		goto done;
	}
	if (ares->error != LDB_SUCCESS) {
		return ldb_module_done(ac->req, ares->controls,
					ares->response, ares->error);
	}

	/* we are interested only in the single reply (base search) */
	switch (ares->type) {
	case LDB_REPLY_ENTRY:
		/* Make sure we are performing the password change action on a
		 * (for us) valid object. Those are instances of either "user"
		 * and/or "inetOrgPerson". Otherwise continue with the
		 * submodules. */
		if ((!ldb_msg_check_string_attribute(ares->message, "objectClass", "user"))
			&& (!ldb_msg_check_string_attribute(ares->message, "objectClass", "inetOrgPerson"))) {
			talloc_free(ares);

			if (ldb_msg_find_element(ac->req->op.mod.message, "clearTextPassword") != NULL) {
				ldb_set_errstring(ldb,
						  "'clearTextPassword' is only allowed on objects of class 'user' and/or 'inetOrgPerson'!");
				ret = LDB_ERR_NO_SUCH_ATTRIBUTE;
				goto done;
			}

			ret = ldb_next_request(ac->module, ac->req);
			goto done;
		}

		if (ac->search_res != NULL) {
			talloc_free(ares);

			ldb_set_errstring(ldb, "Too many results");
			ret = LDB_ERR_OPERATIONS_ERROR;
			goto done;
		}

		ac->search_res = talloc_steal(ac, ares);
		ret = LDB_SUCCESS;
		break;

	case LDB_REPLY_REFERRAL:
		/* ignore anything else for now */
		talloc_free(ares);
		ret = LDB_SUCCESS;
		break;

	case LDB_REPLY_DONE:
		talloc_free(ares);

		/* get user domain data */
		ret = build_domain_data_request(ac);
		if (ret != LDB_SUCCESS) {
			return ldb_module_done(ac->req, NULL, NULL, ret);
		}

		ret = ldb_next_request(ac->module, ac->dom_req);
		break;
	}

done:
	if (ret != LDB_SUCCESS) {
		return ldb_module_done(ac->req, NULL, NULL, ret);
	}

	return LDB_SUCCESS;
}

static int password_hash_mod_search_self(struct ph_context *ac)
{
	struct ldb_context *ldb;
	static const char * const attrs[] = { "objectClass",
					      "userAccountControl",
					      "msDS-User-Account-Control-Computed",
					      "pwdLastSet",
					      "sAMAccountName",
					      "objectSid",
					      "userPrincipalName",
					      "supplementalCredentials",
					      "lmPwdHistory",
					      "ntPwdHistory",
					      "dBCSPwd",
					      "unicodePwd",
					      "badPasswordTime",
					      "badPwdCount",
					      "lockoutTime",
					      "msDS-SecondaryKrbTgtNumber",
					      NULL };
	struct ldb_request *search_req;
	int ret;

	ldb = ldb_module_get_ctx(ac->module);

	ret = ldb_build_search_req(&search_req, ldb, ac,
				   ac->req->op.mod.message->dn,
				   LDB_SCOPE_BASE,
				   "(objectclass=*)",
				   attrs,
				   NULL,
				   ac, ph_mod_search_callback,
				   ac->req);
	LDB_REQ_SET_LOCATION(search_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	return ldb_next_request(ac->module, search_req);
}

static int password_hash_mod_do_mod(struct ph_context *ac)
{
	struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
	struct ldb_request *mod_req;
	struct setup_password_fields_io io;
	int ret;

	/* Prepare the internal data structure containing the passwords */
	ret = setup_io(ac, ac->req->op.mod.message,
		       ac->search_res->message, &io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = setup_password_fields(&io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = check_password_restrictions(&io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = setup_smartcard_reset(&io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = update_final_msg(&io);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = ldb_build_mod_req(&mod_req, ldb, ac,
				ac->update_msg,
				ac->req->controls,
				ac, ph_op_callback,
				ac->req);
	LDB_REQ_SET_LOCATION(mod_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	return ldb_next_request(ac->module, mod_req);
}

static const struct ldb_module_ops ldb_password_hash_module_ops = {
	.name          = "password_hash",
	.add           = password_hash_add,
	.modify        = password_hash_modify
};

int ldb_password_hash_module_init(const char *version)
{
#ifdef ENABLE_GPGME
	const char *gversion = NULL;
#endif /* ENABLE_GPGME */

	LDB_MODULE_CHECK_VERSION(version);

#ifdef ENABLE_GPGME
	/*
	 * Note: this sets a SIGPIPE handler
	 * if none is active already. See:
	 * https://www.gnupg.org/documentation/manuals/gpgme/Signal-Handling.html#Signal-Handling
	 */
	gversion = gpgme_check_version(GPGME_VERSION);
	if (gversion == NULL) {
		fprintf(stderr, "%s() in %s version[%s]: "
			"gpgme_check_version(%s) not available, "
			"gpgme_check_version(NULL) => '%s'\n",
			__func__, __FILE__, version,
			GPGME_VERSION, gpgme_check_version(NULL));
		return LDB_ERR_UNAVAILABLE;
	}
#endif /* ENABLE_GPGME */

	return ldb_register_module(&ldb_password_hash_module_ops);
}