summaryrefslogtreecommitdiff
path: root/source3/utils/ntlm_auth.c
blob: b38995712cd719e97d1d352dc125ca60d53c8645 (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
/*
   Unix SMB/CIFS implementation.

   Winbind status program.

   Copyright (C) Tim Potter      2000-2003
   Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
   Copyright (C) Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it> 2000
   Copyright (C) Robert O'Callahan 2006 (added cached credential code).
   Copyright (C) Kai Blin <kai@samba.org> 2008

   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/>.
*/

#include "includes.h"
#include "lib/param/param.h"
#include "popt_common.h"
#include "utils/ntlm_auth.h"
#include "../libcli/auth/libcli_auth.h"
#include "../libcli/auth/spnego.h"
#include "auth/ntlmssp/ntlmssp.h"
#include "auth/gensec/gensec.h"
#include "auth/credentials/credentials.h"
#include "librpc/crypto/gse.h"
#include "smb_krb5.h"
#include <iniparser.h>
#include "../lib/crypto/arcfour.h"
#include "libads/kerberos_proto.h"
#include "nsswitch/winbind_client.h"
#include "librpc/gen_ndr/krb5pac.h"
#include "../lib/util/asn1.h"
#include "auth/common_auth.h"

#ifndef PAM_WINBIND_CONFIG_FILE
#define PAM_WINBIND_CONFIG_FILE "/etc/security/pam_winbind.conf"
#endif

#define WINBIND_KRB5_AUTH	0x00000080

#undef DBGC_CLASS
#define DBGC_CLASS DBGC_WINBIND

#define INITIAL_BUFFER_SIZE 300
#define MAX_BUFFER_SIZE 630000

enum stdio_helper_mode {
	SQUID_2_4_BASIC,
	SQUID_2_5_BASIC,
	SQUID_2_5_NTLMSSP,
	NTLMSSP_CLIENT_1,
	GSS_SPNEGO,
	GSS_SPNEGO_CLIENT,
	NTLM_SERVER_1,
	NTLM_CHANGE_PASSWORD_1,
	NUM_HELPER_MODES
};

enum ntlm_auth_cli_state {
	CLIENT_INITIAL = 0,
	CLIENT_RESPONSE,
	CLIENT_FINISHED,
	CLIENT_ERROR
};

enum ntlm_auth_svr_state {
	SERVER_INITIAL = 0,
	SERVER_CHALLENGE,
	SERVER_FINISHED,
	SERVER_ERROR
};

struct ntlm_auth_state {
	TALLOC_CTX *mem_ctx;
	enum stdio_helper_mode helper_mode;
	enum ntlm_auth_cli_state cli_state;
	enum ntlm_auth_svr_state svr_state;
	struct ntlmssp_state *ntlmssp_state;
	struct gensec_security *gensec_security;
	uint32_t neg_flags;
	char *want_feature_list;
	char *spnego_mech;
	char *spnego_mech_oid;
	bool have_session_key;
	DATA_BLOB session_key;
	DATA_BLOB initial_message;
};

typedef void (*stdio_helper_function)(struct ntlm_auth_state *state, char *buf,
					int length);

static void manage_squid_basic_request (struct ntlm_auth_state *state,
					char *buf, int length);

static void manage_squid_ntlmssp_request (struct ntlm_auth_state *state,
					char *buf, int length);

static void manage_client_ntlmssp_request (struct ntlm_auth_state *state,
					char *buf, int length);

static void manage_gss_spnego_request (struct ntlm_auth_state *state,
					char *buf, int length);

static void manage_gss_spnego_client_request (struct ntlm_auth_state *state,
					char *buf, int length);

static void manage_ntlm_server_1_request (struct ntlm_auth_state *state,
					char *buf, int length);

static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
					char *buf, int length);

static const struct {
	enum stdio_helper_mode mode;
	const char *name;
	stdio_helper_function fn;
} stdio_helper_protocols[] = {
	{ SQUID_2_4_BASIC, "squid-2.4-basic", manage_squid_basic_request},
	{ SQUID_2_5_BASIC, "squid-2.5-basic", manage_squid_basic_request},
	{ SQUID_2_5_NTLMSSP, "squid-2.5-ntlmssp", manage_squid_ntlmssp_request},
	{ NTLMSSP_CLIENT_1, "ntlmssp-client-1", manage_client_ntlmssp_request},
	{ GSS_SPNEGO, "gss-spnego", manage_gss_spnego_request},
	{ GSS_SPNEGO_CLIENT, "gss-spnego-client", manage_gss_spnego_client_request},
	{ NTLM_SERVER_1, "ntlm-server-1", manage_ntlm_server_1_request},
	{ NTLM_CHANGE_PASSWORD_1, "ntlm-change-password-1", manage_ntlm_change_password_1_request},
	{ NUM_HELPER_MODES, NULL, NULL}
};

const char *opt_username;
const char *opt_domain;
const char *opt_workstation;
const char *opt_password;
static DATA_BLOB opt_challenge;
static DATA_BLOB opt_lm_response;
static DATA_BLOB opt_nt_response;
static int request_lm_key;
static int request_user_session_key;
static int use_cached_creds;

static const char *require_membership_of;
static const char *require_membership_of_sid;
static const char *opt_pam_winbind_conf;

/**
 * A limited set of features are defined with text strings as needed
 * by ntlm_auth
 *
 */
static void gensec_want_feature_list(struct gensec_security *state, char* feature_list)
{
	if (in_list("NTLMSSP_FEATURE_SESSION_KEY", feature_list, true)) {
		DEBUG(10, ("want GENSEC_FEATURE_SESSION_KEY\n"));
		gensec_want_feature(state, GENSEC_FEATURE_SESSION_KEY);
	}
	if (in_list("NTLMSSP_FEATURE_SIGN", feature_list, true)) {
		DEBUG(10, ("want GENSEC_FEATURE_SIGN\n"));
		gensec_want_feature(state, GENSEC_FEATURE_SIGN);
	}
	if (in_list("NTLMSSP_FEATURE_SEAL", feature_list, true)) {
		DEBUG(10, ("want GENSEC_FEATURE_SEAL\n"));
		gensec_want_feature(state, GENSEC_FEATURE_SEAL);
	}
}

static char winbind_separator(void)
{
	struct winbindd_response response;
	static bool got_sep;
	static char sep;

	if (got_sep)
		return sep;

	ZERO_STRUCT(response);

	/* Send off request */

	if (winbindd_request_response(WINBINDD_INFO, NULL, &response) !=
	    NSS_STATUS_SUCCESS) {
		d_printf("could not obtain winbind separator!\n");
		return *lp_winbind_separator();
	}

	sep = response.data.info.winbind_separator;
	got_sep = True;

	if (!sep) {
		d_printf("winbind separator was NULL!\n");
		return *lp_winbind_separator();
	}

	return sep;
}

const char *get_winbind_domain(void)
{
	struct winbindd_response response;

	static fstring winbind_domain;
	if (*winbind_domain) {
		return winbind_domain;
	}

	ZERO_STRUCT(response);

	/* Send off request */

	if (winbindd_request_response(WINBINDD_DOMAIN_NAME, NULL, &response) !=
	    NSS_STATUS_SUCCESS) {
		DEBUG(0, ("could not obtain winbind domain name!\n"));
		return lp_workgroup();
	}

	fstrcpy(winbind_domain, response.data.domain_name);

	return winbind_domain;

}

const char *get_winbind_netbios_name(void)
{
	struct winbindd_response response;

	static fstring winbind_netbios_name;

	if (*winbind_netbios_name) {
		return winbind_netbios_name;
	}

	ZERO_STRUCT(response);

	/* Send off request */

	if (winbindd_request_response(WINBINDD_NETBIOS_NAME, NULL, &response) !=
	    NSS_STATUS_SUCCESS) {
		DEBUG(0, ("could not obtain winbind netbios name!\n"));
		return lp_netbios_name();
	}

	fstrcpy(winbind_netbios_name, response.data.netbios_name);

	return winbind_netbios_name;

}

DATA_BLOB get_challenge(void) 
{
	static DATA_BLOB chal;
	if (opt_challenge.length)
		return opt_challenge;

	chal = data_blob(NULL, 8);

	generate_random_buffer(chal.data, chal.length);
	return chal;
}

/* Copy of parse_domain_user from winbindd_util.c.  Parse a string of the
   form DOMAIN/user into a domain and a user */

static bool parse_ntlm_auth_domain_user(const char *domuser, fstring domain, 
				     fstring user)
{

	char *p = strchr(domuser,winbind_separator());

	if (!p) {
		return False;
	}

	fstrcpy(user, p+1);
	fstrcpy(domain, domuser);
	domain[PTR_DIFF(p, domuser)] = 0;
	strupper_m(domain);

	return True;
}

static bool get_require_membership_sid(void) {
	struct winbindd_request request;
	struct winbindd_response response;

	if (!require_membership_of) {
		return True;
	}

	if (require_membership_of_sid) {
		return True;
	}

	/* Otherwise, ask winbindd for the name->sid request */

	ZERO_STRUCT(request);
	ZERO_STRUCT(response);

	if (!parse_ntlm_auth_domain_user(require_membership_of, 
					 request.data.name.dom_name, 
					 request.data.name.name)) {
		DEBUG(0, ("Could not parse %s into seperate domain/name parts!\n", 
			  require_membership_of));
		return False;
	}

	if (winbindd_request_response(WINBINDD_LOOKUPNAME, &request, &response) !=
	    NSS_STATUS_SUCCESS) {
		DEBUG(0, ("Winbindd lookupname failed to resolve %s into a SID!\n", 
			  require_membership_of));
		return False;
	}

	require_membership_of_sid = SMB_STRDUP(response.data.sid.sid);

	if (require_membership_of_sid)
		return True;

	return False;
}

/* 
 * Get some configuration from pam_winbind.conf to see if we 
 * need to contact trusted domain
 */

int get_pam_winbind_config()
{
	int ctrl = 0;
	dictionary *d = NULL;

	if (!opt_pam_winbind_conf || !*opt_pam_winbind_conf) {
		opt_pam_winbind_conf = PAM_WINBIND_CONFIG_FILE;
	}

	d = iniparser_load(discard_const_p(char, opt_pam_winbind_conf));

	if (!d) {
		return 0;
	}

	if (iniparser_getboolean(d, discard_const_p(char, "global:krb5_auth"), false)) {
		ctrl |= WINBIND_KRB5_AUTH;
	}

	iniparser_freedict(d);

	return ctrl;
}

/* Authenticate a user with a plaintext password */

static bool check_plaintext_auth(const char *user, const char *pass,
				 bool stdout_diagnostics)
{
	struct winbindd_request request;
	struct winbindd_response response;
        NSS_STATUS result;

	if (!get_require_membership_sid()) {
		return False;
	}

	/* Send off request */

	ZERO_STRUCT(request);
	ZERO_STRUCT(response);

	fstrcpy(request.data.auth.user, user);
	fstrcpy(request.data.auth.pass, pass);
	if (require_membership_of_sid) {
		strlcpy(request.data.auth.require_membership_of_sid,
			require_membership_of_sid,
			sizeof(request.data.auth.require_membership_of_sid));
	}

	result = winbindd_request_response(WINBINDD_PAM_AUTH, &request, &response);

	/* Display response */

	if (stdout_diagnostics) {
		if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
			d_printf("Reading winbind reply failed! (0x01)\n");
		}

		d_printf("%s: %s (0x%x)\n",
			 response.data.auth.nt_status_string,
			 response.data.auth.error_string,
			 response.data.auth.nt_status);
	} else {
		if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
			DEBUG(1, ("Reading winbind reply failed! (0x01)\n"));
		}

		DEBUG(3, ("%s: %s (0x%x)\n",
			  response.data.auth.nt_status_string,
			  response.data.auth.error_string,
			  response.data.auth.nt_status));
	}

        return (result == NSS_STATUS_SUCCESS);
}

/* authenticate a user with an encrypted username/password */

NTSTATUS contact_winbind_auth_crap(const char *username,
				   const char *domain,
				   const char *workstation,
				   const DATA_BLOB *challenge,
				   const DATA_BLOB *lm_response,
				   const DATA_BLOB *nt_response,
				   uint32 flags,
				   uint32 extra_logon_parameters,
				   uint8 lm_key[8],
				   uint8 user_session_key[16],
				   char **error_string,
				   char **unix_name)
{
	NTSTATUS nt_status;
        NSS_STATUS result;
	struct winbindd_request request;
	struct winbindd_response response;

	if (!get_require_membership_sid()) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	ZERO_STRUCT(request);
	ZERO_STRUCT(response);

	request.flags = flags;

	request.data.auth_crap.logon_parameters = extra_logon_parameters
		| MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT | MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT;

	if (require_membership_of_sid)
		fstrcpy(request.data.auth_crap.require_membership_of_sid, require_membership_of_sid);

        fstrcpy(request.data.auth_crap.user, username);
	fstrcpy(request.data.auth_crap.domain, domain);

	fstrcpy(request.data.auth_crap.workstation, 
		workstation);

	memcpy(request.data.auth_crap.chal, challenge->data, MIN(challenge->length, 8));

	if (lm_response && lm_response->length) {
		memcpy(request.data.auth_crap.lm_resp, 
		       lm_response->data, 
		       MIN(lm_response->length, sizeof(request.data.auth_crap.lm_resp)));
		request.data.auth_crap.lm_resp_len = lm_response->length;
	}

	if (nt_response && nt_response->length) {
		if (nt_response->length > sizeof(request.data.auth_crap.nt_resp)) {
			request.flags = request.flags | WBFLAG_BIG_NTLMV2_BLOB;
			request.extra_len = nt_response->length;
			request.extra_data.data = SMB_MALLOC_ARRAY(char, request.extra_len);
			if (request.extra_data.data == NULL) {
				return NT_STATUS_NO_MEMORY;
			}
			memcpy(request.extra_data.data, nt_response->data,
			       nt_response->length);

		} else {
			memcpy(request.data.auth_crap.nt_resp,
			       nt_response->data, nt_response->length);
		}
                request.data.auth_crap.nt_resp_len = nt_response->length;
	}

	result = winbindd_request_response(WINBINDD_PAM_AUTH_CRAP, &request, &response);
	SAFE_FREE(request.extra_data.data);

	/* Display response */

	if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0)) {
		nt_status = NT_STATUS_UNSUCCESSFUL;
		if (error_string)
			*error_string = smb_xstrdup("Reading winbind reply failed!");
		winbindd_free_response(&response);
		return nt_status;
	}

	nt_status = (NT_STATUS(response.data.auth.nt_status));
	if (!NT_STATUS_IS_OK(nt_status)) {
		if (error_string) 
			*error_string = smb_xstrdup(response.data.auth.error_string);
		winbindd_free_response(&response);
		return nt_status;
	}

	if ((flags & WBFLAG_PAM_LMKEY) && lm_key) {
		memcpy(lm_key, response.data.auth.first_8_lm_hash, 
		       sizeof(response.data.auth.first_8_lm_hash));
	}
	if ((flags & WBFLAG_PAM_USER_SESSION_KEY) && user_session_key) {
		memcpy(user_session_key, response.data.auth.user_session_key, 
			sizeof(response.data.auth.user_session_key));
	}

	if (flags & WBFLAG_PAM_UNIX_NAME) {
		*unix_name = SMB_STRDUP(response.data.auth.unix_username);
		if (!*unix_name) {
			winbindd_free_response(&response);
			return NT_STATUS_NO_MEMORY;
		}
	}

	winbindd_free_response(&response);
	return nt_status;
}

/* contact server to change user password using auth crap */
static NTSTATUS contact_winbind_change_pswd_auth_crap(const char *username,
						      const char *domain,
						      const DATA_BLOB new_nt_pswd,
						      const DATA_BLOB old_nt_hash_enc,
						      const DATA_BLOB new_lm_pswd,
						      const DATA_BLOB old_lm_hash_enc,
						      char  **error_string)
{
	NTSTATUS nt_status;
	NSS_STATUS result;
	struct winbindd_request request;
	struct winbindd_response response;

	if (!get_require_membership_sid())
	{
		if(error_string)
			*error_string = smb_xstrdup("Can't get membership sid.");
		return NT_STATUS_INVALID_PARAMETER;
	}

	ZERO_STRUCT(request);
	ZERO_STRUCT(response);

	if(username != NULL)
		fstrcpy(request.data.chng_pswd_auth_crap.user, username);
	if(domain != NULL)
		fstrcpy(request.data.chng_pswd_auth_crap.domain,domain);

	if(new_nt_pswd.length)
	{
		memcpy(request.data.chng_pswd_auth_crap.new_nt_pswd, new_nt_pswd.data, sizeof(request.data.chng_pswd_auth_crap.new_nt_pswd));
		request.data.chng_pswd_auth_crap.new_nt_pswd_len = new_nt_pswd.length;
	}

	if(old_nt_hash_enc.length)
	{
		memcpy(request.data.chng_pswd_auth_crap.old_nt_hash_enc, old_nt_hash_enc.data, sizeof(request.data.chng_pswd_auth_crap.old_nt_hash_enc));
		request.data.chng_pswd_auth_crap.old_nt_hash_enc_len = old_nt_hash_enc.length;
	}

	if(new_lm_pswd.length)
	{
		memcpy(request.data.chng_pswd_auth_crap.new_lm_pswd, new_lm_pswd.data, sizeof(request.data.chng_pswd_auth_crap.new_lm_pswd));
		request.data.chng_pswd_auth_crap.new_lm_pswd_len = new_lm_pswd.length;
	}

	if(old_lm_hash_enc.length)
	{
		memcpy(request.data.chng_pswd_auth_crap.old_lm_hash_enc, old_lm_hash_enc.data, sizeof(request.data.chng_pswd_auth_crap.old_lm_hash_enc));
		request.data.chng_pswd_auth_crap.old_lm_hash_enc_len = old_lm_hash_enc.length;
	}

	result = winbindd_request_response(WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, &request, &response);

	/* Display response */

	if ((result != NSS_STATUS_SUCCESS) && (response.data.auth.nt_status == 0))
	{
		nt_status = NT_STATUS_UNSUCCESSFUL;
		if (error_string)
			*error_string = smb_xstrdup("Reading winbind reply failed!");
		winbindd_free_response(&response);
		return nt_status;
	}

	nt_status = (NT_STATUS(response.data.auth.nt_status));
	if (!NT_STATUS_IS_OK(nt_status))
	{
		if (error_string) 
			*error_string = smb_xstrdup(response.data.auth.error_string);
		winbindd_free_response(&response);
		return nt_status;
	}

	winbindd_free_response(&response);

    return nt_status;
}

static NTSTATUS ntlm_auth_generate_session_info(struct auth4_context *auth_context,
						TALLOC_CTX *mem_ctx,
						void *server_returned_info,
						const char *original_user_name,
						uint32_t session_info_flags,
						struct auth_session_info **session_info_out)
{
	char *unix_username = (char *)server_returned_info;
	struct auth_session_info *session_info = talloc_zero(mem_ctx, struct auth_session_info);
	if (!session_info) {
		return NT_STATUS_NO_MEMORY;
	}

	session_info->unix_info = talloc_zero(session_info, struct auth_user_info_unix);
	if (!session_info->unix_info) {
		TALLOC_FREE(session_info);
		return NT_STATUS_NO_MEMORY;
	}
	session_info->unix_info->unix_name = talloc_steal(session_info->unix_info, unix_username);

	*session_info_out = session_info;

	return NT_STATUS_OK;
}

/**
 * Return the challenge as determined by the authentication subsystem 
 * @return an 8 byte random challenge
 */

static NTSTATUS ntlm_auth_get_challenge(struct auth4_context *auth_ctx,
					uint8_t chal[8])
{
	if (auth_ctx->challenge.data.length == 8) {
		DEBUG(5, ("auth_get_challenge: returning previous challenge by module %s (normal)\n", 
			  auth_ctx->challenge.set_by));
		memcpy(chal, auth_ctx->challenge.data.data, 8);
		return NT_STATUS_OK;
	}

	if (!auth_ctx->challenge.set_by) {
		generate_random_buffer(chal, 8);

		auth_ctx->challenge.data		= data_blob_talloc(auth_ctx, chal, 8);
		NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.data.data);
		auth_ctx->challenge.set_by		= "random";

		auth_ctx->challenge.may_be_modified	= true;
	}

	DEBUG(10,("auth_get_challenge: challenge set by %s\n",
		 auth_ctx->challenge.set_by));

	return NT_STATUS_OK;
}

/**
 * Some authentication methods 'fix' the challenge, so we may not be able to set it
 *
 * @return If the effective challenge used by the auth subsystem may be modified
 */
static bool ntlm_auth_may_set_challenge(struct auth4_context *auth_ctx)
{
	return auth_ctx->challenge.may_be_modified;
}

/**
 * NTLM2 authentication modifies the effective challenge, 
 * @param challenge The new challenge value
 */
static NTSTATUS ntlm_auth_set_challenge(struct auth4_context *auth_ctx, const uint8_t chal[8], const char *set_by) 
{
	auth_ctx->challenge.set_by = talloc_strdup(auth_ctx, set_by);
	NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.set_by);

	auth_ctx->challenge.data = data_blob_talloc(auth_ctx, chal, 8);
	NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.data.data);

	return NT_STATUS_OK;
}

/**
 * Check the password on an NTLMSSP login.  
 *
 * Return the session keys used on the connection.
 */

static NTSTATUS winbind_pw_check(struct auth4_context *auth4_context, 
				 TALLOC_CTX *mem_ctx,
				 const struct auth_usersupplied_info *user_info, 
				 void **server_returned_info,
				 DATA_BLOB *session_key, DATA_BLOB *lm_session_key)
{
	static const char zeros[16] = { 0, };
	NTSTATUS nt_status;
	char *error_string = NULL;
	uint8 lm_key[8]; 
	uint8 user_sess_key[16]; 
	char *unix_name = NULL;

	nt_status = contact_winbind_auth_crap(user_info->client.account_name, user_info->client.domain_name, 
					      user_info->workstation_name, 
					      &auth4_context->challenge.data,
					      &user_info->password.response.lanman,
					      &user_info->password.response.nt,
					      WBFLAG_PAM_LMKEY | WBFLAG_PAM_USER_SESSION_KEY | WBFLAG_PAM_UNIX_NAME,
					      0,
					      lm_key, user_sess_key, 
					      &error_string, &unix_name);

	if (NT_STATUS_IS_OK(nt_status)) {
		if (memcmp(lm_key, zeros, 8) != 0) {
			*lm_session_key = data_blob_talloc(mem_ctx, NULL, 16);
			memcpy(lm_session_key->data, lm_key, 8);
			memset(lm_session_key->data+8, '\0', 8);
		}

		if (memcmp(user_sess_key, zeros, 16) != 0) {
			*session_key = data_blob_talloc(mem_ctx, user_sess_key, 16);
		}
		*server_returned_info = talloc_strdup(mem_ctx,
						      unix_name);
	} else {
		DEBUG(NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED) ? 0 : 3, 
		      ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
		       user_info->client.domain_name, user_info->client.account_name,
		       user_info->workstation_name, 
		       error_string ? error_string : "unknown error (NULL)"));
	}

	SAFE_FREE(error_string);
	SAFE_FREE(unix_name);
	return nt_status;
}

static NTSTATUS local_pw_check(struct auth4_context *auth4_context, 
				TALLOC_CTX *mem_ctx,
				const struct auth_usersupplied_info *user_info, 
				void **server_returned_info,
				DATA_BLOB *session_key, DATA_BLOB *lm_session_key)
{
	NTSTATUS nt_status;
	struct samr_Password lm_pw, nt_pw;

	nt_lm_owf_gen (opt_password, nt_pw.hash, lm_pw.hash);

	nt_status = ntlm_password_check(mem_ctx,
					true, true, 0,
					&auth4_context->challenge.data,
					&user_info->password.response.lanman,
					&user_info->password.response.nt,
					user_info->client.account_name,
					user_info->client.account_name,
					user_info->client.domain_name, 
					&lm_pw, &nt_pw, session_key, lm_session_key);

	if (NT_STATUS_IS_OK(nt_status)) {
		*server_returned_info = talloc_asprintf(mem_ctx,
							"%s%c%s", user_info->client.domain_name,
							*lp_winbind_separator(), 
							user_info->client.account_name);
	} else {
		DEBUG(3, ("Login for user [%s]\\[%s]@[%s] failed due to [%s]\n", 
			  user_info->client.domain_name, user_info->client.account_name,
			  user_info->workstation_name, 
			  nt_errstr(nt_status)));
	}
	return nt_status;
}

static NTSTATUS ntlm_auth_start_ntlmssp_client(struct ntlmssp_state **client_ntlmssp_state)
{
	NTSTATUS status;
	if ( (opt_username == NULL) || (opt_domain == NULL) ) {
		status = NT_STATUS_UNSUCCESSFUL;
		DEBUG(1, ("Need username and domain for NTLMSSP\n"));
		return NT_STATUS_INVALID_PARAMETER;
	}

	status = ntlmssp_client_start(NULL,
				      lp_netbios_name(),
				      lp_workgroup(),
				      lp_client_ntlmv2_auth(),
				      client_ntlmssp_state);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Could not start NTLMSSP client: %s\n",
			  nt_errstr(status)));
		TALLOC_FREE(*client_ntlmssp_state);
		return status;
	}

	status = ntlmssp_set_username(*client_ntlmssp_state, opt_username);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Could not set username: %s\n",
			  nt_errstr(status)));
		TALLOC_FREE(*client_ntlmssp_state);
		return status;
	}

	status = ntlmssp_set_domain(*client_ntlmssp_state, opt_domain);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Could not set domain: %s\n",
			  nt_errstr(status)));
		TALLOC_FREE(*client_ntlmssp_state);
		return status;
	}

	if (opt_password) {
		status = ntlmssp_set_password(*client_ntlmssp_state, opt_password);

		if (!NT_STATUS_IS_OK(status)) {
			DEBUG(1, ("Could not set password: %s\n",
				  nt_errstr(status)));
			TALLOC_FREE(*client_ntlmssp_state);
			return status;
		}
	}

	return NT_STATUS_OK;
}

static struct auth4_context *make_auth4_context_ntlm_auth(TALLOC_CTX *mem_ctx, bool local_pw)
{
	struct auth4_context *auth4_context = talloc_zero(mem_ctx, struct auth4_context);
	if (auth4_context == NULL) {
		DEBUG(10, ("failed to allocate auth4_context failed\n"));
		return NULL;
	}
	auth4_context->generate_session_info = ntlm_auth_generate_session_info;
	auth4_context->get_ntlm_challenge = ntlm_auth_get_challenge;
	auth4_context->set_ntlm_challenge = ntlm_auth_set_challenge;
	auth4_context->challenge_may_be_modified = ntlm_auth_may_set_challenge;
	if (local_pw) {
		auth4_context->check_ntlm_password = local_pw_check;
	} else {
		auth4_context->check_ntlm_password = winbind_pw_check;
	}
	auth4_context->private_data = NULL;
	return auth4_context;
}

static NTSTATUS ntlm_auth_start_ntlmssp_server(TALLOC_CTX *mem_ctx,
					       struct gensec_security **gensec_security_out)
{
	struct gensec_security *gensec_security;
	NTSTATUS nt_status;

	TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
	NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);

	struct gensec_settings *gensec_settings;
	struct loadparm_context *lp_ctx;
	size_t idx = 0;
	struct cli_credentials *server_credentials;
	
	struct auth4_context *auth4_context = make_auth4_context_ntlm_auth(tmp_ctx, opt_password);
	if (auth4_context == NULL) {
		TALLOC_FREE(tmp_ctx);
		return NT_STATUS_NO_MEMORY;
	}
	
	lp_ctx = loadparm_init_s3(tmp_ctx, loadparm_s3_context());
	if (lp_ctx == NULL) {
		DEBUG(10, ("loadparm_init_s3 failed\n"));
		TALLOC_FREE(tmp_ctx);
		return NT_STATUS_INVALID_SERVER_STATE;
	}
	
	gensec_settings = lpcfg_gensec_settings(tmp_ctx, lp_ctx);
	if (lp_ctx == NULL) {
		DEBUG(10, ("lpcfg_gensec_settings failed\n"));
		TALLOC_FREE(tmp_ctx);
		return NT_STATUS_NO_MEMORY;
	}
	
	/* 
	 * This should be a 'netbios domain -> DNS domain'
	 * mapping, and can currently validly return NULL on
	 * poorly configured systems.
	 *
	 * This is used for the NTLMSSP server
	 *
	 */
	if (opt_password) {
		gensec_settings->server_netbios_name = lp_netbios_name();
		gensec_settings->server_netbios_domain = lp_workgroup();
	} else {
		gensec_settings->server_netbios_name = get_winbind_netbios_name();
		gensec_settings->server_netbios_domain = get_winbind_domain();
	}
	
	gensec_settings->server_dns_domain = strlower_talloc(gensec_settings,
							     get_mydnsdomname(talloc_tos()));
	gensec_settings->server_dns_name = strlower_talloc(gensec_settings,
							   get_mydnsfullname());
	
	gensec_settings->backends = talloc_zero_array(gensec_settings,
						      struct gensec_security_ops *, 4);
	
	if (gensec_settings->backends == NULL) {
		TALLOC_FREE(tmp_ctx);
		return NT_STATUS_NO_MEMORY;
	}
	
	gensec_init();
	
	gensec_settings->backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_NTLMSSP);
	
#if defined(HAVE_KRB5) && defined(HAVE_GSS_WRAP_IOV)
	gensec_settings->backends[idx++] = &gensec_gse_krb5_security_ops;
#endif
	
	gensec_settings->backends[idx++] = gensec_security_by_oid(NULL,
								  GENSEC_OID_SPNEGO);
	
	/*
	 * This is anonymous for now, because we just use it
	 * to set the kerberos state at the moment
	 */
	server_credentials = cli_credentials_init_anon(tmp_ctx);
	if (!server_credentials) {
		DEBUG(0, ("auth_generic_prepare: Failed to init server credentials\n"));
		return NT_STATUS_NO_MEMORY;
	}
	
	cli_credentials_set_conf(server_credentials, lp_ctx);
	
	if (lp_security() == SEC_ADS || USE_KERBEROS_KEYTAB) {
		cli_credentials_set_kerberos_state(server_credentials, CRED_AUTO_USE_KERBEROS);
	} else {
		cli_credentials_set_kerberos_state(server_credentials, CRED_DONT_USE_KERBEROS);
	}
	
	nt_status = gensec_server_start(tmp_ctx, gensec_settings,
					auth4_context, &gensec_security);
	
	if (!NT_STATUS_IS_OK(nt_status)) {
		TALLOC_FREE(tmp_ctx);
		return nt_status;
	}
	
	gensec_set_credentials(gensec_security, server_credentials);
	
	gensec_want_feature(gensec_security, GENSEC_FEATURE_SIGN);
	gensec_want_feature(gensec_security, GENSEC_FEATURE_SEAL);

	talloc_unlink(tmp_ctx, lp_ctx);
	talloc_unlink(tmp_ctx, server_credentials);
	talloc_unlink(tmp_ctx, gensec_settings);
	talloc_unlink(tmp_ctx, auth4_context);

	nt_status = gensec_start_mech_by_oid(gensec_security, GENSEC_OID_NTLMSSP);
	if (!NT_STATUS_IS_OK(nt_status)) {
		TALLOC_FREE(tmp_ctx);
		return nt_status;
	}
	
	*gensec_security_out = talloc_steal(mem_ctx, gensec_security);
	TALLOC_FREE(tmp_ctx);
	return NT_STATUS_OK;
}

/*******************************************************************
 Used by firefox to drive NTLM auth to IIS servers.
*******************************************************************/

static NTSTATUS do_ccache_ntlm_auth(DATA_BLOB initial_msg, DATA_BLOB challenge_msg,
				DATA_BLOB *reply)
{
	struct winbindd_request wb_request;
	struct winbindd_response wb_response;
	int ctrl = 0;
	NSS_STATUS result;

	/* get winbindd to do the ntlmssp step on our behalf */
	ZERO_STRUCT(wb_request);
	ZERO_STRUCT(wb_response);

	/*
	 * This is tricky here. If we set krb5_auth in pam_winbind.conf
	 * creds for users in trusted domain will be stored the winbindd
	 * child of the trusted domain. If we ask the primary domain for
	 * ntlm_ccache_auth, it will fail. So, we have to ask the trusted
	 * domain's child for ccache_ntlm_auth. that is to say, we have to 
	 * set WBFLAG_PAM_CONTACT_TRUSTDOM in request.flags.
	 */
	ctrl = get_pam_winbind_config();

	if (ctrl & WINBIND_KRB5_AUTH) {
		wb_request.flags |= WBFLAG_PAM_CONTACT_TRUSTDOM;
	}

	fstr_sprintf(wb_request.data.ccache_ntlm_auth.user,
		"%s%c%s", opt_domain, winbind_separator(), opt_username);
	wb_request.data.ccache_ntlm_auth.uid = geteuid();
	wb_request.data.ccache_ntlm_auth.initial_blob_len = initial_msg.length;
	wb_request.data.ccache_ntlm_auth.challenge_blob_len = challenge_msg.length;
	wb_request.extra_len = initial_msg.length + challenge_msg.length;

	if (wb_request.extra_len > 0) {
		wb_request.extra_data.data = SMB_MALLOC_ARRAY(char, wb_request.extra_len);
		if (wb_request.extra_data.data == NULL) {
			return NT_STATUS_NO_MEMORY;
		}

		memcpy(wb_request.extra_data.data, initial_msg.data, initial_msg.length);
		memcpy(wb_request.extra_data.data + initial_msg.length,
			challenge_msg.data, challenge_msg.length);
	}

	result = winbindd_request_response(WINBINDD_CCACHE_NTLMAUTH, &wb_request, &wb_response);
	SAFE_FREE(wb_request.extra_data.data);

	if (result != NSS_STATUS_SUCCESS) {
		winbindd_free_response(&wb_response);
		return NT_STATUS_UNSUCCESSFUL;
	}

	if (reply) {
		*reply = data_blob(wb_response.extra_data.data,
				wb_response.data.ccache_ntlm_auth.auth_blob_len);
		if (wb_response.data.ccache_ntlm_auth.auth_blob_len > 0 &&
				reply->data == NULL) {
			winbindd_free_response(&wb_response);
			return NT_STATUS_NO_MEMORY;
		}
	}

	winbindd_free_response(&wb_response);
	return NT_STATUS_MORE_PROCESSING_REQUIRED;
}

static void manage_squid_ntlmssp_request_int(struct ntlm_auth_state *state,
					     char *buf, int length,
					     TALLOC_CTX *mem_ctx,
					     char **response)
{
	DATA_BLOB request, reply;
	NTSTATUS nt_status;

	if (strlen(buf) < 2) {
		DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
		*response = talloc_strdup(mem_ctx, "BH NTLMSSP query invalid");
		return;
	}

	if (strlen(buf) > 3) {
		if(strncmp(buf, "SF ", 3) == 0){
			DEBUG(10, ("Setting flags to negotioate\n"));
			TALLOC_FREE(state->want_feature_list);
			state->want_feature_list = talloc_strdup(state->mem_ctx,
					buf+3);
			*response = talloc_strdup(mem_ctx, "OK");
			return;
		}
		request = base64_decode_data_blob(buf + 3);
	} else {
		request = data_blob_null;
	}

	if ((strncmp(buf, "PW ", 3) == 0)) {
		/* The calling application wants us to use a local password
		 * (rather than winbindd) */

		opt_password = SMB_STRNDUP((const char *)request.data,
				request.length);

		if (opt_password == NULL) {
			DEBUG(1, ("Out of memory\n"));
			*response = talloc_strdup(mem_ctx, "BH Out of memory");
			data_blob_free(&request);
			return;
		}

		*response = talloc_strdup(mem_ctx, "OK");
		data_blob_free(&request);
		return;
	}

	if (strncmp(buf, "YR", 2) == 0) {
		TALLOC_FREE(state->gensec_security);
		state->svr_state = SERVER_INITIAL;
	} else if (strncmp(buf, "KK", 2) == 0) {
		/* No special preprocessing required */
	} else if (strncmp(buf, "GF", 2) == 0) {
		DEBUG(10, ("Requested negotiated NTLMSSP flags\n"));

		if (state->svr_state == SERVER_FINISHED) {
			*response = talloc_asprintf(mem_ctx, "GF 0x%08x",
						    gensec_ntlmssp_neg_flags(state->gensec_security));
		}
		else {
			*response = talloc_strdup(mem_ctx, "BH\n");
		}
		data_blob_free(&request);
		return;
	} else if (strncmp(buf, "GK", 2) == 0) {
		DEBUG(10, ("Requested NTLMSSP session key\n"));
		if(state->have_session_key) {
			DATA_BLOB session_key;
			char *key64;
			nt_status = gensec_session_key(state->gensec_security, talloc_tos(), &session_key);
			if (!NT_STATUS_IS_OK(nt_status)) {
				*response = talloc_asprintf(
					mem_ctx, "BH %s", nt_errstr(nt_status));
				return;
			}
			key64 = base64_encode_data_blob(state->mem_ctx, session_key);
			data_blob_free(&session_key);
			*response = talloc_asprintf(mem_ctx, "GK %s",
						 key64 ? key64 : "<NULL>");
			TALLOC_FREE(key64);
		} else {
			*response = talloc_strdup(mem_ctx, "BH");
		}

		data_blob_free(&request);
		return;
	} else {
		DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
		*response = talloc_strdup(mem_ctx, "BH NTLMSSP query invalid");
		return;
	}

	if (!state->gensec_security) {
		nt_status = ntlm_auth_start_ntlmssp_server(state, 
				&state->gensec_security);
		if (!NT_STATUS_IS_OK(nt_status)) {
			*response = talloc_asprintf(
				mem_ctx, "BH %s", nt_errstr(nt_status));
			return;
		}
		gensec_want_feature_list(state->gensec_security,
					 state->want_feature_list);
	}

	DEBUG(10, ("got NTLMSSP packet:\n"));
	dump_data(10, request.data, request.length);

	nt_status = gensec_update(state->gensec_security, talloc_tos(), NULL, request, &reply);

	if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
		char *reply_base64 = base64_encode_data_blob(state->mem_ctx,
				reply);
		*response = talloc_asprintf(mem_ctx, "TT %s", reply_base64);
		TALLOC_FREE(reply_base64);
		data_blob_free(&reply);
		state->svr_state = SERVER_CHALLENGE;
		DEBUG(10, ("NTLMSSP challenge\n"));
	} else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCESS_DENIED)) {
		*response = talloc_asprintf(mem_ctx, "BH %s",
					 nt_errstr(nt_status));
		DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));

		TALLOC_FREE(state->gensec_security);
	} else if (!NT_STATUS_IS_OK(nt_status)) {
		*response = talloc_asprintf(mem_ctx, "NA %s",
					 nt_errstr(nt_status));
		DEBUG(10, ("NTLMSSP %s\n", nt_errstr(nt_status)));
	} else {
		struct auth_session_info *session_info;
		nt_status = gensec_session_info(state->gensec_security, state->gensec_security, &session_info);
		if (!NT_STATUS_IS_OK(nt_status)) {
			DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
			TALLOC_FREE(state->gensec_security);
			return;
		}
		*response = talloc_asprintf(
			mem_ctx, "AF %s",
			session_info->unix_info->unix_name);
		DEBUG(10, ("NTLMSSP OK!\n"));

		state->have_session_key = true;
		state->svr_state = SERVER_FINISHED;
	}

	data_blob_free(&request);
}

static void manage_squid_ntlmssp_request(struct ntlm_auth_state *state,
					 char *buf, int length)
{
	char *response;

	manage_squid_ntlmssp_request_int(state, buf, length,
					 talloc_tos(), &response);

	if (response == NULL) {
		x_fprintf(x_stdout, "BH Out of memory\n");
		return;
	}
	x_fprintf(x_stdout, "%s\n", response);
	TALLOC_FREE(response);
}

static void manage_client_ntlmssp_request(struct ntlm_auth_state *state,
					 	char *buf, int length)
{
	DATA_BLOB request, reply;
	NTSTATUS nt_status;

	if (!opt_username || !*opt_username) {
		x_fprintf(x_stderr, "username must be specified!\n\n");
		exit(1);
	}

	if (strlen(buf) < 2) {
		DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
		x_fprintf(x_stdout, "BH NTLMSSP query invalid\n");
		return;
	}

	if (strlen(buf) > 3) {
		if(strncmp(buf, "SF ", 3) == 0) {
			DEBUG(10, ("Looking for flags to negotiate\n"));
			talloc_free(state->want_feature_list);
			state->want_feature_list = talloc_strdup(state->mem_ctx,
					buf+3);
			x_fprintf(x_stdout, "OK\n");
			return;
		}
		request = base64_decode_data_blob(buf + 3);
	} else {
		request = data_blob_null;
	}

	if (strncmp(buf, "PW ", 3) == 0) {
		/* We asked for a password and obviously got it :-) */

		opt_password = SMB_STRNDUP((const char *)request.data,
				request.length);

		if (opt_password == NULL) {
			DEBUG(1, ("Out of memory\n"));
			x_fprintf(x_stdout, "BH Out of memory\n");
			data_blob_free(&request);
			return;
		}

		x_fprintf(x_stdout, "OK\n");
		data_blob_free(&request);
		return;
	}

	if (!state->ntlmssp_state && use_cached_creds) {
		/* check whether cached credentials are usable. */
		DATA_BLOB empty_blob = data_blob_null;

		nt_status = do_ccache_ntlm_auth(empty_blob, empty_blob, NULL);
		if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
			/* failed to use cached creds */
			use_cached_creds = False;
		}
	}

	if (opt_password == NULL && !use_cached_creds) {
		/* Request a password from the calling process.  After
		   sending it, the calling process should retry asking for the
		   negotiate. */

		DEBUG(10, ("Requesting password\n"));
		x_fprintf(x_stdout, "PW\n");
		return;
	}

	if (strncmp(buf, "YR", 2) == 0) {
		TALLOC_FREE(state->ntlmssp_state);
		state->cli_state = CLIENT_INITIAL;
	} else if (strncmp(buf, "TT", 2) == 0) {
		/* No special preprocessing required */
	} else if (strncmp(buf, "GF", 2) == 0) {
		DEBUG(10, ("Requested negotiated NTLMSSP flags\n"));

		if(state->cli_state == CLIENT_FINISHED) {
			x_fprintf(x_stdout, "GF 0x%08x\n", state->neg_flags);
		}
		else {
			x_fprintf(x_stdout, "BH\n");
		}

		data_blob_free(&request);
		return;
	} else if (strncmp(buf, "GK", 2) == 0 ) {
		DEBUG(10, ("Requested session key\n"));

		if(state->cli_state == CLIENT_FINISHED) {
			char *key64 = base64_encode_data_blob(state->mem_ctx,
					state->session_key);
			x_fprintf(x_stdout, "GK %s\n", key64?key64:"<NULL>");
			TALLOC_FREE(key64);
		}
		else {
			x_fprintf(x_stdout, "BH\n");
		}

		data_blob_free(&request);
		return;
	} else {
		DEBUG(1, ("NTLMSSP query [%s] invalid\n", buf));
		x_fprintf(x_stdout, "BH NTLMSSP query invalid\n");
		return;
	}

	if (!state->ntlmssp_state) {
		nt_status = ntlm_auth_start_ntlmssp_client(
				&state->ntlmssp_state);
		if (!NT_STATUS_IS_OK(nt_status)) {
			x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
			return;
		}
		ntlmssp_want_feature_list(state->ntlmssp_state,
				state->want_feature_list);
		state->initial_message = data_blob_null;
	}

	DEBUG(10, ("got NTLMSSP packet:\n"));
	dump_data(10, request.data, request.length);

	if (use_cached_creds && !opt_password &&
			(state->cli_state == CLIENT_RESPONSE)) {
		nt_status = do_ccache_ntlm_auth(state->initial_message, request,
				&reply);
	} else {
		nt_status = ntlmssp_update(state->ntlmssp_state, request,
				&reply);
	}

	if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
		char *reply_base64 = base64_encode_data_blob(state->mem_ctx,
				reply);
		if (state->cli_state == CLIENT_INITIAL) {
			x_fprintf(x_stdout, "YR %s\n", reply_base64);
			state->initial_message = reply;
			state->cli_state = CLIENT_RESPONSE;
		} else {
			x_fprintf(x_stdout, "KK %s\n", reply_base64);
			data_blob_free(&reply);
		}
		TALLOC_FREE(reply_base64);
		DEBUG(10, ("NTLMSSP challenge\n"));
	} else if (NT_STATUS_IS_OK(nt_status)) {
		char *reply_base64 = base64_encode_data_blob(talloc_tos(),
				reply);
		x_fprintf(x_stdout, "AF %s\n", reply_base64);
		TALLOC_FREE(reply_base64);

		if(state->have_session_key)
			data_blob_free(&state->session_key);

		state->session_key = data_blob(
				state->ntlmssp_state->session_key.data,
				state->ntlmssp_state->session_key.length);
		state->neg_flags = state->ntlmssp_state->neg_flags;
		state->have_session_key = true;

		DEBUG(10, ("NTLMSSP OK!\n"));
		state->cli_state = CLIENT_FINISHED;
		TALLOC_FREE(state->ntlmssp_state);
	} else {
		x_fprintf(x_stdout, "BH %s\n", nt_errstr(nt_status));
		DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(nt_status)));
		state->cli_state = CLIENT_ERROR;
		TALLOC_FREE(state->ntlmssp_state);
	}

	data_blob_free(&request);
}

static void manage_squid_basic_request(struct ntlm_auth_state *state,
					char *buf, int length)
{
	char *user, *pass;	
	user=buf;

	pass=(char *)memchr(buf,' ',length);
	if (!pass) {
		DEBUG(2, ("Password not found. Denying access\n"));
		x_fprintf(x_stdout, "ERR\n");
		return;
	}
	*pass='\0';
	pass++;

	if (state->helper_mode == SQUID_2_5_BASIC) {
		rfc1738_unescape(user);
		rfc1738_unescape(pass);
	}

	if (check_plaintext_auth(user, pass, False)) {
		x_fprintf(x_stdout, "OK\n");
	} else {
		x_fprintf(x_stdout, "ERR\n");
	}
}

static void offer_gss_spnego_mechs(void) {

	DATA_BLOB token;
	struct spnego_data spnego;
	ssize_t len;
	char *reply_base64;
	TALLOC_CTX *ctx = talloc_tos();
	char *principal;
	char *myname_lower;

	ZERO_STRUCT(spnego);

	myname_lower = talloc_strdup(ctx, lp_netbios_name());
	if (!myname_lower) {
		return;
	}
	strlower_m(myname_lower);

	principal = talloc_asprintf(ctx, "%s$@%s", myname_lower, lp_realm());
	if (!principal) {
		return;
	}

	/* Server negTokenInit (mech offerings) */
	spnego.type = SPNEGO_NEG_TOKEN_INIT;
	spnego.negTokenInit.mechTypes = talloc_array(ctx, const char *, 4);
#ifdef HAVE_KRB5
	spnego.negTokenInit.mechTypes[0] = talloc_strdup(ctx, OID_KERBEROS5_OLD);
	spnego.negTokenInit.mechTypes[1] = talloc_strdup(ctx, OID_KERBEROS5);
	spnego.negTokenInit.mechTypes[2] = talloc_strdup(ctx, OID_NTLMSSP);
	spnego.negTokenInit.mechTypes[3] = NULL;
#else
	spnego.negTokenInit.mechTypes[0] = talloc_strdup(ctx, OID_NTLMSSP);
	spnego.negTokenInit.mechTypes[1] = NULL;
#endif


	spnego.negTokenInit.mechListMIC = data_blob_talloc(ctx, principal,
						    strlen(principal));

	len = spnego_write_data(ctx, &token, &spnego);
	spnego_free_data(&spnego);

	if (len == -1) {
		DEBUG(1, ("Could not write SPNEGO data blob\n"));
		x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
		return;
	}

	reply_base64 = base64_encode_data_blob(talloc_tos(), token);
	x_fprintf(x_stdout, "TT %s *\n", reply_base64);

	TALLOC_FREE(reply_base64);
	data_blob_free(&token);
	DEBUG(10, ("sent SPNEGO negTokenInit\n"));
	return;
}

static void manage_gss_spnego_request(struct ntlm_auth_state *state,
					char *buf, int length)
{
	struct spnego_data request, response;
	DATA_BLOB token;
	DATA_BLOB raw_in_token = data_blob_null;
	DATA_BLOB raw_out_token = data_blob_null;
	NTSTATUS status;
	ssize_t len;
	TALLOC_CTX *ctx = talloc_tos();

	const char *unix_username = NULL;

	const char *reply_code;
	char       *reply_base64;
	char *reply_argument = NULL;
	char *supportedMech = NULL;

	if (strlen(buf) < 2) {
		DEBUG(1, ("SPENGO query [%s] invalid\n", buf));
		x_fprintf(x_stdout, "BH SPENGO query invalid\n");
		return;
	}

	if (strncmp(buf, "YR", 2) == 0) {
		TALLOC_FREE(state->gensec_security);
		TALLOC_FREE(state->spnego_mech);
		TALLOC_FREE(state->spnego_mech_oid);
	} else if (strncmp(buf, "KK", 2) == 0) {
		;
	} else {
		DEBUG(1, ("SPENGO query [%s] invalid\n", buf));
		x_fprintf(x_stdout, "BH SPENGO query invalid\n");
		return;
	}

	if ( (strlen(buf) == 2)) {

		/* no client data, get the negTokenInit offering
                   mechanisms */

		offer_gss_spnego_mechs();
		return;
	}

	/* All subsequent requests have a blob. This might be negTokenInit or negTokenTarg */

	if (strlen(buf) <= 3) {
		DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
		x_fprintf(x_stdout, "BH GSS-SPNEGO query invalid\n");
		return;
	}

	token = base64_decode_data_blob(buf + 3);

	if ((token.length >= 7)
	    && (strncmp((char *)token.data, "NTLMSSP", 7) == 0)) {
		char *reply;

		data_blob_free(&token);

		DEBUG(10, ("Could not parse GSS-SPNEGO, trying raw "
			   "ntlmssp\n"));

		manage_squid_ntlmssp_request_int(state, buf, length,
						 talloc_tos(), &reply);
		if (reply == NULL) {
			x_fprintf(x_stdout, "BH Out of memory\n");
			return;
		}

		if (strncmp(reply, "AF ", 3) == 0) {
			x_fprintf(x_stdout, "AF * %s\n", reply+3);
		} else {
			x_fprintf(x_stdout, "%s *\n", reply);
		}

		TALLOC_FREE(reply);
		return;
	}

	ZERO_STRUCT(request);
	len = spnego_read_data(ctx, token, &request);
	data_blob_free(&token);

	if (len == -1) {
		DEBUG(1, ("GSS-SPNEGO query [%s] invalid\n", buf));
		x_fprintf(x_stdout, "BH GSS-SPNEGO query invalid\n");
		return;
	}

	if (request.type == SPNEGO_NEG_TOKEN_INIT) {
#ifdef HAVE_KRB5
		int krb5_idx = -1;
#endif
		int ntlm_idx = -1;
		int used_idx = -1;
		int i;

		if (state->spnego_mech) {
			DEBUG(1, ("Client restarted SPNEGO with NegTokenInit "
				  "while mech[%s] was already negotiated\n",
				  state->spnego_mech));
			x_fprintf(x_stdout, "BH Client send NegTokenInit twice\n");
			return;
		}

		/* Second request from Client. This is where the
		   client offers its mechanism to use. */

		if ( (request.negTokenInit.mechTypes == NULL) ||
		     (request.negTokenInit.mechTypes[0] == NULL) ) {
			DEBUG(1, ("Client did not offer any mechanism\n"));
			x_fprintf(x_stdout, "BH Client did not offer any "
					    "mechanism\n");
			return;
		}

		status = NT_STATUS_UNSUCCESSFUL;
		for (i = 0; request.negTokenInit.mechTypes[i] != NULL; i++) {
			DEBUG(10,("got mech[%d][%s]\n",
				i, request.negTokenInit.mechTypes[i]));
#ifdef HAVE_KRB5
			if (strcmp(request.negTokenInit.mechTypes[i], OID_KERBEROS5_OLD) == 0) {
				krb5_idx = i;
				break;
			}
			if (strcmp(request.negTokenInit.mechTypes[i], OID_KERBEROS5) == 0) {
				krb5_idx = i;
				break;
			}
#endif
			if (strcmp(request.negTokenInit.mechTypes[i], OID_NTLMSSP) == 0) {
				ntlm_idx = i;
				break;
			}
		}

		used_idx = ntlm_idx;
#ifdef HAVE_KRB5
		if (krb5_idx != -1) {
			ntlm_idx = -1;
			used_idx = krb5_idx;
		}
#endif
		if (ntlm_idx > -1) {
			state->spnego_mech = talloc_strdup(state, "ntlmssp");
			if (state->spnego_mech == NULL) {
				x_fprintf(x_stdout, "BH Out of memory\n");
				return;
			}

			if (state->gensec_security) {
				DEBUG(1, ("Client wants a new NTLMSSP challenge, but "
					  "already got one\n"));
				x_fprintf(x_stdout, "BH Client wants a new "
						    "NTLMSSP challenge, but "
						    "already got one\n");
				TALLOC_FREE(state->gensec_security);
				return;
			}

			status = ntlm_auth_start_ntlmssp_server(state, &state->gensec_security);
			if (!NT_STATUS_IS_OK(status)) {
				x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
				return;
			}
		}

#ifdef HAVE_KRB5
		if (krb5_idx > -1) {
			state->spnego_mech = talloc_strdup(state, "krb5");
			if (state->spnego_mech == NULL) {
				x_fprintf(x_stdout, "BH Out of memory\n");
				return;
			}
		}
#endif
		if (used_idx > -1) {
			state->spnego_mech_oid = talloc_strdup(state,
				request.negTokenInit.mechTypes[used_idx]);
			if (state->spnego_mech_oid == NULL) {
				x_fprintf(x_stdout, "BH Out of memory\n");
				return;
			}
			supportedMech = talloc_strdup(ctx, state->spnego_mech_oid);
			if (supportedMech == NULL) {
				x_fprintf(x_stdout, "BH Out of memory\n");
				return;
			}

			status = NT_STATUS_MORE_PROCESSING_REQUIRED;
		} else {
			status = NT_STATUS_NOT_SUPPORTED;
		}
		if (used_idx == 0) {
			status = NT_STATUS_OK;
			raw_in_token = request.negTokenInit.mechToken;
		}
	} else {
		if (state->spnego_mech == NULL) {
			DEBUG(1,("Got netTokenTarg without negTokenInit\n"));
			x_fprintf(x_stdout, "BH Got a negTokenTarg without "
					    "negTokenInit\n");
			return;
		}

		if ((request.negTokenTarg.supportedMech != NULL) &&
		     (strcmp(request.negTokenTarg.supportedMech, state->spnego_mech_oid) != 0 ) ) {
			DEBUG(1, ("Got a negTokenTarg with mech[%s] while [%s] was already negotiated\n",
				  request.negTokenTarg.supportedMech,
				  state->spnego_mech_oid));
			x_fprintf(x_stdout, "BH Got a negTokenTarg with speficied mech\n");
			return;
		}

		status = NT_STATUS_OK;
		raw_in_token = request.negTokenTarg.responseToken;
	}

	if (!NT_STATUS_IS_OK(status)) {
		/* error or more processing */
	} else if (strcmp(state->spnego_mech, "ntlmssp") == 0) {

		DEBUG(10, ("got NTLMSSP packet:\n"));
		dump_data(10, raw_in_token.data, raw_in_token.length);

		status = gensec_update(state->gensec_security,
				       talloc_tos(), NULL,
				       raw_in_token,
				       &raw_out_token);
		if (NT_STATUS_IS_OK(status)) {
			struct auth_session_info *session_info;
			status = gensec_session_info(state->gensec_security, state->gensec_security, &session_info);
			if (!NT_STATUS_IS_OK(status)) {
				DEBUG(0, ("NTLMSSP BH: %s\n", nt_errstr(status)));
				TALLOC_FREE(state->gensec_security);
				return;
			}
			unix_username = session_info->unix_info->unix_name;
			DEBUG(10, ("NTLMSSP OK!\n"));
		}
		if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
			TALLOC_FREE(state->ntlmssp_state);
		}
#ifdef HAVE_KRB5
	} else if (strcmp(state->spnego_mech, "krb5") == 0) {
		char *principal;
		DATA_BLOB ap_rep;
		DATA_BLOB session_key;
		struct PAC_LOGON_INFO *logon_info = NULL;
		DATA_BLOB ticket;
		uint8_t tok_id[2];

		if (!spnego_parse_krb5_wrap(ctx, raw_in_token,
					    &ticket, tok_id)) {
			DEBUG(1, ("spnego_parse_krb5_wrap failed\n"));
			x_fprintf(x_stdout, "BH spnego_parse_krb5_wrap failed\n");
			return;
		}

		status = ads_verify_ticket(ctx, lp_realm(), 0,
					   &ticket,
					   &principal, &logon_info, &ap_rep,
					   &session_key, True);

		/* Now in "principal" we have the name we are authenticated as. */

		if (NT_STATUS_IS_OK(status)) {
			char *domain;
			char *user;
			domain = strchr_m(principal, '@');

			if (domain == NULL) {
				DEBUG(1, ("Did not get a valid principal "
					  "from ads_verify_ticket\n"));
				x_fprintf(x_stdout, "BH Did not get a "
					  "valid principal from "
					  "ads_verify_ticket\n");
				return;
			}

			*domain++ = '\0';
			domain = talloc_strdup(ctx, domain);
			user = talloc_strdup(ctx, principal);

			if (logon_info) {
				netsamlogon_cache_store(
					user, &logon_info->info3);
			}

			data_blob_free(&ap_rep);
			data_blob_free(&session_key);
			unix_username = talloc_asprintf(ctx, "%s\\%s", domain, user);
		}
		data_blob_free(&ticket);
#endif
	}

	spnego_free_data(&request);
	ZERO_STRUCT(response);
	response.type = SPNEGO_NEG_TOKEN_TARG;

	if (NT_STATUS_IS_OK(status)) {
		TALLOC_FREE(state->spnego_mech);
		TALLOC_FREE(state->spnego_mech_oid);
		response.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED;
		response.negTokenTarg.responseToken = raw_out_token;
		reply_code = "AF";
		reply_argument = unix_username;
	} else if (NT_STATUS_EQUAL(status,
				   NT_STATUS_MORE_PROCESSING_REQUIRED)) {
		response.negTokenTarg.supportedMech = supportedMech;
		response.negTokenTarg.responseToken = raw_out_token;
		response.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
		reply_code = "TT";
		reply_argument = talloc_strdup(ctx, "*");
	} else {
		TALLOC_FREE(state->spnego_mech);
		TALLOC_FREE(state->spnego_mech_oid);
		data_blob_free(&raw_out_token);
		response.negTokenTarg.negResult = SPNEGO_REJECT;
		reply_code = "NA";
		reply_argument = talloc_strdup(ctx, nt_errstr(status));
	}

	if (!reply_argument) {
		DEBUG(1, ("Could not write SPNEGO data blob\n"));
		x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
		spnego_free_data(&response);
		return;
	}

	len = spnego_write_data(ctx, &token, &response);
	spnego_free_data(&response);

	if (len == -1) {
		DEBUG(1, ("Could not write SPNEGO data blob\n"));
		x_fprintf(x_stdout, "BH Could not write SPNEGO data blob\n");
		return;
	}

	reply_base64 = base64_encode_data_blob(talloc_tos(), token);

	x_fprintf(x_stdout, "%s %s %s\n",
		  reply_code, reply_base64, reply_argument);

	TALLOC_FREE(reply_base64);
	data_blob_free(&token);

	return;
}

static struct ntlmssp_state *client_ntlmssp_state = NULL;

static bool manage_client_ntlmssp_init(struct spnego_data spnego)
{
	NTSTATUS status;
	DATA_BLOB null_blob = data_blob_null;
	DATA_BLOB to_server;
	char *to_server_base64;
	const char *my_mechs[] = {OID_NTLMSSP, NULL};
	TALLOC_CTX *ctx = talloc_tos();

	DEBUG(10, ("Got spnego negTokenInit with NTLMSSP\n"));

	if (client_ntlmssp_state != NULL) {
		DEBUG(1, ("Request for initial SPNEGO request where "
			  "we already have a state\n"));
		return False;
	}

	if (!client_ntlmssp_state) {
		if (!NT_STATUS_IS_OK(status = ntlm_auth_start_ntlmssp_client(&client_ntlmssp_state))) {
			x_fprintf(x_stdout, "BH %s\n", nt_errstr(status));
			return False;
		}
	}


	if (opt_password == NULL) {

		/* Request a password from the calling process.  After
		   sending it, the calling process should retry with
		   the negTokenInit. */

		DEBUG(10, ("Requesting password\n"));
		x_fprintf(x_stdout, "PW\n");
		return True;
	}

	spnego.type = SPNEGO_NEG_TOKEN_INIT;
	spnego.negTokenInit.mechTypes = my_mechs;
	spnego.negTokenInit.reqFlags = data_blob_null;
	spnego.negTokenInit.reqFlagsPadding = 0;
	spnego.negTokenInit.mechListMIC = null_blob;

	status = ntlmssp_update(client_ntlmssp_state, null_blob,
				       &spnego.negTokenInit.mechToken);

	if ( !(NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) ||
			NT_STATUS_IS_OK(status)) ) {
		DEBUG(1, ("Expected OK or MORE_PROCESSING_REQUIRED, got: %s\n",
			  nt_errstr(status)));
		TALLOC_FREE(client_ntlmssp_state);
		return False;
	}

	spnego_write_data(ctx, &to_server, &spnego);
	data_blob_free(&spnego.negTokenInit.mechToken);

	to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
	data_blob_free(&to_server);
	x_fprintf(x_stdout, "KK %s\n", to_server_base64);
	TALLOC_FREE(to_server_base64);
	return True;
}

static void manage_client_ntlmssp_targ(struct spnego_data spnego)
{
	NTSTATUS status;
	DATA_BLOB null_blob = data_blob_null;
	DATA_BLOB request;
	DATA_BLOB to_server;
	char *to_server_base64;
	TALLOC_CTX *ctx = talloc_tos();

	DEBUG(10, ("Got spnego negTokenTarg with NTLMSSP\n"));

	if (client_ntlmssp_state == NULL) {
		DEBUG(1, ("Got NTLMSSP tArg without a client state\n"));
		x_fprintf(x_stdout, "BH Got NTLMSSP tArg without a client state\n");
		return;
	}

	if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) {
		x_fprintf(x_stdout, "NA\n");
		TALLOC_FREE(client_ntlmssp_state);
		return;
	}

	if (spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_COMPLETED) {
		x_fprintf(x_stdout, "AF\n");
		TALLOC_FREE(client_ntlmssp_state);
		return;
	}

	status = ntlmssp_update(client_ntlmssp_state,
				       spnego.negTokenTarg.responseToken,
				       &request);

	if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
		DEBUG(1, ("Expected MORE_PROCESSING_REQUIRED from "
			  "ntlmssp_client_update, got: %s\n",
			  nt_errstr(status)));
		x_fprintf(x_stdout, "BH Expected MORE_PROCESSING_REQUIRED from "
				    "ntlmssp_client_update\n");
		data_blob_free(&request);
		TALLOC_FREE(client_ntlmssp_state);
		return;
	}

	spnego.type = SPNEGO_NEG_TOKEN_TARG;
	spnego.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE;
	spnego.negTokenTarg.supportedMech = (const char *)OID_NTLMSSP;
	spnego.negTokenTarg.responseToken = request;
	spnego.negTokenTarg.mechListMIC = null_blob;

	spnego_write_data(ctx, &to_server, &spnego);
	data_blob_free(&request);

	to_server_base64 = base64_encode_data_blob(talloc_tos(), to_server);
	data_blob_free(&to_server);
	x_fprintf(x_stdout, "KK %s\n", to_server_base64);
	TALLOC_FREE(to_server_base64);
	return;
}

#ifdef HAVE_KRB5

static bool manage_client_krb5_init(struct spnego_data spnego)
{
	char *principal;
	DATA_BLOB tkt, to_server;
	DATA_BLOB session_key_krb5 = data_blob_null;
	struct spnego_data reply;
	char *reply_base64;
	int retval;

	const char *my_mechs[] = {OID_KERBEROS5_OLD, NULL};
	ssize_t len;
	TALLOC_CTX *ctx = talloc_tos();

	if ( (spnego.negTokenInit.mechListMIC.data == NULL) ||
	     (spnego.negTokenInit.mechListMIC.length == 0) ) {
		DEBUG(1, ("Did not get a principal for krb5\n"));
		return False;
	}

	principal = (char *)SMB_MALLOC(
		spnego.negTokenInit.mechListMIC.length+1);

	if (principal == NULL) {
		DEBUG(1, ("Could not malloc principal\n"));
		return False;
	}

	memcpy(principal, spnego.negTokenInit.mechListMIC.data,
	       spnego.negTokenInit.mechListMIC.length);
	principal[spnego.negTokenInit.mechListMIC.length] = '\0';

	retval = cli_krb5_get_ticket(ctx, principal, 0,
					  &tkt, &session_key_krb5,
					  0, NULL, NULL, NULL);
	if (retval) {
		char *user = NULL;

		/* Let's try to first get the TGT, for that we need a
                   password. */

		if (opt_password == NULL) {
			DEBUG(10, ("Requesting password\n"));
			x_fprintf(x_stdout, "PW\n");
			return True;
		}

		user = talloc_asprintf(talloc_tos(), "%s@%s", opt_username, opt_domain);
		if (!user) {
			return false;
		}

		if ((retval = kerberos_kinit_password(user, opt_password, 0, NULL))) {
			DEBUG(10, ("Requesting TGT failed: %s\n", error_message(retval)));
			return False;
		}

		retval = cli_krb5_get_ticket(ctx, principal, 0,
						  &tkt, &session_key_krb5,
						  0, NULL, NULL, NULL);
		if (retval) {
			DEBUG(10, ("Kinit suceeded, but getting a ticket failed: %s\n", error_message(retval)));
			return False;
		}
	}

	data_blob_free(&session_key_krb5);

	ZERO_STRUCT(reply);

	reply.type = SPNEGO_NEG_TOKEN_INIT;
	reply.negTokenInit.mechTypes = my_mechs;
	reply.negTokenInit.reqFlags = data_blob_null;
	reply.negTokenInit.reqFlagsPadding = 0;
	reply.negTokenInit.mechToken = tkt;
	reply.negTokenInit.mechListMIC = data_blob_null;

	len = spnego_write_data(ctx, &to_server, &reply);
	data_blob_free(&tkt);

	if (len == -1) {
		DEBUG(1, ("Could not write SPNEGO data blob\n"));
		return False;
	}

	reply_base64 = base64_encode_data_blob(talloc_tos(), to_server);
	x_fprintf(x_stdout, "KK %s *\n", reply_base64);

	TALLOC_FREE(reply_base64);
	data_blob_free(&to_server);
	DEBUG(10, ("sent GSS-SPNEGO KERBEROS5 negTokenInit\n"));
	return True;
}

static void manage_client_krb5_targ(struct spnego_data spnego)
{
	switch (spnego.negTokenTarg.negResult) {
	case SPNEGO_ACCEPT_INCOMPLETE:
		DEBUG(1, ("Got a Kerberos negTokenTarg with ACCEPT_INCOMPLETE\n"));
		x_fprintf(x_stdout, "BH Got a Kerberos negTokenTarg with "
				    "ACCEPT_INCOMPLETE\n");
		break;
	case SPNEGO_ACCEPT_COMPLETED:
		DEBUG(10, ("Accept completed\n"));
		x_fprintf(x_stdout, "AF\n");
		break;
	case SPNEGO_REJECT:
		DEBUG(10, ("Rejected\n"));
		x_fprintf(x_stdout, "NA\n");
		break;
	default:
		DEBUG(1, ("Got an invalid negTokenTarg\n"));
		x_fprintf(x_stdout, "AF\n");
	}
}

#endif

static void manage_gss_spnego_client_request(struct ntlm_auth_state *state,
						char *buf, int length)
{
	DATA_BLOB request;
	struct spnego_data spnego;
	ssize_t len;
	TALLOC_CTX *ctx = talloc_tos();

	if (!opt_username || !*opt_username) {
		x_fprintf(x_stderr, "username must be specified!\n\n");
		exit(1);
	}

	if (strlen(buf) <= 3) {
		DEBUG(1, ("SPNEGO query [%s] too short\n", buf));
		x_fprintf(x_stdout, "BH SPNEGO query too short\n");
		return;
	}

	request = base64_decode_data_blob(buf+3);

	if (strncmp(buf, "PW ", 3) == 0) {

		/* We asked for a password and obviously got it :-) */

		opt_password = SMB_STRNDUP((const char *)request.data, request.length);

		if (opt_password == NULL) {
			DEBUG(1, ("Out of memory\n"));
			x_fprintf(x_stdout, "BH Out of memory\n");
			data_blob_free(&request);
			return;
		}

		x_fprintf(x_stdout, "OK\n");
		data_blob_free(&request);
		return;
	}

	if ( (strncmp(buf, "TT ", 3) != 0) &&
	     (strncmp(buf, "AF ", 3) != 0) &&
	     (strncmp(buf, "NA ", 3) != 0) ) {
		DEBUG(1, ("SPNEGO request [%s] invalid\n", buf));
		x_fprintf(x_stdout, "BH SPNEGO request invalid\n");
		data_blob_free(&request);
		return;
	}

	/* So we got a server challenge to generate a SPNEGO
           client-to-server request... */

	len = spnego_read_data(ctx, request, &spnego);
	data_blob_free(&request);

	if (len == -1) {
		DEBUG(1, ("Could not read SPNEGO data for [%s]\n", buf));
		x_fprintf(x_stdout, "BH Could not read SPNEGO data\n");
		return;
	}

	if (spnego.type == SPNEGO_NEG_TOKEN_INIT) {

		/* The server offers a list of mechanisms */

		const char **mechType = (const char **)spnego.negTokenInit.mechTypes;

		while (*mechType != NULL) {

#ifdef HAVE_KRB5
			if ( (strcmp(*mechType, OID_KERBEROS5_OLD) == 0) ||
			     (strcmp(*mechType, OID_KERBEROS5) == 0) ) {
				if (manage_client_krb5_init(spnego))
					goto out;
			}
#endif

			if (strcmp(*mechType, OID_NTLMSSP) == 0) {
				if (manage_client_ntlmssp_init(spnego))
					goto out;
			}

			mechType++;
		}

		DEBUG(1, ("Server offered no compatible mechanism\n"));
		x_fprintf(x_stdout, "BH Server offered no compatible mechanism\n");
		return;
	}

	if (spnego.type == SPNEGO_NEG_TOKEN_TARG) {

		if (spnego.negTokenTarg.supportedMech == NULL) {
			/* On accept/reject Windows does not send the
                           mechanism anymore. Handle that here and
                           shut down the mechanisms. */

			switch (spnego.negTokenTarg.negResult) {
			case SPNEGO_ACCEPT_COMPLETED:
				x_fprintf(x_stdout, "AF\n");
				break;
			case SPNEGO_REJECT:
				x_fprintf(x_stdout, "NA\n");
				break;
			default:
				DEBUG(1, ("Got a negTokenTarg with no mech and an "
					  "unknown negResult: %d\n",
					  spnego.negTokenTarg.negResult));
				x_fprintf(x_stdout, "BH Got a negTokenTarg with"
						    " no mech and an unknown "
						    "negResult\n");
			}

			TALLOC_FREE(client_ntlmssp_state);
			goto out;
		}

		if (strcmp(spnego.negTokenTarg.supportedMech,
			   OID_NTLMSSP) == 0) {
			manage_client_ntlmssp_targ(spnego);
			goto out;
		}

#if HAVE_KRB5
		if (strcmp(spnego.negTokenTarg.supportedMech,
			   OID_KERBEROS5_OLD) == 0) {
			manage_client_krb5_targ(spnego);
			goto out;
		}
#endif

	}

	DEBUG(1, ("Got an SPNEGO token I could not handle [%s]!\n", buf));
	x_fprintf(x_stdout, "BH Got an SPNEGO token I could not handle\n");
	return;

 out:
	spnego_free_data(&spnego);
	return;
}

static void manage_ntlm_server_1_request(struct ntlm_auth_state *state,
						char *buf, int length)
{
	char *request, *parameter;	
	static DATA_BLOB challenge;
	static DATA_BLOB lm_response;
	static DATA_BLOB nt_response;
	static char *full_username;
	static char *username;
	static char *domain;
	static char *plaintext_password;
	static bool ntlm_server_1_user_session_key;
	static bool ntlm_server_1_lm_session_key;

	if (strequal(buf, ".")) {
		if (!full_username && !username) {	
			x_fprintf(x_stdout, "Error: No username supplied!\n");
		} else if (plaintext_password) {
			/* handle this request as plaintext */
			if (!full_username) {
				if (asprintf(&full_username, "%s%c%s", domain, winbind_separator(), username) == -1) {
					x_fprintf(x_stdout, "Error: Out of memory in asprintf!\n.\n");
					return;
				}
			}
			if (check_plaintext_auth(full_username, plaintext_password, False)) {
				x_fprintf(x_stdout, "Authenticated: Yes\n");
			} else {
				x_fprintf(x_stdout, "Authenticated: No\n");
			}
		} else if (!lm_response.data && !nt_response.data) {
			x_fprintf(x_stdout, "Error: No password supplied!\n");
		} else if (!challenge.data) {	
			x_fprintf(x_stdout, "Error: No lanman-challenge supplied!\n");
		} else {
			char *error_string = NULL;
			uchar lm_key[8];
			uchar user_session_key[16];
			uint32 flags = 0;

			if (full_username && !username) {
				fstring fstr_user;
				fstring fstr_domain;

				if (!parse_ntlm_auth_domain_user(full_username, fstr_user, fstr_domain)) {
					/* username might be 'tainted', don't print into our new-line deleimianted stream */
					x_fprintf(x_stdout, "Error: Could not parse into domain and username\n");
				}
				SAFE_FREE(username);
				SAFE_FREE(domain);
				username = smb_xstrdup(fstr_user);
				domain = smb_xstrdup(fstr_domain);
			}

			if (!domain) {
				domain = smb_xstrdup(get_winbind_domain());
			}

			if (ntlm_server_1_lm_session_key) 
				flags |= WBFLAG_PAM_LMKEY;

			if (ntlm_server_1_user_session_key) 
				flags |= WBFLAG_PAM_USER_SESSION_KEY;

			if (!NT_STATUS_IS_OK(
				    contact_winbind_auth_crap(username, 
							      domain, 
							      lp_netbios_name(),
							      &challenge, 
							      &lm_response, 
							      &nt_response, 
							      flags, 0,
							      lm_key, 
							      user_session_key,
							      &error_string,
							      NULL))) {

				x_fprintf(x_stdout, "Authenticated: No\n");
				x_fprintf(x_stdout, "Authentication-Error: %s\n.\n", error_string);
			} else {
				static char zeros[16];
				char *hex_lm_key;
				char *hex_user_session_key;

				x_fprintf(x_stdout, "Authenticated: Yes\n");

				if (ntlm_server_1_lm_session_key 
				    && (memcmp(zeros, lm_key, 
					       sizeof(lm_key)) != 0)) {
					hex_lm_key = hex_encode_talloc(NULL,
								(const unsigned char *)lm_key,
								sizeof(lm_key));
					x_fprintf(x_stdout, "LANMAN-Session-Key: %s\n", hex_lm_key);
					TALLOC_FREE(hex_lm_key);
				}

				if (ntlm_server_1_user_session_key 
				    && (memcmp(zeros, user_session_key, 
					       sizeof(user_session_key)) != 0)) {
					hex_user_session_key = hex_encode_talloc(NULL,
									  (const unsigned char *)user_session_key, 
									  sizeof(user_session_key));
					x_fprintf(x_stdout, "User-Session-Key: %s\n", hex_user_session_key);
					TALLOC_FREE(hex_user_session_key);
				}
			}
			SAFE_FREE(error_string);
		}
		/* clear out the state */
		challenge = data_blob_null;
		nt_response = data_blob_null;
		lm_response = data_blob_null;
		SAFE_FREE(full_username);
		SAFE_FREE(username);
		SAFE_FREE(domain);
		SAFE_FREE(plaintext_password);
		ntlm_server_1_user_session_key = False;
		ntlm_server_1_lm_session_key = False;
		x_fprintf(x_stdout, ".\n");

		return;
	}

	request = buf;

	/* Indicates a base64 encoded structure */
	parameter = strstr_m(request, ":: ");
	if (!parameter) {
		parameter = strstr_m(request, ": ");

		if (!parameter) {
			DEBUG(0, ("Parameter not found!\n"));
			x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
			return;
		}

		parameter[0] ='\0';
		parameter++;
		parameter[0] ='\0';
		parameter++;

	} else {
		parameter[0] ='\0';
		parameter++;
		parameter[0] ='\0';
		parameter++;
		parameter[0] ='\0';
		parameter++;

		base64_decode_inplace(parameter);
	}

	if (strequal(request, "LANMAN-Challenge")) {
		challenge = strhex_to_data_blob(NULL, parameter);
		if (challenge.length != 8) {
			x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 8)\n.\n", 
				  parameter,
				  (int)challenge.length);
			challenge = data_blob_null;
		}
	} else if (strequal(request, "NT-Response")) {
		nt_response = strhex_to_data_blob(NULL, parameter);
		if (nt_response.length < 24) {
			x_fprintf(x_stdout, "Error: hex decode of %s failed! (only got %d bytes, needed at least 24)\n.\n", 
				  parameter,
				  (int)nt_response.length);
			nt_response = data_blob_null;
		}
	} else if (strequal(request, "LANMAN-Response")) {
		lm_response = strhex_to_data_blob(NULL, parameter);
		if (lm_response.length != 24) {
			x_fprintf(x_stdout, "Error: hex decode of %s failed! (got %d bytes, expected 24)\n.\n", 
				  parameter,
				  (int)lm_response.length);
			lm_response = data_blob_null;
		}
	} else if (strequal(request, "Password")) {
		plaintext_password = smb_xstrdup(parameter);
	} else if (strequal(request, "NT-Domain")) {
		domain = smb_xstrdup(parameter);
	} else if (strequal(request, "Username")) {
		username = smb_xstrdup(parameter);
	} else if (strequal(request, "Full-Username")) {
		full_username = smb_xstrdup(parameter);
	} else if (strequal(request, "Request-User-Session-Key")) {
		ntlm_server_1_user_session_key = strequal(parameter, "Yes");
	} else if (strequal(request, "Request-LanMan-Session-Key")) {
		ntlm_server_1_lm_session_key = strequal(parameter, "Yes");
	} else {
		x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
	}
}

static void manage_ntlm_change_password_1_request(struct ntlm_auth_state *state,
							char *buf, int length)
{
	char *request, *parameter;	
	static DATA_BLOB new_nt_pswd;
	static DATA_BLOB old_nt_hash_enc;
	static DATA_BLOB new_lm_pswd;
	static DATA_BLOB old_lm_hash_enc;
	static char *full_username = NULL;
	static char *username = NULL;
	static char *domain = NULL;
	static char *newpswd =  NULL;
	static char *oldpswd = NULL;

	if (strequal(buf, "."))	{
		if(newpswd && oldpswd) {
			uchar old_nt_hash[16];
			uchar old_lm_hash[16];
			uchar new_nt_hash[16];
			uchar new_lm_hash[16];

			new_nt_pswd = data_blob(NULL, 516);
			old_nt_hash_enc = data_blob(NULL, 16);

			/* Calculate the MD4 hash (NT compatible) of the
			 * password */
			E_md4hash(oldpswd, old_nt_hash);
			E_md4hash(newpswd, new_nt_hash);

			/* E_deshash returns false for 'long'
			   passwords (> 14 DOS chars).  

			   Therefore, don't send a buffer
			   encrypted with the truncated hash
			   (it could allow an even easier
			   attack on the password)

			   Likewise, obey the admin's restriction
			*/

			if (lp_client_lanman_auth() &&
			    E_deshash(newpswd, new_lm_hash) &&
			    E_deshash(oldpswd, old_lm_hash)) {
				new_lm_pswd = data_blob(NULL, 516);
				old_lm_hash_enc = data_blob(NULL, 16);
				encode_pw_buffer(new_lm_pswd.data, newpswd,
						 STR_UNICODE);

				arcfour_crypt(new_lm_pswd.data, old_nt_hash, 516);
				E_old_pw_hash(new_nt_hash, old_lm_hash,
					      old_lm_hash_enc.data);
			} else {
				new_lm_pswd.data = NULL;
				new_lm_pswd.length = 0;
				old_lm_hash_enc.data = NULL;
				old_lm_hash_enc.length = 0;
			}

			encode_pw_buffer(new_nt_pswd.data, newpswd,
					 STR_UNICODE);

			arcfour_crypt(new_nt_pswd.data, old_nt_hash, 516);
			E_old_pw_hash(new_nt_hash, old_nt_hash,
				      old_nt_hash_enc.data);
		}

		if (!full_username && !username) {	
			x_fprintf(x_stdout, "Error: No username supplied!\n");
		} else if ((!new_nt_pswd.data || !old_nt_hash_enc.data) &&
			   (!new_lm_pswd.data || old_lm_hash_enc.data) ) {
			x_fprintf(x_stdout, "Error: No NT or LM password "
				  "blobs supplied!\n");
		} else {
			char *error_string = NULL;

			if (full_username && !username)	{
				fstring fstr_user;
				fstring fstr_domain;

				if (!parse_ntlm_auth_domain_user(full_username,
								 fstr_user,
								 fstr_domain)) {
					/* username might be 'tainted', don't
					 * print into our new-line
					 * deleimianted stream */
					x_fprintf(x_stdout, "Error: Could not "
						  "parse into domain and "
						  "username\n");
					SAFE_FREE(username);
					username = smb_xstrdup(full_username);
				} else {
					SAFE_FREE(username);
					SAFE_FREE(domain);
					username = smb_xstrdup(fstr_user);
					domain = smb_xstrdup(fstr_domain);
				}

			}

			if(!NT_STATUS_IS_OK(contact_winbind_change_pswd_auth_crap(
						    username, domain,
						    new_nt_pswd,
						    old_nt_hash_enc,
						    new_lm_pswd,
						    old_lm_hash_enc,
						    &error_string))) {
				x_fprintf(x_stdout, "Password-Change: No\n");
				x_fprintf(x_stdout, "Password-Change-Error: "
					  "%s\n.\n", error_string);
			} else {
				x_fprintf(x_stdout, "Password-Change: Yes\n");
			}

			SAFE_FREE(error_string);
		}
		/* clear out the state */
		new_nt_pswd = data_blob_null;
		old_nt_hash_enc = data_blob_null;
		new_lm_pswd = data_blob_null;
		old_nt_hash_enc = data_blob_null;
		SAFE_FREE(full_username);
		SAFE_FREE(username);
		SAFE_FREE(domain);
		SAFE_FREE(newpswd);
		SAFE_FREE(oldpswd);
		x_fprintf(x_stdout, ".\n");

		return;
	}

	request = buf;

	/* Indicates a base64 encoded structure */
	parameter = strstr_m(request, ":: ");
	if (!parameter) {
		parameter = strstr_m(request, ": ");

		if (!parameter)	{
			DEBUG(0, ("Parameter not found!\n"));
			x_fprintf(x_stdout, "Error: Parameter not found!\n.\n");
			return;
		}

		parameter[0] ='\0';
		parameter++;
		parameter[0] ='\0';
		parameter++;
	} else {
		parameter[0] ='\0';
		parameter++;
		parameter[0] ='\0';
		parameter++;
		parameter[0] ='\0';
		parameter++;

		base64_decode_inplace(parameter);
	}

	if (strequal(request, "new-nt-password-blob")) {
		new_nt_pswd = strhex_to_data_blob(NULL, parameter);
		if (new_nt_pswd.length != 516) {
			x_fprintf(x_stdout, "Error: hex decode of %s failed! "
				  "(got %d bytes, expected 516)\n.\n", 
				  parameter,
				  (int)new_nt_pswd.length);
			new_nt_pswd = data_blob_null;
		}
	} else if (strequal(request, "old-nt-hash-blob")) {
		old_nt_hash_enc = strhex_to_data_blob(NULL, parameter);
		if (old_nt_hash_enc.length != 16) {
			x_fprintf(x_stdout, "Error: hex decode of %s failed! "
				  "(got %d bytes, expected 16)\n.\n", 
				  parameter,
				  (int)old_nt_hash_enc.length);
			old_nt_hash_enc = data_blob_null;
		}
	} else if (strequal(request, "new-lm-password-blob")) {
		new_lm_pswd = strhex_to_data_blob(NULL, parameter);
		if (new_lm_pswd.length != 516) {
			x_fprintf(x_stdout, "Error: hex decode of %s failed! "
				  "(got %d bytes, expected 516)\n.\n", 
				  parameter,
				  (int)new_lm_pswd.length);
			new_lm_pswd = data_blob_null;
		}
	}
	else if (strequal(request, "old-lm-hash-blob"))	{
		old_lm_hash_enc = strhex_to_data_blob(NULL, parameter);
		if (old_lm_hash_enc.length != 16)
		{
			x_fprintf(x_stdout, "Error: hex decode of %s failed! "
				  "(got %d bytes, expected 16)\n.\n", 
				  parameter,
				  (int)old_lm_hash_enc.length);
			old_lm_hash_enc = data_blob_null;
		}
	} else if (strequal(request, "nt-domain")) {
		domain = smb_xstrdup(parameter);
	} else if(strequal(request, "username")) {
		username = smb_xstrdup(parameter);
	} else if(strequal(request, "full-username")) {
		username = smb_xstrdup(parameter);
	} else if(strequal(request, "new-password")) {
		newpswd = smb_xstrdup(parameter);
	} else if (strequal(request, "old-password")) {
		oldpswd = smb_xstrdup(parameter);
	} else {
		x_fprintf(x_stdout, "Error: Unknown request %s\n.\n", request);
	}
}

static void manage_squid_request(struct ntlm_auth_state *state,
		stdio_helper_function fn)
{
	char *buf;
	char tmp[INITIAL_BUFFER_SIZE+1];
	int length, buf_size = 0;
	char *c;

	buf = talloc_strdup(state->mem_ctx, "");
	if (!buf) {
		DEBUG(0, ("Failed to allocate input buffer.\n"));
		x_fprintf(x_stderr, "ERR\n");
		exit(1);
	}

	do {

		/* this is not a typo - x_fgets doesn't work too well under
		 * squid */
		if (fgets(tmp, sizeof(tmp)-1, stdin) == NULL) {
			if (ferror(stdin)) {
				DEBUG(1, ("fgets() failed! dying..... errno=%d "
					  "(%s)\n", ferror(stdin),
					  strerror(ferror(stdin))));

				exit(1);
			}
			exit(0);
		}

		buf = talloc_strdup_append_buffer(buf, tmp);
		buf_size += INITIAL_BUFFER_SIZE;

		if (buf_size > MAX_BUFFER_SIZE) {
			DEBUG(2, ("Oversized message\n"));
			x_fprintf(x_stderr, "ERR\n");
			talloc_free(buf);
			return;
		}

		c = strchr(buf, '\n');
	} while (c == NULL);

	*c = '\0';
	length = c-buf;

	DEBUG(10, ("Got '%s' from squid (length: %d).\n",buf,length));

	if (buf[0] == '\0') {
		DEBUG(2, ("Invalid Request\n"));
		x_fprintf(x_stderr, "ERR\n");
		talloc_free(buf);
		return;
	}

	fn(state, buf, length);
	talloc_free(buf);
}


static void squid_stream(enum stdio_helper_mode stdio_mode, stdio_helper_function fn) {
	TALLOC_CTX *mem_ctx;
	struct ntlm_auth_state *state;

	/* initialize FDescs */
	x_setbuf(x_stdout, NULL);
	x_setbuf(x_stderr, NULL);

	mem_ctx = talloc_init("ntlm_auth");
	if (!mem_ctx) {
		DEBUG(0, ("squid_stream: Failed to create talloc context\n"));
		x_fprintf(x_stderr, "ERR\n");
		exit(1);
	}

	state = talloc_zero(mem_ctx, struct ntlm_auth_state);
	if (!state) {
		DEBUG(0, ("squid_stream: Failed to talloc ntlm_auth_state\n"));
		x_fprintf(x_stderr, "ERR\n");
		exit(1);
	}

	state->mem_ctx = mem_ctx;
	state->helper_mode = stdio_mode;

	while(1) {
		TALLOC_CTX *frame = talloc_stackframe();
		manage_squid_request(state, fn);
		TALLOC_FREE(frame);
	}
}


/* Authenticate a user with a challenge/response */

static bool check_auth_crap(void)
{
	NTSTATUS nt_status;
	uint32 flags = 0;
	char lm_key[8];
	char user_session_key[16];
	char *hex_lm_key;
	char *hex_user_session_key;
	char *error_string;
	static uint8 zeros[16];

	x_setbuf(x_stdout, NULL);

	if (request_lm_key) 
		flags |= WBFLAG_PAM_LMKEY;

	if (request_user_session_key) 
		flags |= WBFLAG_PAM_USER_SESSION_KEY;

	flags |= WBFLAG_PAM_NT_STATUS_SQUASH;

	nt_status = contact_winbind_auth_crap(opt_username, opt_domain, 
					      opt_workstation,
					      &opt_challenge, 
					      &opt_lm_response, 
					      &opt_nt_response, 
					      flags, 0,
					      (unsigned char *)lm_key, 
					      (unsigned char *)user_session_key, 
					      &error_string, NULL);

	if (!NT_STATUS_IS_OK(nt_status)) {
		x_fprintf(x_stdout, "%s (0x%x)\n", 
			  error_string,
			  NT_STATUS_V(nt_status));
		SAFE_FREE(error_string);
		return False;
	}

	if (request_lm_key 
	    && (memcmp(zeros, lm_key, 
		       sizeof(lm_key)) != 0)) {
		hex_lm_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)lm_key,
					sizeof(lm_key));
		x_fprintf(x_stdout, "LM_KEY: %s\n", hex_lm_key);
		TALLOC_FREE(hex_lm_key);
	}
	if (request_user_session_key 
	    && (memcmp(zeros, user_session_key, 
		       sizeof(user_session_key)) != 0)) {
		hex_user_session_key = hex_encode_talloc(talloc_tos(), (const unsigned char *)user_session_key, 
						  sizeof(user_session_key));
		x_fprintf(x_stdout, "NT_KEY: %s\n", hex_user_session_key);
		TALLOC_FREE(hex_user_session_key);
	}

        return True;
}

/* Main program */

enum {
	OPT_USERNAME = 1000,
	OPT_DOMAIN,
	OPT_WORKSTATION,
	OPT_CHALLENGE,
	OPT_RESPONSE,
	OPT_LM,
	OPT_NT,
	OPT_PASSWORD,
	OPT_LM_KEY,
	OPT_USER_SESSION_KEY,
	OPT_DIAGNOSTICS,
	OPT_REQUIRE_MEMBERSHIP,
	OPT_USE_CACHED_CREDS,
	OPT_PAM_WINBIND_CONF
};

 int main(int argc, const char **argv)
{
	TALLOC_CTX *frame = talloc_stackframe();
	int opt;
	static const char *helper_protocol;
	static int diagnostics;

	static const char *hex_challenge;
	static const char *hex_lm_response;
	static const char *hex_nt_response;

	poptContext pc;

	/* NOTE: DO NOT change this interface without considering the implications!
	   This is an external interface, which other programs will use to interact 
	   with this helper.
	*/

	/* We do not use single-letter command abbreviations, because they harm future 
	   interface stability. */

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{ "helper-protocol", 0, POPT_ARG_STRING, &helper_protocol, OPT_DOMAIN, "operate as a stdio-based helper", "helper protocol to use"},
 		{ "username", 0, POPT_ARG_STRING, &opt_username, OPT_USERNAME, "username"},
 		{ "domain", 0, POPT_ARG_STRING, &opt_domain, OPT_DOMAIN, "domain name"},
 		{ "workstation", 0, POPT_ARG_STRING, &opt_workstation, OPT_WORKSTATION, "workstation"},
 		{ "challenge", 0, POPT_ARG_STRING, &hex_challenge, OPT_CHALLENGE, "challenge (HEX encoded)"},
		{ "lm-response", 0, POPT_ARG_STRING, &hex_lm_response, OPT_LM, "LM Response to the challenge (HEX encoded)"},
		{ "nt-response", 0, POPT_ARG_STRING, &hex_nt_response, OPT_NT, "NT or NTLMv2 Response to the challenge (HEX encoded)"},
		{ "password", 0, POPT_ARG_STRING, &opt_password, OPT_PASSWORD, "User's plaintext password"},		
		{ "request-lm-key", 0, POPT_ARG_NONE, &request_lm_key, OPT_LM_KEY, "Retrieve LM session key"},
		{ "request-nt-key", 0, POPT_ARG_NONE, &request_user_session_key, OPT_USER_SESSION_KEY, "Retrieve User (NT) session key"},
		{ "use-cached-creds", 0, POPT_ARG_NONE, &use_cached_creds, OPT_USE_CACHED_CREDS, "Use cached credentials if no password is given"},
		{ "diagnostics", 0, POPT_ARG_NONE, &diagnostics,
		  OPT_DIAGNOSTICS,
		  "Perform diagnostics on the authentication chain"},
		{ "require-membership-of", 0, POPT_ARG_STRING, &require_membership_of, OPT_REQUIRE_MEMBERSHIP, "Require that a user be a member of this group (either name or SID) for authentication to succeed" },
		{ "pam-winbind-conf", 0, POPT_ARG_STRING, &opt_pam_winbind_conf, OPT_PAM_WINBIND_CONF, "Require that request must set WBFLAG_PAM_CONTACT_TRUSTDOM when krb5 auth is required" },
		POPT_COMMON_CONFIGFILE
		POPT_COMMON_VERSION
		POPT_TABLEEND
	};

	/* Samba client initialisation */
	load_case_tables();

	setup_logging("ntlm_auth", DEBUG_STDERR);

	/* Parse options */

	pc = poptGetContext("ntlm_auth", argc, argv, long_options, 0);

	/* Parse command line options */

	if (argc == 1) {
		poptPrintHelp(pc, stderr, 0);
		return 1;
	}

	while((opt = poptGetNextOpt(pc)) != -1) {
		/* Get generic config options like --configfile */
	}

	poptFreeContext(pc);

	if (!lp_load_global(get_dyn_CONFIGFILE())) {
		d_fprintf(stderr, "ntlm_auth: error opening config file %s. Error was %s\n",
			get_dyn_CONFIGFILE(), strerror(errno));
		exit(1);
	}

	pc = poptGetContext(NULL, argc, (const char **)argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);

	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_CHALLENGE:
			opt_challenge = strhex_to_data_blob(NULL, hex_challenge);
			if (opt_challenge.length != 8) {
				x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
					  hex_challenge,
					  (int)opt_challenge.length);
				exit(1);
			}
			break;
		case OPT_LM: 
			opt_lm_response = strhex_to_data_blob(NULL, hex_lm_response);
			if (opt_lm_response.length != 24) {
				x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
					  hex_lm_response,
					  (int)opt_lm_response.length);
				exit(1);
			}
			break;

		case OPT_NT: 
			opt_nt_response = strhex_to_data_blob(NULL, hex_nt_response);
			if (opt_nt_response.length < 24) {
				x_fprintf(x_stderr, "hex decode of %s failed! (only got %d bytes)\n", 
					  hex_nt_response,
					  (int)opt_nt_response.length);
				exit(1);
			}
			break;

                case OPT_REQUIRE_MEMBERSHIP:
			if (strncasecmp_m("S-", require_membership_of, 2) == 0) {
				require_membership_of_sid = require_membership_of;
			}
			break;
		}
	}

	if (opt_username) {
		char *domain = SMB_STRDUP(opt_username);
		char *p = strchr_m(domain, *lp_winbind_separator());
		if (p) {
			opt_username = p+1;
			*p = '\0';
			if (opt_domain && !strequal(opt_domain, domain)) {
				x_fprintf(x_stderr, "Domain specified in username (%s) "
					"doesn't match specified domain (%s)!\n\n",
					domain, opt_domain);
				poptPrintHelp(pc, stderr, 0);
				exit(1);
			}
			opt_domain = domain;
		} else {
			SAFE_FREE(domain);
		}
	}

	/* Note: if opt_domain is "" then send no domain */
	if (opt_domain == NULL) {
		opt_domain = get_winbind_domain();
	}

	if (opt_workstation == NULL) {
		opt_workstation = "";
	}

	if (helper_protocol) {
		int i;
		for (i=0; i<NUM_HELPER_MODES; i++) {
			if (strcmp(helper_protocol, stdio_helper_protocols[i].name) == 0) {
				squid_stream(stdio_helper_protocols[i].mode, stdio_helper_protocols[i].fn);
				exit(0);
			}
		}
		x_fprintf(x_stderr, "unknown helper protocol [%s]\n\nValid helper protools:\n\n", helper_protocol);

		for (i=0; i<NUM_HELPER_MODES; i++) {
			x_fprintf(x_stderr, "%s\n", stdio_helper_protocols[i].name);
		}

		exit(1);
	}

	if (!opt_username || !*opt_username) {
		x_fprintf(x_stderr, "username must be specified!\n\n");
		poptPrintHelp(pc, stderr, 0);
		exit(1);
	}

	if (opt_challenge.length) {
		if (!check_auth_crap()) {
			exit(1);
		}
		exit(0);
	} 

	if (!opt_password) {
		opt_password = getpass("password: ");
	}

	if (diagnostics) {
		if (!diagnose_ntlm_auth()) {
			return 1;
		}
	} else {
		fstring user;

		fstr_sprintf(user, "%s%c%s", opt_domain, winbind_separator(), opt_username);
		if (!check_plaintext_auth(user, opt_password, True)) {
			return 1;
		}
	}

	/* Exit code */

	poptFreeContext(pc);
	TALLOC_FREE(frame);
	return 0;
}