summaryrefslogtreecommitdiffstats
path: root/private/nw/rdr/ndslogin.c
blob: 953a4a4d2b4e34dc4e14a72828e26b08ac3b16d3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
/*++

Copyright (c) 1995  Microsoft Corporation

Module Name:

    NdsLogin.c

Abstract:

    This file implements the functionality required to
    perform an NDS login.

Author:

    Cory West    [CoryWest]    23-Feb-1995

Revision History:

--*/

#include "Procs.h"

#define Dbg (DEBUG_TRACE_NDS)

//
// Pageable.
//

#pragma alloc_text( PAGE, NdsCanonUserName )
#pragma alloc_text( PAGE, NdsCheckCredentials )
#pragma alloc_text( PAGE, NdsCheckCredentialsEx )
#pragma alloc_text( PAGE, NdsLookupCredentials )
#pragma alloc_text( PAGE, NdsGetCredentials )
#pragma alloc_text( PAGE, DoNdsLogon )
#pragma alloc_text( PAGE, BeginLogin )
#pragma alloc_text( PAGE, FinishLogin )
#pragma alloc_text( PAGE, ChangeNdsPassword )
#pragma alloc_text( PAGE, NdsServerAuthenticate )
#pragma alloc_text( PAGE, BeginAuthenticate )
#pragma alloc_text( PAGE, NdsLicenseConnection )
#pragma alloc_text( PAGE, NdsUnlicenseConnection )
#pragma alloc_text( PAGE, NdsGetBsafeKey )

//
// Note pageable:
//
// NdsTreeLogin (holds a spin lock)
// NdsLogoff (holds a spin lock)
//

VOID
Shuffle(
    UCHAR *achObjectId,
    UCHAR *szUpperPassword,
    int   iPasswordLen,
    UCHAR *achOutputBuffer
);

NTSTATUS
NdsCanonUserName(
    IN PNDS_SECURITY_CONTEXT pNdsContext,
    IN PUNICODE_STRING puUserName,
    IN OUT PUNICODE_STRING puCanonUserName
)
/*+++

    Canonicalize the user name for the given tree and
    current connection state.  Canonicalization includes
    handling the correct context and cleaning off all
    the X500 prefixes.

    ALERT! The credential list must be held (shared or
    exclusive) while this function is called.

---*/
{

    NTSTATUS Status = STATUS_SUCCESS;

    USHORT CurrentTargetIndex;
    int PrefixBytes;

    UNICODE_STRING UnstrippedName;
    PWCHAR CanonBuffer;

    PAGED_CODE();

    CanonBuffer = ALLOCATE_POOL( PagedPool, MAX_NDS_NAME_SIZE );
    if ( !CanonBuffer ) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // If the name starts with a dot, it's referenced from the root
    // of the tree and we should not append the context.  We should,
    // however, strip off the leading dot so that name resolution
    // will work.
    //

    if ( puUserName->Buffer[0] == L'.' ) {

        UnstrippedName.Length = puUserName->Length - sizeof( WCHAR );
        UnstrippedName.MaximumLength = UnstrippedName.Length;
        UnstrippedName.Buffer = &(puUserName->Buffer[1]);

        goto StripPrefixes;
    }

    //
    // If the name contains any dots, it's qualified and we
    // should probably just use it as is.
    //

    CurrentTargetIndex= 0;

    while ( CurrentTargetIndex< ( puUserName->Length / sizeof( WCHAR ) ) ) {

        if ( puUserName->Buffer[CurrentTargetIndex] == L'.' ) {

            UnstrippedName.Length = puUserName->Length;
            UnstrippedName.MaximumLength = puUserName->Length;
            UnstrippedName.Buffer = puUserName->Buffer;

            goto StripPrefixes;
        }

        CurrentTargetIndex++;
    }

    //
    // If we have a context for this tree and the name isn't
    // qualified, we should append the context.
    //

    if ( pNdsContext->CurrentContext.Length ) {

        if ( ( puUserName->Length +
             pNdsContext->CurrentContext.Length ) >= MAX_NDS_NAME_SIZE ) {

            DebugTrace( 0, Dbg, "NDS canon name too long.\n", 0 );
            Status = STATUS_INVALID_PARAMETER;
            goto ExitWithCleanup;
        }

        RtlCopyMemory( CanonBuffer, puUserName->Buffer, puUserName->Length );
        CanonBuffer[puUserName->Length / sizeof( WCHAR )] = L'.';

        RtlCopyMemory( ((BYTE *)CanonBuffer) + puUserName->Length + sizeof( WCHAR ),
                       pNdsContext->CurrentContext.Buffer,
                       pNdsContext->CurrentContext.Length );

        UnstrippedName.Length = puUserName->Length +
                                pNdsContext->CurrentContext.Length +
                                sizeof( WCHAR );
        UnstrippedName.MaximumLength = MAX_NDS_NAME_SIZE;
        UnstrippedName.Buffer = CanonBuffer;

        goto StripPrefixes;

    }

    //
    // It wasn't qualified, nor was there a context to append, so fail it.
    //

    DebugTrace( 0, Dbg, "The name %wZ is not canonicalizable.\n", puUserName );
    Status = STATUS_UNSUCCESSFUL;
    goto ExitWithCleanup;

StripPrefixes:

    //
    // All of these indexes are in BYTES, not WCHARS!
    //

    CurrentTargetIndex = 0;
    PrefixBytes = 0;
    puCanonUserName->Length = 0;

    while ( ( CurrentTargetIndex < UnstrippedName.Length ) &&
            ( puCanonUserName->Length < puCanonUserName->MaximumLength ) ) {

        //
        // Strip off the X.500 prefixes.
        //

        if ( UnstrippedName.Buffer[CurrentTargetIndex / sizeof( WCHAR )] == L'=' ) {

            CurrentTargetIndex += sizeof( WCHAR );
            puCanonUserName->Length -= PrefixBytes;
            PrefixBytes = 0;

            continue;
        }

        puCanonUserName->Buffer[puCanonUserName->Length / sizeof( WCHAR )] =
            UnstrippedName.Buffer[CurrentTargetIndex / sizeof( WCHAR )];

        puCanonUserName->Length += sizeof( WCHAR );
        CurrentTargetIndex += sizeof( WCHAR );

        if ( UnstrippedName.Buffer[CurrentTargetIndex / sizeof( WCHAR )] == L'.' ) {
            PrefixBytes = 0;
            PrefixBytes -= sizeof( WCHAR );
        } else {
            PrefixBytes += sizeof( WCHAR );
        }
    }

   DebugTrace( 0, Dbg, "Canonicalized name: %wZ\n", puCanonUserName );

ExitWithCleanup:

   FREE_POOL( CanonBuffer );
   return Status;
}

NTSTATUS
NdsCheckCredentials(
    IN PIRP_CONTEXT pIrpContext,
    IN PUNICODE_STRING puUserName,
    IN PUNICODE_STRING puPassword
)
/*++

    Given a set of credentials and a username and password,
    we need to determine if username and password match those
    that were used to acquire the credentials.

--*/
{

    NTSTATUS Status;
    PLOGON pLogon;
    PNONPAGED_SCB pNpScb;
    PSCB pScb;
    PNDS_SECURITY_CONTEXT pCredentials;

    PAGED_CODE();

    //
    // Grab the user's LOGON structure and credentials.
    //

    pNpScb = pIrpContext->pNpScb;
    pScb = pNpScb->pScb;

    NwAcquireExclusiveRcb( &NwRcb, TRUE );
    pLogon = FindUser( &pScb->UserUid, FALSE );
    NwReleaseRcb( &NwRcb );

    if ( !pLogon ) {
        DebugTrace( 0, Dbg, "Invalid client security context in NdsCheckCredentials.\n", 0 );
        return STATUS_ACCESS_DENIED;
    }

    Status = NdsLookupCredentials( &pScb->NdsTreeName,
                                   pLogon,
                                   &pCredentials,
                                   CREDENTIAL_READ,
                                   FALSE );

    if( NT_SUCCESS( Status ) ) {

        if ( pCredentials->CredentialLocked ) {

            Status = STATUS_DEVICE_BUSY;

        } else {

            Status = NdsCheckCredentialsEx( pIrpContext,
                                            pLogon,
                                            pCredentials,
                                            puUserName,
                                            puPassword );

        }

        NwReleaseCredList( pLogon );
    }

    return Status;

}

NTSTATUS
NdsCheckCredentialsEx(
    IN PIRP_CONTEXT pIrpContext,
    IN PLOGON pLogon,
    IN PNDS_SECURITY_CONTEXT pNdsContext,
    IN PUNICODE_STRING puUserName,
    IN PUNICODE_STRING puPassword
)
/*++

    Given a set of credentials and a username and password,
    we need to determine if username and password match those
    that were used to acquire the credentials.

    ALERT!  The credential list must be held (either shared or
    exclusive) while this function is called.

--*/
{

    NTSTATUS Status = STATUS_SUCCESS;

    UNICODE_STRING CredentialName;

    UNICODE_STRING CanonCredentialName, CanonUserName;
    PWCHAR CredNameBuffer;
    PWCHAR UserNameBuffer;

    UNICODE_STRING StoredPassword;
    PWCHAR Stored;

    PAGED_CODE();

    //
    // If we haven't logged into to the tree, there is no security
    // conflict.  Otherwise, run the check.
    //

    ASSERT ( pNdsContext->Credential != NULL );

    CredNameBuffer = ALLOCATE_POOL( PagedPool,
                                    ( 2 * MAX_NDS_NAME_SIZE ) +
                                    ( MAX_PW_CHARS * sizeof( WCHAR ) ) );
    if ( !CredNameBuffer ) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    UserNameBuffer = (PWCHAR) (((BYTE *)CredNameBuffer) + MAX_NDS_NAME_SIZE );
    Stored = (PWCHAR) (((BYTE *)UserNameBuffer) + MAX_NDS_NAME_SIZE );

    if ( puUserName && puUserName->Length ) {

        //
        // Canon the incoming name and the credential name.
        //

        CanonUserName.Length = 0;
        CanonUserName.MaximumLength = MAX_NDS_NAME_SIZE;
        CanonUserName.Buffer = UserNameBuffer;

        Status = NdsCanonUserName( pNdsContext,
                                   puUserName,
                                   &CanonUserName );

        if ( !NT_SUCCESS( Status )) {
            Status = STATUS_NETWORK_CREDENTIAL_CONFLICT;
            goto ExitWithCleanup;
        }

        CanonCredentialName.Length = 0;
        CanonCredentialName.MaximumLength = MAX_NDS_NAME_SIZE;
        CanonCredentialName.Buffer = CredNameBuffer;

        CredentialName.Length = (USHORT)pNdsContext->Credential->userNameLength - sizeof( WCHAR );
        CredentialName.MaximumLength = CredentialName.Length;
        CredentialName.Buffer = (PWCHAR)( (PBYTE)(pNdsContext->Credential) +
                                          sizeof( NDS_CREDENTIAL ) );

        Status = NdsCanonUserName( pNdsContext,
                                   &CredentialName,
                                   &CanonCredentialName );

        if ( !NT_SUCCESS( Status )) {
            Status = STATUS_NETWORK_CREDENTIAL_CONFLICT;
            goto ExitWithCleanup;
        }

        //
        // See if they match.
        //

        if ( RtlCompareUnicodeString( &CanonUserName, &CanonCredentialName, TRUE )) {
            DebugTrace( 0, Dbg, "NdsCheckCredentialsEx: user name conflict.\n", 0 );
            Status = STATUS_NETWORK_CREDENTIAL_CONFLICT;
            goto ExitWithCleanup;
        }
    }

    if ( puPassword && puPassword->Length ) {

        //
        // Now check the password.
        //

        StoredPassword.Length = 0;
        StoredPassword.MaximumLength = MAX_PW_CHARS * sizeof( WCHAR );
        StoredPassword.Buffer = Stored;

        RtlOemStringToUnicodeString( &StoredPassword,
                                     &pNdsContext->Password,
                                     FALSE );

        if ( RtlCompareUnicodeString( puPassword,
                                      &StoredPassword,
                                      TRUE ) ) {
            DebugTrace( 0, Dbg, "NdsCheckCredentialsEx: password conflict.\n", 0 );
            Status = STATUS_WRONG_PASSWORD;
            goto ExitWithCleanup;
        }
    }

ExitWithCleanup:

    FREE_POOL( CredNameBuffer );
    return Status;
}

NTSTATUS
NdsLookupCredentials(
    IN PUNICODE_STRING puTreeName,
    IN PLOGON pLogon,
    OUT PNDS_SECURITY_CONTEXT *ppCredentials,
    DWORD dwDesiredAccess,
    BOOLEAN fCreate
)
/*+++

    Retrieve the nds credentials for the given tree from the
    list of valid credentials for the specified user.

    puTreeName      - The name of the tree that we want credentials for.  If NULL
                      is specified, we return the credentials for the default tree.
    pLogon          - The logon structure for the user we want to access the tree.
    ppCredentials   - Where to put the pointed to the credentials.
    dwDesiredAccess - CREDENTIAL_READ if we want read/only access, CREDENTIAL_WRITE
                      if we're going to change the credentials.
    fCreate         - If the credentials don't exist, should we create them?

    We return the credentials with the list held in the appropriate mode.  The
    caller is responsible for releasing the list when done with the credentials.

---*/
{

    NTSTATUS Status;

    PLIST_ENTRY pFirst, pNext;
    PNDS_SECURITY_CONTEXT pNdsContext;

    PAGED_CODE();


    //
    // Check for existing credentials.
    //

    if ( dwDesiredAccess == CREDENTIAL_READ ) {
        NwAcquireSharedCredList( pLogon );
    } else {
        NwAcquireExclusiveCredList( pLogon );
    }

    pFirst = &pLogon->NdsCredentialList;
    pNext = pLogon->NdsCredentialList.Flink;

    while ( pNext && ( pFirst != pNext ) ) {

        pNdsContext = (PNDS_SECURITY_CONTEXT)
                      CONTAINING_RECORD( pNext,
                                         NDS_SECURITY_CONTEXT,
                                         Next );

        ASSERT( pNdsContext->ntc == NW_NTC_NDS_CREDENTIAL );

        if ( !puTreeName ||
             !RtlCompareUnicodeString( puTreeName,
                                       &pNdsContext->NdsTreeName,
                                       TRUE ) ) {

            //
            // If the tree name is null, we'll return the first one
            // on the list.  Otherwise this will work as normal.
            //

            *ppCredentials = pNdsContext;
            return STATUS_SUCCESS;
        }

    pNext = pNdsContext->Next.Flink;

    }

    //
    // We didn't find the credential.  Should we create it?
    //

    NwReleaseCredList( pLogon );

    if ( !fCreate || !puTreeName ) {
        return STATUS_UNSUCCESSFUL;
    }

    //
    // Acquire exclusive since we're mucking with the list.
    //

    NwAcquireExclusiveCredList( pLogon );

    pNdsContext = ( PNDS_SECURITY_CONTEXT )
        ALLOCATE_POOL( PagedPool, sizeof( NDS_SECURITY_CONTEXT ) );

    if ( !pNdsContext ) {

        DebugTrace( 0, Dbg, "Out of memory in NdsLookupCredentials.\n", 0 );
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto UnlockAndExit;
    }

    //
    // Initialize the structure.
    //

    RtlZeroMemory( pNdsContext, sizeof( NDS_SECURITY_CONTEXT ) );
    pNdsContext->ntc = NW_NTC_NDS_CREDENTIAL;
    pNdsContext->nts = sizeof( NDS_SECURITY_CONTEXT );

    //
    // Initialize the tree name.
    //

    pNdsContext->NdsTreeName.MaximumLength = sizeof( pNdsContext->NdsTreeNameBuffer );
    pNdsContext->NdsTreeName.Buffer = pNdsContext->NdsTreeNameBuffer;

    RtlCopyUnicodeString( &pNdsContext->NdsTreeName, puTreeName );

    //
    // Initialize the context buffer.
    //

    pNdsContext->CurrentContext.Length = 0;
    pNdsContext->CurrentContext.MaximumLength = sizeof( pNdsContext->CurrentContextString );
    pNdsContext->CurrentContext.Buffer = pNdsContext->CurrentContextString;

    //
    // Insert the context into the list.
    //

    InsertHeadList( &pLogon->NdsCredentialList, &pNdsContext->Next );
    *ppCredentials = pNdsContext;

    //
    // Release and re-acquire with the correct permissions.
    //

    NwReleaseCredList( pLogon );

    if ( dwDesiredAccess == CREDENTIAL_READ ) {
        NwAcquireSharedCredList( pLogon );
    } else {
        NwAcquireExclusiveCredList( pLogon );
    }

    //
    // There's no chance that someone's going to come in during this
    // small window and do a logout because there's no login data
    // in the credentials.
    //

    return STATUS_SUCCESS;

UnlockAndExit:

    NwReleaseCredList( pLogon );
    return STATUS_UNSUCCESSFUL;

}

NTSTATUS
NdsGetCredentials(
    IN PIRP_CONTEXT pIrpContext,
    IN PLOGON pLogon,
    IN PUNICODE_STRING puUserName,
    IN PUNICODE_STRING puPassword
)
/*++

    Do an NDS tree login and aquire a valid set of credentials.

--*/
{
    NTSTATUS Status;

    USHORT i;
    UNICODE_STRING LoginName, LoginPassword;
    PWCHAR NdsName;
    PWCHAR NdsPassword;

    OEM_STRING OemPassword;
    PBYTE OemPassBuffer;
    PNDS_SECURITY_CONTEXT pNdsContext;

    PAGED_CODE();

    //
    // Prepare our login name by canonicalizing the supplied user
    // name or using a default user name if appropriate.
    //

    NdsName = ALLOCATE_POOL( PagedPool, MAX_NDS_NAME_SIZE +
                                        MAX_PW_CHARS * sizeof( WCHAR ) +
                                        MAX_PW_CHARS );

    if ( !NdsName ) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    NdsPassword = (PWCHAR) (((BYTE *) NdsName) + MAX_NDS_NAME_SIZE );
    OemPassBuffer = ((BYTE *) NdsPassword ) + ( MAX_PW_CHARS * sizeof( WCHAR ) );

    LoginName.Length = 0;
    LoginName.MaximumLength = MAX_NDS_NAME_SIZE;
    LoginName.Buffer = NdsName;

    Status = NdsLookupCredentials( &pIrpContext->pScb->NdsTreeName,
                                   pLogon,
                                   &pNdsContext,
                                   CREDENTIAL_READ,
                                   TRUE );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    //
    // If the credential list is locked, someone is logging
    // out and we have to fail the request.
    //

    if ( pNdsContext->CredentialLocked ) {

        Status = STATUS_DEVICE_BUSY;
        NwReleaseCredList( pLogon );
        goto ExitWithCleanup;
    }

    //
    // Fix up the user name.
    // ALERT! We are holding the credential list!
    //

    if ( puUserName && puUserName->Buffer ) {

        Status = NdsCanonUserName( pNdsContext,
                                   puUserName,
                                   &LoginName );

        if ( !NT_SUCCESS( Status )) {
            Status = STATUS_NO_SUCH_USER;
        }

    } else {

        //
        // There's no name, so try the default name in the
        // current context.
        //

        if ( pNdsContext->CurrentContext.Length > 0 ) {

            //
            // Make sure the lengths fit and all that.
            //

            if ( ( pLogon->UserName.Length +
                 pNdsContext->CurrentContext.Length ) >= LoginName.MaximumLength ) {

                Status = STATUS_INVALID_PARAMETER;
                goto NameResolved;
            }

            RtlCopyMemory( LoginName.Buffer, pLogon->UserName.Buffer, pLogon->UserName.Length );
            LoginName.Buffer[pLogon->UserName.Length / sizeof( WCHAR )] = L'.';

            RtlCopyMemory( ((BYTE *)LoginName.Buffer) + pLogon->UserName.Length + sizeof( WCHAR ),
                           pNdsContext->CurrentContext.Buffer,
                           pNdsContext->CurrentContext.Length );

            LoginName.Length = pLogon->UserName.Length +
                               pNdsContext->CurrentContext.Length +
                               sizeof( WCHAR );

            DebugTrace( 0, Dbg, "Using default name and context for login: %wZ\n", &LoginName );

        } else {
            Status = STATUS_NO_SUCH_USER;
        }

    }

NameResolved:

    NwReleaseCredList( pLogon );

    //
    // RELAX! The credential list is free.
    //

    if ( !NT_SUCCESS( Status ) ) {
        DebugTrace( 0, Dbg, "No name in NdsGetCredentials.\n", 0 );
        goto ExitWithCleanup;
    }

    //
    // If there's a password, use it.  Otherwise, use the default password.
    //

    if ( puPassword && puPassword->Buffer ) {

        LoginPassword.Length = puPassword->Length;
        LoginPassword.MaximumLength = puPassword->MaximumLength;
        LoginPassword.Buffer = puPassword->Buffer;

    } else {

        LoginPassword.Length = 0;
        LoginPassword.MaximumLength = MAX_PW_CHARS * sizeof( WCHAR );
        LoginPassword.Buffer = NdsPassword;

        RtlCopyUnicodeString( &LoginPassword,
                              &pLogon->PassWord );
    }

    //
    // Convert the password to upcase OEM and login.
    //

    OemPassword.Length = 0;
    OemPassword.MaximumLength = MAX_PW_CHARS;
    OemPassword.Buffer = OemPassBuffer;

    Status = RtlUpcaseUnicodeStringToOemString( &OemPassword,
                                                &LoginPassword,
                                                FALSE );

    if ( !NT_SUCCESS( Status )) {
        Status = STATUS_WRONG_PASSWORD;
        goto ExitWithCleanup;
    }

    Status = NdsTreeLogin( pIrpContext, &LoginName, &OemPassword, NULL, pLogon );

ExitWithCleanup:

   FREE_POOL( NdsName );
   return Status;
}

NTSTATUS
DoNdsLogon(
    IN PIRP_CONTEXT pIrpContext,
    IN PUNICODE_STRING UserName,
    IN PUNICODE_STRING Password
)
/*+++

Description:

    This is the lead function for handling login and authentication to
    Netware Directory Services.  This function acquires credentials to
    the appropriate tree for the server that the irp context points to,
    logging us into that tree if necessary, and authenticates us to the
    current server.

    BUGBUG: This routine gets called from reconnect attempts and from
    normal requests.  Since the allowable actions on each of these paths
    are different, it might make sense to have two routines, each
    more maintainable than this single routine.  For now, watch out for
    code in the RECONNECT_ATTEMPT cases.

Arguments:

    pIrpContext - irp context; must refer to appropriate server
    UserName    - login username
    Password    - password

--*/
{

    NTSTATUS Status;
    PLOGON pLogon;
    PNDS_SECURITY_CONTEXT pCredentials;
    PSCB pScb;
    UNICODE_STRING BinderyName;
    UNICODE_STRING uUserName;
    UNICODE_STRING NtGroup;
    USHORT Length;
    PSCB pOriginalServer = NULL;
    DWORD UserOID;

    BOOL AtHeadOfQueue = FALSE;
    BOOL HoldingCredentialResource = FALSE;
    BOOL PasswordExpired = FALSE;

    PAGED_CODE();

    //
    // Get to the head of the queue if we need to.
    //

    if ( BooleanFlagOn( pIrpContext->Flags, IRP_FLAG_RECONNECT_ATTEMPT ) ) {
        ASSERT( pIrpContext->pNpScb->Requests.Flink == &pIrpContext->NextRequest );
    } else {
        NwAppendToQueueAndWait( pIrpContext );
    }

    AtHeadOfQueue = TRUE;

    //
    // Grab the user's logon structure.
    //

    pScb = pIrpContext->pScb;

    NwAcquireExclusiveRcb( &NwRcb, TRUE );
    pLogon = FindUser( &pScb->UserUid, FALSE );
    NwReleaseRcb( &NwRcb );

    if ( !pLogon ) {

        DebugTrace( 0, Dbg, "Invalid client security context.\n", 0 );
        Status = STATUS_ACCESS_DENIED;
        goto ExitWithCleanup;
    }

    //
    // Login and then re-get the tree credentials.
    //

    Status = NdsLookupCredentials( &pScb->NdsTreeName,
                                   pLogon,
                                   &pCredentials,
                                   CREDENTIAL_READ,
                                   FALSE );

    if ( !NT_SUCCESS( Status ) ) {
       HoldingCredentialResource = FALSE;
       goto LOGIN;
    }

    HoldingCredentialResource = TRUE;

    //
    // Are we logged in? We can't hold the
    // credential list while logging in!!
    //

    if ( !pCredentials->Credential ) {

        HoldingCredentialResource = FALSE;
        NwReleaseCredList( pLogon );
        goto LOGIN;
    }

    //
    // If this credential is locked, we fail!
    //

    if ( pCredentials->CredentialLocked ) {
        Status = STATUS_DEVICE_BUSY;
        goto ExitWithCleanup;
    }

    Status = NdsCheckCredentialsEx( pIrpContext,
                                    pLogon,
                                    pCredentials,
                                    UserName,
                                    Password );

    if( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    goto AUTHENTICATE;

LOGIN:

    ASSERT( HoldingCredentialResource == FALSE );

    //
    // If this is a reconnect attempt and we don't have credentials
    // already, we have to give up.  We can't acquire credentials
    // during a reconnect and retry because it could cause a deadlock.
    //

    if ( BooleanFlagOn( pIrpContext->Flags, IRP_FLAG_RECONNECT_ATTEMPT ) ) {
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    Status = NdsGetCredentials( pIrpContext,
                                pLogon,
                                UserName,
                                Password );

    if ( !NT_SUCCESS( Status )) {
        goto ExitWithCleanup;
    }

    if ( Status == NWRDR_PASSWORD_HAS_EXPIRED ) {
        PasswordExpired = TRUE;
    }

    Status = NdsLookupCredentials( &pScb->NdsTreeName,
                                   pLogon,
                                   &pCredentials,
                                   CREDENTIAL_READ,
                                   FALSE );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    //
    // If this credential is locked, someone is
    // already logging out and so we fail this.
    //

    if ( pCredentials->CredentialLocked ) {
        Status = STATUS_DEVICE_BUSY;
        NwReleaseCredList( pLogon );
        goto ExitWithCleanup;
    }

    HoldingCredentialResource = TRUE;

AUTHENTICATE:

    ASSERT( HoldingCredentialResource == TRUE );
    ASSERT( AtHeadOfQueue == TRUE );

    //
    // NdsServerAuthenticate will not take us off the
    // head of the queue since this is not allowed.
    //

    Status = NdsServerAuthenticate( pIrpContext, pCredentials );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    NwReleaseCredList( pLogon );
    HoldingCredentialResource = FALSE;

    //
    // If this is a gateway request and is not a reconnect attempt, we
    // need to check the group membership.
    //

    if ( pIrpContext->Specific.Create.UserUid.QuadPart == DefaultLuid.QuadPart) {

        if ( !BooleanFlagOn( pIrpContext->Flags, IRP_FLAG_RECONNECT_ATTEMPT ) ) {

            NwDequeueIrpContext( pIrpContext, FALSE );
            AtHeadOfQueue = FALSE;

            //
            // Resolve the name, allowing a server jump if necessary.
            //

            pOriginalServer = pIrpContext->pScb;
            NwReferenceScb( pOriginalServer->pNpScb );

            uUserName.MaximumLength = pCredentials->Credential->userNameLength;
            uUserName.Length = uUserName.MaximumLength;
            uUserName.Buffer = ( WCHAR * ) ( ((BYTE *)pCredentials->Credential) +
                                             sizeof( NDS_CREDENTIAL ) +
                                             pCredentials->Credential->optDataSize );

            Status = NdsResolveNameKm( pIrpContext,
                                       &uUserName,
                                       &UserOID,
                                       TRUE,
                                       DEFAULT_RESOLVE_FLAGS );

            if ( NT_SUCCESS(Status) ) {

                RtlInitUnicodeString( &NtGroup, NT_GATEWAY_GROUP );
                Status = NdsCheckGroupMembership( pIrpContext, UserOID, &NtGroup );

                if ( !NT_SUCCESS( Status ) ) {
                    DebugTrace( 0, Dbg, "Gateway connection to NDS server not allowed.\n", 0 );
                    Status = STATUS_ACCESS_DENIED;
                }
            }

            //
            // Take us off the head of the queue in case were were left there.
            //

            NwDequeueIrpContext( pIrpContext, FALSE );

            //
            // Restore us to the server that we authenticated to so that
            // the irp context refers to the authenticated server.
            //

            if ( pOriginalServer != NULL ) {

                NwDereferenceScb( pIrpContext->pNpScb );

                if ( pIrpContext->pScb != pOriginalServer ) {
                    pIrpContext->pScb = pOriginalServer;
                    pIrpContext->pNpScb = pOriginalServer->pNpScb;
                }
            }

        }
    }

ExitWithCleanup:

    if ( HoldingCredentialResource ) {
        NwReleaseCredList( pLogon );
    }

    if ( AtHeadOfQueue ) {

        //
        // If we failed and this was a reconnect attempt, don't dequeue the
        // irp context or we may deadlock when we try to do the bindery logon.
        // See ReconnectRetry() for more information on this restriction.
        //

        if ( !BooleanFlagOn( pIrpContext->Flags, IRP_FLAG_RECONNECT_ATTEMPT ) ) {
            NwDequeueIrpContext( pIrpContext, FALSE );
        }

    }

    if ( ( NT_SUCCESS( Status ) ) &&
         ( PasswordExpired ) ) {
        Status = NWRDR_PASSWORD_HAS_EXPIRED;
    }

    DebugTrace( 0, Dbg, "DoNdsLogin: Status = %08lx\n", Status );
    return Status;
}

NTSTATUS
NdsTreeLogin(
    IN PIRP_CONTEXT    pIrpContext,
    IN PUNICODE_STRING puUser,
    IN POEM_STRING     pOemPassword,
    IN POEM_STRING     pOemNewPassword,
    IN PLOGON          pUserLogon
)
/*++

Routine Description:

    Login the specified user to the NDS tree at the server referred
    to by the given IrpContext using the supplied password.

Arguments:

    pIrpContext     - The irp context for this server connection.
    puUser          - The user login name.
    pOemPassword    - The upper-case, plaintext password.
    pOemNewPassword - The new password for a change pass request.
    pUserLogon      - The LOGON security structure for this user,
                      which may be NULL for a change password
                      request.

Side Effects:

    If successful, the user's credentials, signature, and
    public key are saved in the nds context for this NDS tree
    in the credential list in the LOGON structure.

Notes:

    This function may have to jump around a few servers to
    get all the info needed for login.  If restores the irp
    context to the original server so that when we authenticate,
    we authenticate to the correct server (as requested by the
    user).

--*/
{
    NTSTATUS Status;                   // status of the operation
    int CryptStatus;                   // crypt status

    DWORD dwChallenge;                 // four byte server challenge
    PUNICODE_STRING puServerName;      // server's distinguished name

    DWORD dwUserOID,                   // user oid on the current server
          dwSrcUserOID,                // user oid on the originating server
          dwServerOID;                 // server oid

    BYTE  *pbServerPublicNdsKey,       // server's public key in NDS format
          *pbServerPublicBsafeKey;     // server's public BSAFE key

    int   cbServerPublicNdsKeyLen,     // length of server public NDS key
          cbServerPublicBsafeKeyLen;   // length of server pubilc BSAFE key

    BYTE  *pbUserPrivateNdsKey,        // user's private key in NDS format
          *pbUserPrivateBsafeKey;      // user's private BSAFE key

    int   cbUserPrivateNdsKeyLen;      // length of user private NDS key
    WORD  cbUserPrivateBsafeKeyLen;    // length of user private BSAFE key

    BYTE  pbNw3PasswdHash[16];         // nw3 passwd hash
    BYTE  pbNewPasswdHash[16];         // new passwd hash for change pass
    BYTE  pbPasswdHashRC2Key[8];       // RC2 secret key generated from hash

    BYTE  pbEncryptedChallenge[16];    // RC2 encrypted server challenge
    int   cbEncryptedChallengeLen;     // length of the encrypted challenge

    PNDS_SECURITY_CONTEXT psNdsSecurityContext;  // user's nds context
    BYTE                  *pbSignData;           // user's signature data

    UNICODE_STRING uUserDN;            // users fully distinguished name
    PWCHAR UserDnBuffer;

    DWORD dwValidityStart, dwValidityEnd;
    BOOLEAN AtHeadOfQueue = FALSE;
    BOOLEAN HoldingCredResource = FALSE;
    BOOLEAN PasswordExpired = FALSE;

    UNICODE_STRING PlainServerName;
    USHORT UidLen;
    KIRQL OldIrql;
    PSCB pLoginServer = NULL;
    PSCB pOriginalServer = NULL;
    DWORD dwLoginFlags = 0;

    DebugTrace( 0, Dbg, "Enter NdsTreeLogin...\n", 0 );

    ASSERT( puUser );
    ASSERT( pOemPassword );

    //
    // Allocate space for the server's public key and the user's private key.
    //

    cbServerPublicNdsKeyLen = MAX_PUBLIC_KEY_LEN + MAX_ENC_PRIV_KEY_LEN + MAX_NDS_NAME_SIZE;

    pbServerPublicNdsKey = ALLOCATE_POOL( PagedPool, cbServerPublicNdsKeyLen );

    if ( !pbServerPublicNdsKey ) {

        DebugTrace( 0, Dbg, "Out of memory in NdsTreeLogin...\n", 0 );
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // First, jump to a server where we can get this user object.
    // Don't forget the server to which we were originally pointed.
    //

    pOriginalServer = pIrpContext->pScb;
    NwReferenceScb( pOriginalServer->pNpScb );

    Status = NdsResolveNameKm( pIrpContext,
                               puUser,
                               &dwUserOID,
                               TRUE,
                               DEFAULT_RESOLVE_FLAGS );

    if ( !NT_SUCCESS( Status ) ) {
        if ( Status == STATUS_BAD_NETWORK_PATH ) {
            Status = STATUS_NO_SUCH_USER;
        }
        goto ExitWithCleanup;
    }

    //
    // Now get the user name from the object info.
    //

    UserDnBuffer = (PWCHAR) ( pbServerPublicNdsKey +
                              MAX_PUBLIC_KEY_LEN +
                              MAX_ENC_PRIV_KEY_LEN );

    uUserDN.Length = 0;
    uUserDN.MaximumLength = MAX_NDS_NAME_SIZE;
    uUserDN.Buffer = UserDnBuffer;

    Status = NdsGetUserName( pIrpContext,
                             dwUserOID,
                             &uUserDN );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    //
    // Get the name of the server we are currently on.  We borrow a
    // little space from our key buffer and overwrite it later.
    //

    puServerName = ( PUNICODE_STRING ) pbServerPublicNdsKey;
    puServerName->Buffer = (PWCHAR) pbServerPublicNdsKey + sizeof( UNICODE_STRING );
    puServerName->MaximumLength = cbServerPublicNdsKeyLen - sizeof( UNICODE_STRING );

    Status = NdsGetServerName( pIrpContext,
                               puServerName );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    //
    // If the public key for this server is on a partition that's
    // on another server, we'll have to jump over there to get the
    // public key and then return.  The key and user object are
    // only any good on this server!  DO NOT CHANGE THE ORDER OF
    // THIS OR IT WILL BREAK!
    //

    pLoginServer = pIrpContext->pScb;
    NwReferenceScb( pLoginServer->pNpScb );

    Status = NdsResolveNameKm( pIrpContext,
                               puServerName,
                               &dwServerOID,
                               TRUE,
                               DEFAULT_RESOLVE_FLAGS );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    //
    // Get the server's public key and its length.
    //

    Status = NdsReadPublicKey( pIrpContext,
                               dwServerOID,
                               pbServerPublicNdsKey,
                               &cbServerPublicNdsKeyLen );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    //
    // Return us to the login server.
    //

    if ( pLoginServer != pIrpContext->pScb ) {

        NwDequeueIrpContext( pIrpContext, FALSE );
        NwDereferenceScb( pIrpContext->pNpScb );
        pIrpContext->pScb = pLoginServer;
        pIrpContext->pNpScb = pLoginServer->pNpScb;

    } else {

       NwDereferenceScb( pLoginServer->pNpScb );
    }

    pLoginServer = NULL;

    //
    // Locate the BSAFE key in the NDS key.
    //

    cbServerPublicBsafeKeyLen = NdsGetBsafeKey( pbServerPublicNdsKey,
                                                cbServerPublicNdsKeyLen,
                                                &pbServerPublicBsafeKey );

    if ( !cbServerPublicBsafeKeyLen ) {
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    //
    // Send the begin login packet.  This returns to us the
    // 4 byte challenge and the object id of the user's account
    // on the server on which it was created.  It may be the
    // same as the object id that we provided if the account
    // was created on this server.
    //

    Status = BeginLogin( pIrpContext,
                         dwUserOID,
                         &dwSrcUserOID,
                         &dwChallenge );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    //
    // Compute the 16 byte NW3 hash and generate the
    // 8 byte secret key from it.  The 8 byte secret
    // key consists of a MAC checksum of the NW3 hash.
    //

    Shuffle( (UCHAR *)&dwSrcUserOID,
             pOemPassword->Buffer,
             pOemPassword->Length,
             pbNw3PasswdHash );

    GenKey8( pbNw3PasswdHash,
             sizeof( pbNw3PasswdHash ),
             pbPasswdHashRC2Key );

    //
    // RC2 Encrypt the 4 byte challenge using the secret
    // key generated from the password.
    //

    CryptStatus = CBCEncrypt( pbPasswdHashRC2Key,
                              NULL,
                              (BYTE *)&dwChallenge,
                              4,
                              pbEncryptedChallenge,
                              &cbEncryptedChallengeLen,
                              BSAFE_CHECKSUM_LEN );

    if ( CryptStatus ) {

        DebugTrace( 0, Dbg, "CBC encryption failed.\n", 0 );
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    pbUserPrivateNdsKey = pbServerPublicNdsKey + MAX_PUBLIC_KEY_LEN;
    cbUserPrivateNdsKeyLen = MAX_ENC_PRIV_KEY_LEN;

    //
    // Make the finish login packet.  If successful, this routine
    // returns the encrypted user private key and the valid duration
    // of the user's credentials.
    //

    if ( pOemNewPassword ) {
        dwLoginFlags = 1;
    }

    Status = FinishLogin( pIrpContext,
                          dwUserOID,
                          dwLoginFlags,
                          pbEncryptedChallenge,
                          pbServerPublicBsafeKey,
                          cbServerPublicBsafeKeyLen,
                          pbUserPrivateNdsKey,
                          &cbUserPrivateNdsKeyLen,
                          &dwValidityStart,
                          &dwValidityEnd );

    if ( !NT_SUCCESS( Status ) ) {
       goto ExitWithCleanup;
    }

    if ( !pOemNewPassword ) {

        //
        // If the password is expired, report it to the user.
        //

        if ( Status == NWRDR_PASSWORD_HAS_EXPIRED ) {
            PasswordExpired = TRUE;
        }

        //
        // Allocate the credential and set up space for the private key.
        //

        NwAppendToQueueAndWait( pIrpContext );
        AtHeadOfQueue = TRUE;

        Status = NdsLookupCredentials( &pIrpContext->pScb->NdsTreeName,
                                       pUserLogon,
                                       &psNdsSecurityContext,
                                       CREDENTIAL_WRITE,
                                       TRUE );

        if ( !NT_SUCCESS( Status ) ) {
            goto ExitWithCleanup;
        }

        //
        // ALERT! We are holding the credential list.
        //

        HoldingCredResource = TRUE;

        psNdsSecurityContext->Credential = ALLOCATE_POOL( PagedPool,
                                                          sizeof( NDS_CREDENTIAL ) +
                                                          uUserDN.Length );

        if ( !psNdsSecurityContext->Credential ) {

            DebugTrace( 0, Dbg, "Out of memory in NdsTreeLogin (for credential)...\n", 0 );
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto ExitWithCleanup;

        }

        *( (UNALIGNED DWORD *) &( psNdsSecurityContext->Credential->validityBegin ) ) = dwValidityStart;
        *( (UNALIGNED DWORD *) &( psNdsSecurityContext->Credential->validityEnd ) )   = dwValidityEnd;

        DebugTrace( 0, Dbg, "Credential validity start: 0x%08lx\n", dwValidityStart );
        DebugTrace( 0, Dbg, "Credential validity end: 0x%08lx\n", dwValidityEnd );

        //
        // RC2 Decrypt the response to extract the BSAFE private
        // key data in place.
        //

        CryptStatus = CBCDecrypt( pbPasswdHashRC2Key,
                                  NULL,
                                  pbUserPrivateNdsKey,
                                  cbUserPrivateNdsKeyLen,
                                  pbUserPrivateNdsKey,
                                  &cbUserPrivateNdsKeyLen,
                                  BSAFE_CHECKSUM_LEN );

        if ( CryptStatus ) {

            DebugTrace( 0, Dbg, "CBC decryption failed.\n", 0 );
            Status = STATUS_UNSUCCESSFUL;
            goto ExitWithCleanup;
        }

        //
        // Skip over the header.
        //

        pbUserPrivateBsafeKey = ( pbUserPrivateNdsKey + sizeof( TAG_DATA_HEADER ) );
        cbUserPrivateBsafeKeyLen = *( ( WORD * ) pbUserPrivateBsafeKey );
        pbUserPrivateBsafeKey += sizeof( WORD );

        //
        // Create the credential.
        //

        psNdsSecurityContext->Credential->tdh.version = 1;
        psNdsSecurityContext->Credential->tdh.tag = TAG_CREDENTIAL;

        GenRandomBytes( ( BYTE * ) &(psNdsSecurityContext->Credential->random),
                        sizeof( psNdsSecurityContext->Credential->random ) );

        psNdsSecurityContext->Credential->optDataSize = 0;
        psNdsSecurityContext->Credential->userNameLength = uUserDN.Length;

        RtlCopyMemory( ( (BYTE *)psNdsSecurityContext->Credential) + sizeof( NDS_CREDENTIAL ),
                         UserDnBuffer,
                         uUserDN.Length );

        //
        // Generate and save the signature.
        //

        psNdsSecurityContext->Signature = ALLOCATE_POOL( PagedPool, MAX_SIGNATURE_LEN );

        if ( !psNdsSecurityContext->Signature ) {

            DebugTrace( 0, Dbg, "Out of memory in NdsTreeLogin (for signature)...\n", 0 );
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto ExitWithCleanup;

        }

        pbSignData = ( ( ( BYTE * ) psNdsSecurityContext->Signature ) +
                                    sizeof( NDS_SIGNATURE ) );

        RtlZeroMemory( pbSignData, MAX_RSA_BYTES );

        psNdsSecurityContext->Signature->tdh.version = 1;
        psNdsSecurityContext->Signature->tdh.tag = TAG_SIGNATURE;

        //
        // Create the hash for the signature from the credential.
        //

        MD2( (BYTE *) psNdsSecurityContext->Credential,
             sizeof( NDS_CREDENTIAL ) + ( uUserDN.Length ),
             pbSignData );

        //
        // Compute the 'signature' by RSA-encrypting the
        // 16-byte signature hash with the private key.
        //

        psNdsSecurityContext->Signature->signDataLength = RSAPrivate( pbUserPrivateBsafeKey,
                                                              cbUserPrivateBsafeKeyLen,
                                                              pbSignData,
                                                              16,
                                                              pbSignData );

        if ( !psNdsSecurityContext->Signature->signDataLength ) {

            DebugTrace( 0, Dbg, "RSA private encryption for signature failed.\n", 0 );
            Status = STATUS_UNSUCCESSFUL;
            goto ExitWithCleanup;
        }

        //
        // Round up the signature length, cause that's how VLM stores it.
        //

        psNdsSecurityContext->Signature->signDataLength =
            ROUNDUP4( psNdsSecurityContext->Signature->signDataLength );

        DebugTrace( 0, Dbg, "Signature data length: %d\n",
            psNdsSecurityContext->Signature->signDataLength );

        //
        // Get the user's public key for storage in the nds context.
        //

        psNdsSecurityContext->PublicNdsKey = ALLOCATE_POOL( PagedPool, MAX_PUBLIC_KEY_LEN );

        if ( !psNdsSecurityContext->PublicNdsKey ) {

            DebugTrace( 0, Dbg, "Out of memory in NdsTreeLogin (for public key)...\n", 0 );
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto ExitWithCleanup;

        }

        psNdsSecurityContext->PublicKeyLen = MAX_PUBLIC_KEY_LEN;

        ASSERT( AtHeadOfQueue );
        ASSERT( HoldingCredResource );

        Status = NdsReadPublicKey( pIrpContext,
                                   dwUserOID,
                                   psNdsSecurityContext->PublicNdsKey,
                                   &(psNdsSecurityContext->PublicKeyLen) );

        if ( !NT_SUCCESS( Status ) ) {
            goto ExitWithCleanup;
        }

        //
        // Store away the password we used to connect.
        //

        psNdsSecurityContext->Password.Buffer = ALLOCATE_POOL( PagedPool, pOemPassword->Length );

        if ( !psNdsSecurityContext->Password.Buffer ) {

            DebugTrace( 0, Dbg, "Out of memory in NdsTreeLogin (for password)\n", 0 );
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto ExitWithCleanup;
        }

        psNdsSecurityContext->Password.Length = pOemPassword->Length;
        psNdsSecurityContext->Password.MaximumLength = pOemPassword->Length;
        RtlCopyMemory( psNdsSecurityContext->Password.Buffer,
                       pOemPassword->Buffer,
                       pOemPassword->Length );

        //
        // We are logged in to the NDS tree.  Should we zero the private
        // key, or is NT's protection sufficient?
        //

        NwReleaseCredList( pUserLogon );

        //
        // Try to elect this server as the preferred server if necessary.
        //

        NwAcquireExclusiveRcb( &NwRcb, TRUE );

        if ( ( pUserLogon->ServerName.Length == 0 ) &&
             ( !pIrpContext->Specific.Create.fExCredentialCreate ) ) {

            //
            // Strip off the unicode uid from the server name.
            //

            PlainServerName.Length = pIrpContext->pScb->UidServerName.Length;
            PlainServerName.Buffer = pIrpContext->pScb->UidServerName.Buffer;

            UidLen = 0;

            while ( UidLen < ( PlainServerName.Length / sizeof( WCHAR ) ) ) {

                if ( PlainServerName.Buffer[UidLen++] == L'\\' ) {
                    break;
                }
            }

            PlainServerName.Buffer += UidLen;
            PlainServerName.Length -= ( UidLen * sizeof( WCHAR ) );
            PlainServerName.MaximumLength = PlainServerName.Length;

            if ( PlainServerName.Length ) {

                Status = SetUnicodeString( &(pUserLogon->ServerName),
                                           PlainServerName.Length,
                                           PlainServerName.Buffer );

                if ( NT_SUCCESS( Status ) ) {

                    DebugTrace( 0, Dbg, "Electing preferred server: %wZ\n", &PlainServerName );

                    //
                    // Increase the Scb ref count, set the preferred server flag,
                    // and move the scb to the head of the SCB list.
                    //

                    NwReferenceScb( pIrpContext->pScb->pNpScb );
                    pIrpContext->pScb->PreferredServer = TRUE;

                    KeAcquireSpinLock( &ScbSpinLock, &OldIrql );

                    RemoveEntryList( &(pIrpContext->pScb->pNpScb->ScbLinks) );
                    InsertHeadList( &ScbQueue, &(pIrpContext->pScb->pNpScb->ScbLinks) );

                    KeReleaseSpinLock(&ScbSpinLock, OldIrql);

                }
            }
        }

    } else {

        //
        // This isn't a login, but a change password request.
        //
        // First we have to RC2 Decrypt the response to extract
        // the BSAFE private key data in place (just like for a
        // login).
        //

        CryptStatus = CBCDecrypt( pbPasswdHashRC2Key,
                                  NULL,
                                  pbUserPrivateNdsKey,
                                  cbUserPrivateNdsKeyLen,
                                  pbUserPrivateNdsKey,
                                  &cbUserPrivateNdsKeyLen,
                                  BSAFE_CHECKSUM_LEN );

        if ( CryptStatus ) {

            DebugTrace( 0, Dbg, "CBC decryption failed.\n", 0 );
            Status = STATUS_UNSUCCESSFUL;
            goto ExitWithCleanup;
        }

        //
        // Now, compute the hash of the new password.
        //

        Shuffle( (UCHAR *)&dwSrcUserOID,
                 pOemNewPassword->Buffer,
                 pOemNewPassword->Length,
                 pbNewPasswdHash );

        //
        // And finally, make the request.
        //

        Status = ChangeNdsPassword( pIrpContext,
                                    dwUserOID,
                                    dwChallenge,
                                    pbNw3PasswdHash,
                                    pbNewPasswdHash,
                                    ( PNDS_PRIVATE_KEY ) pbUserPrivateNdsKey,
                                    pbServerPublicBsafeKey,
                                    cbServerPublicBsafeKeyLen );

        if ( !NT_SUCCESS( Status ) ) {
            DebugTrace( 0, Dbg, "Change NDS password failed!\n", 0 );
            goto ExitWithCleanup;
        }

    }

    //
    // Return us to our original server if we've jumped around.
    //

    NwDequeueIrpContext( pIrpContext, FALSE );

    if ( pIrpContext->pScb != pOriginalServer ) {

        NwDereferenceScb( pIrpContext->pNpScb );
        pIrpContext->pScb = pOriginalServer;
        pIrpContext->pNpScb = pOriginalServer->pNpScb;

    } else {

        NwDereferenceScb( pOriginalServer->pNpScb );
    }

    pOriginalServer = NULL;

    if ( !pOemNewPassword ) {
        NwReleaseRcb( &NwRcb );
    }

    FREE_POOL( pbServerPublicNdsKey );

    if ( PasswordExpired ) {
        Status = NWRDR_PASSWORD_HAS_EXPIRED;
    } else {
        Status = STATUS_SUCCESS;
    }

    return Status;

ExitWithCleanup:

    DebugTrace( 0, Dbg, "NdsTreeLogin seems to have failed... cleaning up.\n", 0 );

    FREE_POOL( pbServerPublicNdsKey );

    if ( pLoginServer ) {
        NwDereferenceScb( pLoginServer->pNpScb );
    }

    //
    // If we failed after jumping servers, we have to restore
    // the irp context to the original server.
    //

    NwDequeueIrpContext( pIrpContext, FALSE );

    if ( pOriginalServer ) {

        if ( pIrpContext->pScb != pOriginalServer ) {

            NwDereferenceScb( pIrpContext->pNpScb );
            pIrpContext->pScb = pOriginalServer;
            pIrpContext->pNpScb = pOriginalServer->pNpScb;

        } else {

            NwDereferenceScb( pOriginalServer->pNpScb );
        }

    }

    if ( HoldingCredResource ) {

        if ( psNdsSecurityContext->Credential ) {
            FREE_POOL( psNdsSecurityContext->Credential );
            psNdsSecurityContext->Credential = NULL;
        }

        if ( psNdsSecurityContext->Signature ) {
            FREE_POOL( psNdsSecurityContext->Signature );
            psNdsSecurityContext->Signature = NULL;
        }

        if ( psNdsSecurityContext->PublicNdsKey ) {
            FREE_POOL( psNdsSecurityContext->PublicNdsKey );
            psNdsSecurityContext->PublicNdsKey = NULL;
            psNdsSecurityContext->PublicKeyLen = 0;
        }

        NwReleaseCredList( pUserLogon );
    }

    return Status;

}

NTSTATUS
BeginLogin(
   IN PIRP_CONTEXT pIrpContext,
   IN DWORD        userId,
   OUT DWORD       *loginId,
   OUT DWORD       *challenge
)
/*++

Routine Desription:

    Begin the NDS login process. The loginId returned is objectId of the user
    on the server which created the account (may not be the current server).

Arguments:

    pIrpContext - The IRP context for this connection.
    userId      - The user's NDS object Id.
    loginId     - The objectId used to encrypt password.
    challenge   - The 4 byte random challenge.

Return value:

    NTSTATUS - The result of the operation.

--*/
{

    NTSTATUS Status;
    LOCKED_BUFFER NdsRequest;

    PAGED_CODE();

    DebugTrace( 0, Dbg, "Enter BeginLogin...\n", 0 );

    Status = NdsAllocateLockedBuffer( &NdsRequest, NDS_BUFFER_SIZE );

    if ( !NT_SUCCESS( Status ) ) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // Announce myself.
    //

    Status = FragExWithWait( pIrpContext,
                             NDSV_BEGIN_LOGIN,
                             &NdsRequest,
                             "DD",
                             0,
                             userId );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    Status = NdsCompletionCodetoNtStatus( &NdsRequest );

    if ( !NT_SUCCESS( Status ) ) {

        if ( Status == STATUS_BAD_NETWORK_PATH ) {
            Status = STATUS_NO_SUCH_USER;
        }

        goto ExitWithCleanup;
    }

    //
    // Get the object id and the challenge string.
    //

    Status = ParseResponse( NULL,
                            NdsRequest.pRecvBufferVa,
                            NdsRequest.dwBytesWritten,
                            "G_DD",
                            sizeof( DWORD ),
                            loginId,
                            challenge );

    if ( NT_SUCCESS( Status ) ) {
        DebugTrace( 0, Dbg, "Login 4 byte challenge: 0x%08lx\n", *challenge );
    } else {
       DebugTrace( 0, Dbg, "Begin login failed...\n", 0 );
    }

ExitWithCleanup:

    NdsFreeLockedBuffer( &NdsRequest );
    return Status;

}

NTSTATUS
FinishLogin(
    IN PIRP_CONTEXT pIrpContext,
    IN DWORD        dwUserOID,
    IN DWORD        dwLoginFlags,
    IN BYTE         pbEncryptedChallenge[16],
    IN BYTE         *pbServerPublicBsafeKey,
    IN int          cbServerPublicBsafeKeyLen,
    OUT BYTE        *pbUserEncPrivateNdsKey,
    OUT int         *pcbUserEncPrivateNdsKeyLen,
    OUT DWORD       *pdwCredentialStartTime,
    OUT DWORD       *pdwCredentialEndTime
)
/*++

Routine Description:

    Constructs and sends the Finish Login request to the server.

Arguments:

    pIrpContext                - (IN)  IRP context for this request
    dwUserOID                  - (IN)  user's NDS object Id
    pbEncryptedChallenge       - (IN)  RC2 encrypted challenge
    pbServerPublicBsafeKey     - (IN)  server public bsafe key
    cbServerPublicBsafeKeyLen  - (IN)  length of server public key

    pbUserEncPrivateNdsKey     - (OUT) user's encrypted private nds key
    pcbUserEncPrivateNdsKeyLen - (OUT) length of pbUserEncPrivateNdsKey
    pdwCredentialStartTime     - (OUT) validity start time for credentials
    pdwCredentialEndTime       - (OUT) validity end time for credentials

--*/
{
    NTSTATUS Status;

    const int cbEncryptedChallengeLen = 16;

    int LOG_DATA_POOL_SIZE,                     // pool sizes for our allocation call
        PACKET_POOL_SIZE,
        RESP_POOL_SIZE;

    BYTE *pbRandomBytes;                        // random bytes used in crypto routines
    BYTE RandRC2SecretKey[RC2_KEY_LEN];         // random RC2 key generated from above
    BYTE pbEncryptedChallengeKey[RC2_KEY_LEN];  // RC2 key that will decode the response

    NDS_RAND_BYTE_BLOCK *psRandByteBlock;

    ENC_BLOCK_HDR  *pbEncRandSeedHead;          // header for encrypted random RC2 key seed
    BYTE           *pbEncRandSeed;              // encrypted random seed
    int            cbPackedRandSeedLen;         // length of the packed rand seed bytes

    ENC_BLOCK_HDR  *pbEncChallengeHead;         // header for encrypted challenge

    ENC_BLOCK_HDR  *pbEncLogDataHead;           // header for encrypted login data
    BYTE           *pbEncLogData;               // encrypted login data
    int            cbEncLogDataLen;             // length of the encrypted login data

    ENC_BLOCK_HDR  *pbEncServerRespHead;        // header for encrypted response
    BYTE           *pbEncServerResp;            // encrypted response

    int CryptStatus,                            // crypt call status
        CryptLen,                               // length of encrypted data
        RequestPacketLen,                       // length of the request packet data
        cbServerRespLen;                        // server response length after decryption

    BYTE *pbServerResponse;                     // response from the server
    DWORD cbEncServerRespLen;                   // server response length before decryption

    DWORD EncKeyLen;                            // length of the encrypted private key
    ENC_BLOCK_HDR *pbPrivKeyHead;               // encryption header of the private key

    LOCKED_BUFFER NdsRequest;                   // fragex locked buffer
    BOOL PasswordExpired = FALSE;

    PAGED_CODE();

    DebugTrace( 0, Dbg, "Enter FinishLogin...\n", 0 );

    //
    // Allocate working space.  The login data pool starts at
    // pbRandomBytes.  The packet data starts at pbEncRandSeedHead.
    // The server response pool starts at pbServerResponse.
    //

    //
    // BUGBUG: The alignment of these structures may possibly be wrong on
    // quad aligned machines; check out a hardware independent fix.
    //

    LOG_DATA_POOL_SIZE = RAND_KEY_DATA_LEN +               // 28 bytes for random seed
                         sizeof ( NDS_RAND_BYTE_BLOCK ) +  // login data random header
                         sizeof ( ENC_BLOCK_HDR ) +        // header for encrypted challenge
                         cbEncryptedChallengeLen +         // data for encrypted challenge
                         8;                                // padding
    LOG_DATA_POOL_SIZE = ROUNDUP4( LOG_DATA_POOL_SIZE );

    PACKET_POOL_SIZE =   2048;                             // packet buffer size
    RESP_POOL_SIZE =     2048;                             // packet buffer size

    pbRandomBytes = ALLOCATE_POOL( PagedPool,
                                   LOG_DATA_POOL_SIZE +
                                   PACKET_POOL_SIZE +
                                   RESP_POOL_SIZE );

    if ( !pbRandomBytes ) {

        DebugTrace( 0, Dbg, "Out of memory in FinishLogin (main block)...\n", 0 );
        return STATUS_INSUFFICIENT_RESOURCES;

    }

    pbEncRandSeedHead = ( PENC_BLOCK_HDR ) ( pbRandomBytes + LOG_DATA_POOL_SIZE );
    pbServerResponse = ( pbRandomBytes + LOG_DATA_POOL_SIZE + PACKET_POOL_SIZE );

    //
    // Start working on the login data.  As is common in the crypto world, we
    // generate a random seed and then make a key from it to be used with a
    // bulk cipher algorithm.  In Netware land, we use MAC to make an 8 byte
    // key from the random seed and use 64bit RC2 as our bulk cipher.  We then
    // RSA encrypt the seed using the server's public RSA key and use the bulk
    // cipher to encrypt the rest of our login data.
    //
    // Since Novell uses 64bit RC2, the security isn't great.
    //

    GenRandomBytes( pbRandomBytes, RAND_KEY_DATA_LEN );
    GenKey8( pbRandomBytes, RAND_KEY_DATA_LEN, RandRC2SecretKey );

    //
    // Now work on the actual packet data.  Create the header for the
    // encrypted random seed and pack the seed into it.
    //

    pbEncRandSeed = ( ( BYTE * )pbEncRandSeedHead ) + sizeof( ENC_BLOCK_HDR );

    pbEncRandSeedHead->cipherLength = RSAGetInputBlockSize( pbServerPublicBsafeKey,
                                                            cbServerPublicBsafeKeyLen );

    cbPackedRandSeedLen = RSAPack( pbRandomBytes,
                                   RAND_KEY_DATA_LEN,
                                   pbEncRandSeed,
                                   pbEncRandSeedHead->cipherLength );
    //
    // We should have packed exactly one block.
    //

    if( cbPackedRandSeedLen != pbEncRandSeedHead->cipherLength ) {
        DebugTrace( 0, Dbg, "RSAPack didn't pack exactly one block!\n", 0 );
    }

    pbEncRandSeedHead->cipherLength = RSAPublic( pbServerPublicBsafeKey,
                                                 cbServerPublicBsafeKeyLen,
                                                 pbEncRandSeed,
                                                 pbEncRandSeedHead->cipherLength,
                                                 pbEncRandSeed );

    if ( !pbEncRandSeedHead->cipherLength ) {

        DebugTrace( 0, Dbg, "Failing in FinishLogin... encryption failed.\n", 0 );
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;

    }

    //
    // Fill in the rest of the header for the random seed.  We don't count
    // the first DWORD in the EBH; it isn't part of the header as netware
    // wants it, per se.
    //

    pbEncRandSeedHead->blockLength = pbEncRandSeedHead->cipherLength +
                                     sizeof( ENC_BLOCK_HDR ) -
                                     sizeof( DWORD );
    pbEncRandSeedHead->version     = 1;
    pbEncRandSeedHead->encType     = ENC_TYPE_RSA_PUBLIC;
    pbEncRandSeedHead->dataLength  = RAND_KEY_DATA_LEN;

    //
    // Go back to working on the login data.  Fill out the rbb.
    //

    psRandByteBlock = ( PNDS_RAND_BYTE_BLOCK ) ( pbRandomBytes + RAND_KEY_DATA_LEN );

    GenRandomBytes( (BYTE *) &psRandByteBlock->rand1, 4 );
    psRandByteBlock->rand2Len = RAND_FL_DATA_LEN;
    GenRandomBytes( (BYTE *) &psRandByteBlock->rand2[0], RAND_FL_DATA_LEN );

    //
    // Fill out the header for the encrypted challenge right after the rbb.
    //

    pbEncChallengeHead = (ENC_BLOCK_HDR *) ( ((BYTE *)psRandByteBlock) +
                                             sizeof( NDS_RAND_BYTE_BLOCK ) );

    pbEncChallengeHead->version      = 1;
    pbEncChallengeHead->encType      = ENC_TYPE_RC2_CBC;
    pbEncChallengeHead->dataLength   = 4;
    pbEncChallengeHead->cipherLength = cbEncryptedChallengeLen;
    pbEncChallengeHead->blockLength  = cbEncryptedChallengeLen +
                                       sizeof( ENC_BLOCK_HDR ) -
                                       sizeof( DWORD );

    //
    // Place the encrypted challenge immediately after its header.
    //

    RtlCopyMemory( (BYTE *)( ((BYTE *)pbEncChallengeHead) +
                             sizeof( ENC_BLOCK_HDR )),
                   pbEncryptedChallenge,
                   cbEncryptedChallengeLen );

    //
    // Prepare the RC2 key to decrypt FinishLogin response.
    //

    GenKey8( (BYTE *)( &pbEncChallengeHead->version ),
             pbEncChallengeHead->blockLength,
             pbEncryptedChallengeKey );

    //
    // Finish up the packet data by preparing the login data.  Start
    // with the encryption header.
    //

    pbEncLogDataHead = ( PENC_BLOCK_HDR ) ( pbEncRandSeed +
                           ROUNDUP4( pbEncRandSeedHead->cipherLength ) );

    pbEncLogData = ( ( BYTE * )pbEncLogDataHead ) + sizeof( ENC_BLOCK_HDR );

    pbEncLogDataHead->version = 1;
    pbEncLogDataHead->encType = ENC_TYPE_RC2_CBC;
    pbEncLogDataHead->dataLength = sizeof( NDS_RAND_BYTE_BLOCK ) +
                                   sizeof( ENC_BLOCK_HDR ) +
                                   cbEncryptedChallengeLen;

    //
    // Sanity check the packet pool for overflow.
    //

    if ( ( pbEncLogData + pbEncLogDataHead->dataLength + ( 2 * CIPHERBLOCKSIZE ) ) -
         (BYTE *) pbEncRandSeedHead > PACKET_POOL_SIZE ) {

        DebugTrace( 0, Dbg, "Packet pool overflow... I'd better fix this.\n", 0 );
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    //
    // Encrypt the login data.
    //

    CryptStatus = CBCEncrypt( RandRC2SecretKey,
                              NULL,
                              (BYTE *)psRandByteBlock,
                              pbEncLogDataHead->dataLength,
                              pbEncLogData,
                              &CryptLen,
                              BSAFE_CHECKSUM_LEN );

    if ( CryptStatus ) {

        DebugTrace( 0, Dbg, "Encryption failure in FinishLogin...\n", 0 );
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    pbEncLogDataHead->cipherLength = (WORD)CryptLen;
    pbEncLogDataHead->blockLength = pbEncLogDataHead->cipherLength +
                                    sizeof( ENC_BLOCK_HDR ) -
                                    sizeof( DWORD );

    //
    // We can finally send out the finish login request!  Calculate the
    // send amount and make the request.
    //

    RequestPacketLen = ( (BYTE *) pbEncLogData + pbEncLogDataHead->cipherLength ) -
                         (BYTE *) pbEncRandSeedHead;

    NdsRequest.pRecvBufferVa = pbServerResponse;
    NdsRequest.dwRecvLen = RESP_POOL_SIZE;
    NdsRequest.pRecvMdl = NULL;

    NdsRequest.pRecvMdl = ALLOCATE_MDL( pbServerResponse,
                                        RESP_POOL_SIZE,
                                        FALSE,
                                        FALSE,
                                        NULL );
    if ( !NdsRequest.pRecvMdl ) {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto ExitWithCleanup;
    }

    MmProbeAndLockPages( NdsRequest.pRecvMdl,
                         KernelMode,
                         IoWriteAccess );

    Status = FragExWithWait( pIrpContext,
                             NDSV_FINISH_LOGIN,
                             &NdsRequest,
                             "DDDDDDDr",
                             2,                    // Version
                             dwLoginFlags,         // Flags
                             dwUserOID,            // Entry ID
                             0x494,                //
                             1,                    // Security Version
                             0x20009,              // Envelope ID 1
                             0x488,                // Envelope length
                             pbEncRandSeedHead,    // Cipher block
                             RequestPacketLen );   // Cipher block length

    MmUnlockPages( NdsRequest.pRecvMdl );
    FREE_MDL( NdsRequest.pRecvMdl );

    if ( !NT_SUCCESS( Status ) ) {
       goto ExitWithCleanup;
    }

    Status = NdsCompletionCodetoNtStatus( &NdsRequest );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    if ( Status == NWRDR_PASSWORD_HAS_EXPIRED ) {
        PasswordExpired = TRUE;
    }

    cbServerRespLen = NdsRequest.dwBytesWritten;

    //
    // Save the credential validity times.
    //

    Status = ParseResponse( NULL,
                            pbServerResponse,
                            cbServerRespLen,
                            "G_DD",
                            sizeof( DWORD ),
                            pdwCredentialStartTime,
                            pdwCredentialEndTime );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    //
    // Grab the encryption block header for the response.  This response in
    // RC2 encrypted with the pbEncryptedChallengeKey.
    //

    pbEncServerRespHead = (ENC_BLOCK_HDR *) ( pbServerResponse +
                                              ( 3 * sizeof( DWORD ) ) );

    if ( pbEncServerRespHead->encType != ENC_TYPE_RC2_CBC ||
         pbEncServerRespHead->cipherLength >
         ( RESP_POOL_SIZE + sizeof( ENC_BLOCK_HDR ) + 12 ) ) {

        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    //
    // Decrypt the server response in place.
    //

    pbEncServerResp = ( BYTE * ) ( ( BYTE * ) pbEncServerRespHead +
                                     sizeof( ENC_BLOCK_HDR ) );

    CryptStatus = CBCDecrypt( pbEncryptedChallengeKey,
                              NULL,
                              pbEncServerResp,
                              pbEncServerRespHead->cipherLength,
                              pbEncServerResp,
                              &cbServerRespLen,
                              BSAFE_CHECKSUM_LEN );

    if ( CryptStatus ||
         cbServerRespLen != pbEncServerRespHead->dataLength ) {

        DebugTrace( 0, Dbg, "Encryption failure (2) in FinishLogin...\n", 0 );
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    //
    // Examine the first random number to make sure the server is authentic.
    //

    if ( psRandByteBlock->rand1 != * ( DWORD * ) pbEncServerResp ) {

       DebugTrace( 0, Dbg, "Server failed to respond to our challenge correctly...\n", 0 );
       Status = STATUS_UNSUCCESSFUL;
       goto ExitWithCleanup;

    }

    //
    // We know things are legit, so we can extract the private key.
    // Careful, though: don't XOR the size dword.
    //

    pbEncServerResp += sizeof( DWORD );
    EncKeyLen = * ( DWORD * ) ( pbEncServerResp );

    pbEncServerResp += sizeof( DWORD );
    while ( EncKeyLen-- ) {

       pbEncServerResp[EncKeyLen] ^= psRandByteBlock->rand2[EncKeyLen];
    }

    //
    // Check the encryption header on the private key.  Don't forget to
    // backup to include the size dword.
    //

    pbPrivKeyHead = ( ENC_BLOCK_HDR * )( pbEncServerResp - sizeof( DWORD ) ) ;

    if ( pbPrivKeyHead->encType != ENC_TYPE_RC2_CBC ) {

        DebugTrace( 0, Dbg, "Bad encryption header on the private key...\n", 0 );
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;

    }

    //
    // Finally, copy out the user's private NDS key.
    //

    if ( *pcbUserEncPrivateNdsKeyLen >= pbPrivKeyHead->cipherLength ) {

        DebugTrace( 0, Dbg, "Encrypted private key len: %d\n",
                    pbPrivKeyHead->cipherLength );

        RtlCopyMemory( pbUserEncPrivateNdsKey,
                       ((BYTE *)( pbPrivKeyHead )) + sizeof( ENC_BLOCK_HDR ),
                       pbPrivKeyHead->cipherLength );

        *pcbUserEncPrivateNdsKeyLen = pbPrivKeyHead->cipherLength;

        Status = STATUS_SUCCESS;

    } else {

       DebugTrace( 0, Dbg, "Encryption failure on private key in FinishLogin...\n", 0 );
       Status = STATUS_UNSUCCESSFUL;

    }

ExitWithCleanup:

    FREE_POOL( pbRandomBytes );

    if ( ( NT_SUCCESS( Status ) ) &&
         ( PasswordExpired ) ) {
        Status = NWRDR_PASSWORD_HAS_EXPIRED;
    }

    return Status;

}

NTSTATUS
ChangeNdsPassword(
    PIRP_CONTEXT     pIrpContext,
    DWORD            dwUserOID,
    DWORD            dwChallenge,
    PBYTE            pbOldPwHash,
    PBYTE            pbNewPwHash,
    PNDS_PRIVATE_KEY pUserPrivKey,
    PBYTE            pServerPublicBsafeKey,
    UINT             ServerPubKeyLen
)
/*+++

Description:

    Send a change password packet.  Change the users password
    on the NDS tree that this irp context points to.

Arguments:

    pIrpContext           - The irp context for this request.  Points to the target server.
    dwUserOID             - The oid for the current user.
    dwChallenge           - The encrypted challenge from begin login.
    pbOldPwHash           - The 16 byte hash of the old password.
    pbNewPwHash           - The 16 byte hash of the new password.
    pUserPrivKey          - The user's private RSA key with NDS header.
    pServerPublicBsafeKey - The server's public RSA key in BSAFE format.
    ServerPubKeyLen       - The length of the server's public BSAFE key.

--*/
{
    NTSTATUS Status;
    BYTE pbNewPwKey[8];
    BYTE pbSecretKey[8];
    PENC_BLOCK_HDR pbEncSecretKey, pbEncChangePassReq;
    BYTE RandomBytes[RAND_KEY_DATA_LEN];
    PBYTE pbEncData;
    PNDS_CHPW_MSG pChangePassMsg;
    INT CryptStatus, CryptLen;
    DWORD dwTotalEncDataLen;
    LOCKED_BUFFER NdsRequest;

    PAGED_CODE();

    //
    // Create a secret key from the new password.
    //

    GenKey8( pbNewPwHash, 16, pbNewPwKey );

    pbEncSecretKey = ALLOCATE_POOL( PagedPool,
                                    ( ( 2 * sizeof( ENC_BLOCK_HDR ) ) +
                                      ( MAX_RSA_BYTES ) +
                                      ( sizeof( NDS_CHPW_MSG ) ) +
                                      ( sizeof( NDS_PRIVATE_KEY ) ) +
                                      ( pUserPrivKey->keyDataLength ) +
                                      16 ) );

    if ( !pbEncSecretKey ) {
        DebugTrace( 0, Dbg, "ChangeNdsPassword: Out of memory.\n", 0 );
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    Status = NdsAllocateLockedBuffer( &NdsRequest, NDS_BUFFER_SIZE );

    if ( !NT_SUCCESS( Status ) ) {
        FREE_POOL( pbEncSecretKey );
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // Generate a random key.
    //

    GenRandomBytes( RandomBytes, RAND_KEY_DATA_LEN );
    GenKey8( RandomBytes, RAND_KEY_DATA_LEN, pbSecretKey );

    //
    // Encrypt the secret key data in the space after the EBH.
    //

    pbEncSecretKey->dataLength = RAND_KEY_DATA_LEN;
    pbEncSecretKey->cipherLength = RSAGetInputBlockSize( pServerPublicBsafeKey, ServerPubKeyLen);

    pbEncData = ( PBYTE ) ( pbEncSecretKey + 1 );

    pbEncSecretKey->cipherLength = RSAPack( RandomBytes,
                                            pbEncSecretKey->dataLength,
                                            pbEncData,
                                            pbEncSecretKey->cipherLength );

    pbEncSecretKey->cipherLength = RSAPublic( pServerPublicBsafeKey,
                                              ServerPubKeyLen,
                                              pbEncData,
                                              pbEncSecretKey->cipherLength,
                                              pbEncData );

    if ( !pbEncSecretKey->cipherLength ) {
        DebugTrace( 0, Dbg, "ChangeNdsPassword: RSA encryption failed.\n", 0 );
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    //
    // Finish filling out the EBH for the secret key block.
    //

    pbEncSecretKey->version =  1;
    pbEncSecretKey->encType = ENC_TYPE_RSA_PUBLIC;
    pbEncSecretKey->blockLength = pbEncSecretKey->cipherLength +
                                    sizeof( ENC_BLOCK_HDR ) -
                                    sizeof( DWORD );

    //
    // Now form the change password request.
    //

    pbEncChangePassReq = ( PENC_BLOCK_HDR )
        ( pbEncData + ROUNDUP4( pbEncSecretKey->cipherLength ) );

    pChangePassMsg = ( PNDS_CHPW_MSG ) ( pbEncChangePassReq + 1 );

    //
    // Init the Change Password message.
    //

    pChangePassMsg->challenge = dwChallenge;
    pChangePassMsg->oldPwLength = pChangePassMsg->newPwLength = 16;

    RtlCopyMemory( pChangePassMsg->oldPwHash, pbOldPwHash, pChangePassMsg->oldPwLength );
    RtlCopyMemory( pChangePassMsg->newPwHash, pbNewPwHash, pChangePassMsg->newPwLength );

    pChangePassMsg->unknown = 8;
    pChangePassMsg->encPrivKeyHdr.version = 1;
    pChangePassMsg->encPrivKeyHdr.encType = ENC_TYPE_RC2_CBC;
    pChangePassMsg->encPrivKeyHdr.dataLength = pUserPrivKey->keyDataLength + sizeof( NDS_PRIVATE_KEY );

    //
    // Encrypt the private key with the key derived from the new password.
    //

    CryptStatus = CBCEncrypt( pbNewPwKey,
                              NULL,
                              ( PBYTE ) pUserPrivKey,
                              pChangePassMsg->encPrivKeyHdr.dataLength,
                              ( PBYTE ) ( pChangePassMsg + 1 ),
                              &CryptLen,
                              BSAFE_CHECKSUM_LEN );

    if ( CryptStatus ) {
        DebugTrace( 0, Dbg, "ChangeNdsPassword: CBC encrypt failed.\n", 0 );
        Status = STATUS_UNSUCCESSFUL;
        goto ExitWithCleanup;
    }

    //
    // Finish filling out the encryption header.
    //

    pChangePassMsg->encPrivKeyHdr.cipherLength = CryptLen;
    pChangePassMsg->encPrivKeyHdr.blockLength =  CryptLen +
                                                 sizeof( ENC_BLOCK_HDR ) -
                                                 sizeof( DWORD );
    pbEncChangePassReq->version =  1;
    pbEncChangePassReq->encType = ENC_TYPE_RC2_CBC;
    pbEncChangePassReq->dataLength = sizeof( NDS_CHPW_MSG ) + CryptLen;

    //
    // Encrypt the whole Change Password message in-place with the secret key.
    //

    CryptStatus = CBCEncrypt( pbSecretKey,
                              NULL,
                              ( PBYTE ) pChangePassMsg,
                              pbEncChangePassReq->dataLength,
                              ( PBYTE ) pChangePassMsg,
                              &CryptLen,
                              BSAFE_CHECKSUM_LEN);

    if ( CryptStatus ) {
       DebugTrace( 0, Dbg, "ChangeNdsPassword: Second CBC encrypt failed.\n", 0 );
       Status = STATUS_UNSUCCESSFUL;
       goto ExitWithCleanup;
    }

    pbEncChangePassReq->cipherLength = CryptLen;
    pbEncChangePassReq->blockLength =
        CryptLen + sizeof( ENC_BLOCK_HDR ) - sizeof( DWORD );

    //
    // Calculate the size of the request.
    //

    dwTotalEncDataLen = sizeof( ENC_BLOCK_HDR ) +                    // Secret key header.
                        ROUNDUP4( pbEncSecretKey->cipherLength ) +   // Secret key data.
                        sizeof( ENC_BLOCK_HDR ) +                    // Change pass msg header.
                        CryptLen;                                    // Change pass data.

    //
    // Send this change password message to the server.
    //

    Status = FragExWithWait( pIrpContext,
                             NDSV_CHANGE_PASSWORD,
                             &NdsRequest,
                             "DDDDDDr",
                             0,
                             dwUserOID,
                             dwTotalEncDataLen + ( 3 * sizeof( DWORD ) ),
                             1,
                             0x20009,
                             dwTotalEncDataLen,
                             pbEncSecretKey,
                             dwTotalEncDataLen );

    if ( NT_SUCCESS( Status ) ) {
        Status = NdsCompletionCodetoNtStatus( &NdsRequest );
    }

ExitWithCleanup:

    FREE_POOL( pbEncSecretKey );
    NdsFreeLockedBuffer( &NdsRequest );
    return Status;

}

NTSTATUS
NdsServerAuthenticate(
    IN PIRP_CONTEXT pIrpContext,
    IN PNDS_SECURITY_CONTEXT pNdsContext
)
/*++

Routine Description:

    Authenticate an NDS connection.
    The user must have already logged into the NDS tree.

    If you change this function - know that you cannot
    at any point try to acquire the nds credential
    resource exclusive from here since that could cause
    a dead lock!!!

    You also must not dequeue the irp context!

Arguments:

    pIrpContext - IrpContext for the server that we want to authenticate to.

Return value:

    NTSTATUS

--*/
{
    NTSTATUS Status;

    BYTE *pbUserPublicBsafeKey;
    int  cbUserPublicBsafeKeyLen;

    NDS_AUTH_MSG *psAuthMsg;
    NDS_CREDENTIAL *psLocalCredential;
    DWORD dwLocalCredentialLen;
    UNICODE_STRING uUserName;
    DWORD UserOID;

    BYTE *x, *y, *r;
    BYTE CredentialHash[16];
    int i, rsaBlockSize, rsaModSize, totalXLen;
    DWORD dwServerRand;

    BYTE *pbResponse;
    DWORD cbResponseLen;
    LOCKED_BUFFER NdsRequest;

    PAGED_CODE();

    DebugTrace( 0, Dbg, "Entering NdsServerAuthenticate...\n", 0 );

    //
    // Allocate space for the auth msg, credential, G-Q bytes, and
    // the response buffer.
    //

    psAuthMsg = ALLOCATE_POOL( PagedPool,
                               sizeof( NDS_AUTH_MSG ) +    // auth message
                               sizeof( NDS_CREDENTIAL ) +  // credential
                               MAX_NDS_NAME_SIZE +         //
                               ( MAX_RSA_BYTES * 9 ) );    // G-Q rands

    if ( !psAuthMsg ) {

        DebugTrace( 0, Dbg, "Out of memory in NdsServerAuthenticate (0)...\n", 0 );
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    pbResponse = ALLOCATE_POOL( PagedPool, NDS_BUFFER_SIZE );

    if ( !pbResponse ) {

        DebugTrace( 0, Dbg, "Out of memory in NdsServerAuthenticate (1)...\n", 0 );
        FREE_POOL( psAuthMsg );
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    psLocalCredential = (PNDS_CREDENTIAL)( ((BYTE *) psAuthMsg) +
                                        sizeof( NDS_AUTH_MSG ) );

    //
    // Locate the public BSAFE key.
    //

    cbUserPublicBsafeKeyLen = NdsGetBsafeKey ( (BYTE *)(pNdsContext->PublicNdsKey),
                                               pNdsContext->PublicKeyLen,
                                               &pbUserPublicBsafeKey );

    //
    // Get the user's object Id but do not jump dir servers.  There is never
    // any optional data, so we don't really need to skip over it.
    //

    uUserName.MaximumLength = pNdsContext->Credential->userNameLength;
    uUserName.Length = uUserName.MaximumLength;
    uUserName.Buffer = ( WCHAR * ) ( ((BYTE *)pNdsContext->Credential) +
                                     sizeof( NDS_CREDENTIAL ) +
                                     pNdsContext->Credential->optDataSize );

    Status = NdsResolveNameKm( pIrpContext,
                               &uUserName,
                               &UserOID,
                               FALSE,
                               RSLV_DEREF_ALIASES | RSLV_CREATE_ID | RSLV_ENTRY_ID );

    if ( !NT_SUCCESS(Status) ) {
        goto ExitWithCleanup;
    }

    //
    // Issue the Begin Authenticate request to get the random server nonce.
    //

    Status = BeginAuthenticate( pIrpContext,
                                UserOID,
                                &dwServerRand );

    if ( !NT_SUCCESS(Status) ) {
        goto ExitWithCleanup;
    }

    //
    // Figure out the size of the zero-padded RSA Blocks.  We use the same
    // size as the modulus field of the public key (typically 56 bytes).
    //

    RSAGetModulus( pbUserPublicBsafeKey,
                   cbUserPublicBsafeKeyLen,
                   &rsaBlockSize);

    DebugTrace( 0, Dbg, "RSA block size for authentication: %d\n", rsaBlockSize );

    //
    // Prepare the credential and the 3 G-Q rands.  The credential,
    // xs, and ys go out in the packet; rs is secret.
    //

    RtlZeroMemory( ( BYTE * )psLocalCredential,
                   sizeof( NDS_CREDENTIAL ) +
                   MAX_NDS_NAME_SIZE +
                   9 * rsaBlockSize );

    dwLocalCredentialLen = sizeof( NDS_CREDENTIAL ) +
                           pNdsContext->Credential->optDataSize +
                           pNdsContext->Credential->userNameLength;

    DebugTrace( 0, Dbg, "Credential length is %d.\n", dwLocalCredentialLen );

    RtlCopyMemory( (BYTE *)psLocalCredential,
                   pNdsContext->Credential,
                   dwLocalCredentialLen );

    x = ( BYTE * ) psAuthMsg + sizeof( NDS_AUTH_MSG ) + dwLocalCredentialLen;
    y = x + ( 3 * rsaBlockSize );
    r = y + ( 3 * rsaBlockSize );

    rsaModSize = RSAGetInputBlockSize( pbUserPublicBsafeKey,
                                       cbUserPublicBsafeKeyLen );

    DebugTrace( 0, Dbg, "RSA modulus size: %d\n", rsaModSize );

    for ( i = 0; i < 3; i++ ) {

        //
        // Create Random numbers r1, r2 and r3  of modulus size.
        //

        GenRandomBytes( r + ( rsaBlockSize * i ), rsaModSize );

        //
        // Compute x = r**e mod N.
        //

        RSAPublic( pbUserPublicBsafeKey,
                   cbUserPublicBsafeKeyLen,
                   r + ( rsaBlockSize * i ),
                   rsaModSize,
                   x + ( rsaBlockSize * i ) );

    }

    //
    // Fill in the AuthMsg fields.
    //

    psAuthMsg->version = 0;
    psAuthMsg->svrRand = dwServerRand;
    psAuthMsg->verb = NDSV_FINISH_AUTHENTICATE;
    psAuthMsg->credentialLength = dwLocalCredentialLen;

    //
    // MD2 hash the auth message, credential and x's.
    //

    MD2( (BYTE *)psAuthMsg,
         sizeof( NDS_AUTH_MSG ) +
         psAuthMsg->credentialLength +
         ( 3 * rsaBlockSize ),
         CredentialHash );

    //
    // Compute yi = ri*(S**ci) mod N; c1,c2,c3 are the first three
    // 16 bit numbers in CredentialHash.
    //

    totalXLen = 3 * rsaBlockSize;

    for ( i = 0; i < 3; i++ ) {

        RSAModExp( pbUserPublicBsafeKey,
                   cbUserPublicBsafeKeyLen,
                   ( (BYTE *)(pNdsContext->Signature) ) + sizeof( NDS_SIGNATURE ),
                   pNdsContext->Signature->signDataLength,
                   &CredentialHash[i * sizeof( WORD )],
                   sizeof( WORD ),
                   y + ( rsaBlockSize * i) );

        RSAModMpy( pbUserPublicBsafeKey,
                   cbUserPublicBsafeKeyLen,
                   y + ( rsaBlockSize * i ),     // input1 = S**ci mod N
                   rsaModSize + 1,
                   r + ( rsaBlockSize * i ),     // input2 = ri
                   rsaModSize,
                   y + ( rsaBlockSize * i ) );   // output = yi
    }

    //
    // Send the auth proof.
    //

    NdsRequest.pRecvBufferVa = pbResponse;
    NdsRequest.dwRecvLen = NDS_BUFFER_SIZE;
    NdsRequest.pRecvMdl = NULL;

    NdsRequest.pRecvMdl = ALLOCATE_MDL( pbResponse,
                                        NDS_BUFFER_SIZE,
                                        FALSE,
                                        FALSE,
                                        NULL );
    if ( !NdsRequest.pRecvMdl ) {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto ExitWithCleanup;
    }

    MmProbeAndLockPages( NdsRequest.pRecvMdl,
                         KernelMode,
                         IoWriteAccess );

    Status = FragExWithWait( pIrpContext,
                             NDSV_FINISH_AUTHENTICATE,
                             &NdsRequest,
                             "DDDrDDWWWWr",
                             0,                                       // version
                             0,                                       // sessionKeyLen
                             psAuthMsg->credentialLength,             // credential len
                             (BYTE *)psLocalCredential,               // actual credential
                             ROUNDUP4( psAuthMsg->credentialLength ),
                             12 + ( totalXLen * 2 ),                  // length of remaining
                             1,                                       // proof version?
                             8,                                       // tag?
                             16,                                      // message digest base
                             3,                                       // proof order
                             totalXLen,                               // proofOrder*sizeof(x)
                             x,                                       // x1,x2,x3,y1,y2,y3
                             2 * totalXLen );

    MmUnlockPages( NdsRequest.pRecvMdl );
    FREE_MDL( NdsRequest.pRecvMdl );

    if ( !NT_SUCCESS( Status ) ) {
       goto ExitWithCleanup;
    }

    Status = NdsCompletionCodetoNtStatus( &NdsRequest );

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    cbResponseLen = NdsRequest.dwBytesWritten;
    DebugTrace( 0, Dbg, "Authentication returned ok status.\n", 0 );

    //
    // We completed NDS authentication, so clear out the name
    // and password in the SCB so that we use the credentials
    // from now on.
    //

    if ( pIrpContext->pScb->UserName.Buffer != NULL ) {

        DebugTrace( 0, Dbg, "Clearing out bindery login data.\n", 0 );

        pIrpContext->pScb->UserName.Length = 0;
        pIrpContext->pScb->UserName.MaximumLength = 0;

        pIrpContext->pScb->Password.Length = 0;
        pIrpContext->pScb->Password.MaximumLength = 0;

        FREE_POOL( pIrpContext->pScb->UserName.Buffer );
        RtlInitUnicodeString( &pIrpContext->pScb->UserName, NULL );
        RtlInitUnicodeString( &pIrpContext->pScb->Password, NULL );

    }

ExitWithCleanup:

    FREE_POOL( psAuthMsg );
    FREE_POOL( pbResponse );

    return Status;
}

NTSTATUS
BeginAuthenticate(
    IN PIRP_CONTEXT pIrpContext,
    IN DWORD        dwUserId,
    OUT DWORD       *pdwSvrRandom
)
/*++

Routine Description:

    Authenticate an NDS connection.
    The user must have already logged into the NDS tree.

Arguments:

    pIrpContext    - IrpContext for the server that we want to authenticate to.
    dwUserID       - The user OID that we are authenticating ourselves as.
    pdwSvrRandon   - The server random challenge.

Return value:

    NTSTATUS - The result of the operation.

--*/
{
    NTSTATUS Status;
    LOCKED_BUFFER NdsRequest;

    DWORD dwClientRand;

    PAGED_CODE();

    Status = NdsAllocateLockedBuffer( &NdsRequest, NDS_BUFFER_SIZE );

    if ( !NT_SUCCESS( Status ) ) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    GenRandomBytes( (BYTE *)&dwClientRand, sizeof( dwClientRand ) );

    Status = FragExWithWait( pIrpContext,
                             NDSV_BEGIN_AUTHENTICATE,
                             &NdsRequest,
                             "DDD",
                             0,               // Version.
                             dwUserId,        // Entry Id.
                             dwClientRand );  // Client's random challenge.

    if ( !NT_SUCCESS( Status ) ) {
        goto ExitWithCleanup;
    }

    Status = NdsCompletionCodetoNtStatus( &NdsRequest );

    if ( !NT_SUCCESS( Status ) ) {

        if ( Status == STATUS_BAD_NETWORK_PATH ) {
            Status = STATUS_NO_SUCH_USER;
        }

        goto ExitWithCleanup;
    }

    //
    // The reply actually contains all this, even though we don't look at it?
    //
    //     typedef struct {
    //         DWORD svrRand;
    //         DWORD totalLength;
    //         TAG_DATA_HEADER tdh;
    //         WORD unknown;                         // Always 2.
    //         DWORD encClientRandLength;
    //         CIPHER_BLOCK_HEADER keyCipherHdr;
    //         BYTE keyCipher[];
    //         CIPHER_BLOCK_HEADER encClientRandHdr;
    //         BYTE encClientRand[];
    //     } REPLY_BEGIN_AUTHENTICATE;
    //
    // Nah, that can't be right.
    //

    Status = ParseResponse( NULL,
                            NdsRequest.pRecvBufferVa,
                            NdsRequest.dwBytesWritten,
                            "G_D",
                            sizeof( DWORD ),
                            pdwSvrRandom );

    //
    // We either got it or we didn't.
    //

ExitWithCleanup:

    NdsFreeLockedBuffer( &NdsRequest );
    return Status;
}

NTSTATUS
NdsLicenseConnection(
    PIRP_CONTEXT pIrpContext
)
/*+++

    Send the license NCP to the server to license this connection.

---*/
{

    NTSTATUS Status;

    PAGED_CODE();

    DebugTrace( 0, Dbg, "Licensing connection to %wZ.\n", &(pIrpContext->pNpScb->pScb->UidServerName) );

    //
    // Change the authentication state of the connection.
    //

    Status = ExchangeWithWait ( pIrpContext,
                                SynchronousResponseCallback,
                                "SD",
                                NCP_ADMIN_FUNCTION,
                                NCP_CHANGE_CONN_AUTH_STATUS,
                                NCP_CONN_LICENSED );

    if ( !NT_SUCCESS( Status ) ) {
        DebugTrace( 0, Dbg, "Licensing failed to %wZ.\n", &(pIrpContext->pNpScb->pScb->UidServerName) );
    }

    return Status;

}

NTSTATUS
NdsUnlicenseConnection(
    PIRP_CONTEXT pIrpContext
)
/*+++

    Send the license NCP to the server to license this connection.

---*/
{

    NTSTATUS Status;

    PAGED_CODE();

    DebugTrace( 0, Dbg, "Unlicensing connection to %wZ.\n", &(pIrpContext->pNpScb->pScb->UidServerName) );

    //
    // Change the authentication state of the connection.
    //

    Status = ExchangeWithWait ( pIrpContext,
                                SynchronousResponseCallback,
                                "SD",
                                NCP_ADMIN_FUNCTION,
                                NCP_CHANGE_CONN_AUTH_STATUS,
                                NCP_CONN_NOT_LICENSED );

    if ( !NT_SUCCESS( Status ) ) {
        DebugTrace( 0, Dbg, "Unlicensing failed to %wZ.\n", &(pIrpContext->pNpScb->pScb->UidServerName) );
    }

    return Status;
}

int
NdsGetBsafeKey(
    UCHAR       *pPubKey,
    const int   pubKeyLen,
    UCHAR       **ppBsafeKey
)
/*++

Routine Description:

    Locate the BSAFE key from within the public key.  Note that this does
    not work for private keys in NDS format.  For private keys, you just
    skip the size word.

    This is verbatim from Win95.

Routine Arguments:

    pPubKey        - A pointer to the public key.
    pubKeyLen      - The length of the public key.
    ppBsafeKey     - The pointer to the BSAFE key in the public key.

Return Value:

    The length of the BSAFE key.

--*/
{
    int bsafePubKeyLen = 0, totalDNLen;
    char *pRcv;
    NTSTATUS Status;

    PAGED_CODE();

    totalDNLen = 0;
    Status = ParseResponse( NULL,
                            pPubKey,
                            pubKeyLen,
                            "G_W",
                            ( 2 * sizeof( DWORD ) ) + sizeof( WORD ),
                            &totalDNLen );

    if ( !NT_SUCCESS(Status) ) {
        goto Exit;
    }

    Status = ParseResponse( NULL,
                            pPubKey,
                            pubKeyLen - 12,
                            "G__W",
                            12,
                            5 * sizeof( WORD ) +
                            3 * sizeof( DWORD ) +
                            totalDNLen,
                            &bsafePubKeyLen );

    if ( !NT_SUCCESS(Status) ) {
        goto Exit;
    }

    *ppBsafeKey = (UCHAR *) pPubKey +
                            14 +
                            5 * sizeof( WORD ) +
                            3 * sizeof( DWORD ) +
                            totalDNLen;


Exit:

    return bsafePubKeyLen;
}

NTSTATUS
NdsLogoff(
    IN PIRP_CONTEXT pIrpContext
)
/*++

Routine Description:

    Sends a logout to the NDS tree, closes all NDS authenticated
    connections, and destroys the current set of NDS credentials.

    This routine acquires the credential list exclusive.

Arguments:

    pIrpContext - The IRP context for this request pointed to a
    valid dir server.

Notes:

    This is only called from DeleteConnection.  The caller owns
    the RCB exclusive and we will free it before returning.

--*/
{
    NTSTATUS Status;
    LOCKED_BUFFER NdsRequest;
    PNDS_SECURITY_CONTEXT pCredentials;
    PLOGON pLogon;
    PSCB pScb;
    PNONPAGED_SCB pNpScb;

    PLIST_ENTRY ScbQueueEntry;
    PNONPAGED_SCB pNextNpScb;
    KIRQL OldIrql;

    //
    // Grab the user's LOGON structure.
    //

    pNpScb = pIrpContext->pNpScb;
    pScb = pNpScb->pScb;

    //
    // The caller owns the RCB.
    //

    pLogon = FindUser( &pScb->UserUid, FALSE );

    if ( !pLogon ) {
        DebugTrace( 0, Dbg, "Invalid security context for NdsLogoff.\n", 0 );
        NwReleaseRcb( &NwRcb );
        NwDequeueIrpContext( pIrpContext, FALSE );
        return STATUS_NO_SUCH_USER;
    }

    //
    // Check to make sure that we have something to log off from.
    //

    Status = NdsLookupCredentials( &pScb->NdsTreeName,
                                   pLogon,
                                   &pCredentials,
                                   CREDENTIAL_WRITE,
                                   FALSE );

    if ( !NT_SUCCESS( Status )) {
        DebugTrace( 0, Dbg, "NdsLogoff: Nothing to log off from.\n", 0 );
        NwReleaseRcb( &NwRcb );
        NwDequeueIrpContext( pIrpContext, FALSE );
        return STATUS_NO_SUCH_LOGON_SESSION;
    }

    //
    // If the credentials are locked, then someone is already
    // doing a logout.
    //

    if ( pCredentials->CredentialLocked ) {
        DebugTrace( 0, Dbg, "NdsLogoff: Logoff already in progress.\n", 0 );
        NwReleaseCredList( pLogon );
        NwReleaseRcb( &NwRcb );
        NwDequeueIrpContext( pIrpContext, FALSE );
        return STATUS_DEVICE_BUSY;
    }

    //
    // Mark the credential locked so we can logout without
    // worrying about others logging in.
    //

    pCredentials->CredentialLocked = TRUE;

    //
    // Release all our resoures so we can jump around servers.
    //

    NwReleaseCredList( pLogon );
    NwReleaseRcb( &NwRcb );
    NwDequeueIrpContext( pIrpContext, FALSE );

    //
    // Look through the scb list for connections that are in use.  If all
    // existing connections can be closed down, then we can complete the logout.
    //

    KeAcquireSpinLock( &ScbSpinLock, &OldIrql );

    ScbQueueEntry = pNpScb->ScbLinks.Flink;

    if ( ScbQueueEntry == &ScbQueue ) {
        ScbQueueEntry = ScbQueue.Flink;
    }

    pNextNpScb = CONTAINING_RECORD( ScbQueueEntry, NONPAGED_SCB, ScbLinks );

    NwReferenceScb( pNextNpScb );
    KeReleaseSpinLock( &ScbSpinLock, OldIrql );

    while ( pNextNpScb != pNpScb ) {

        if ( pNextNpScb->pScb != NULL ) {

            //
            // Is this connection in use by us and is it NDS authenticated?
            //

            if ( RtlEqualUnicodeString( &pScb->NdsTreeName,
                                        &pNextNpScb->pScb->NdsTreeName,
                                        TRUE ) &&
                 ( pScb->UserUid.QuadPart == pNextNpScb->pScb->UserUid.QuadPart ) &&
                 ( pNextNpScb->State == SCB_STATE_IN_USE ) &&
                 ( pNextNpScb->pScb->UserName.Length == 0 ) ) {

                pIrpContext->pNpScb = pNextNpScb;
                pIrpContext->pScb = pNextNpScb->pScb;
                NwAppendToQueueAndWait( pIrpContext );

                if ( pNextNpScb->pScb->OpenFileCount == 0 ) {

                    //
                    // Can we close it anyway?  Should we check
                    // for open handles and the such here?
                    //

                    pNextNpScb->State = SCB_STATE_LOGIN_REQUIRED;
                    NwDequeueIrpContext( pIrpContext, FALSE );

                } else {

                    DebugTrace( 0, Dbg, "NdsLogoff: Other connections in use.\n", 0 );

                    NwAcquireExclusiveCredList( pLogon );
                    pCredentials->CredentialLocked = FALSE;
                    NwReleaseCredList( pLogon );

                    NwDereferenceScb( pNextNpScb );
                    NwDequeueIrpContext( pIrpContext, FALSE );

                    return STATUS_CONNECTION_IN_USE;

                }
            }

        }

        //
        // Select the next scb.
        //

        KeAcquireSpinLock( &ScbSpinLock, &OldIrql );

        ScbQueueEntry = pNextNpScb->ScbLinks.Flink;

        if ( ScbQueueEntry == &ScbQueue ) {
            ScbQueueEntry = ScbQueue.Flink;
        }

        NwDereferenceScb( pNextNpScb );
        pNextNpScb = CONTAINING_RECORD( ScbQueueEntry, NONPAGED_SCB, ScbLinks );

        NwReferenceScb( pNextNpScb );
        KeReleaseSpinLock( &ScbSpinLock, OldIrql );

    }

    NwDereferenceScb( pNpScb );

    //
    // The seed scb for the tree logout should be valid.
    //

    ASSERT( pNpScb->State == SCB_STATE_IN_USE );

    //
    // Check to make sure we can close the host scb.
    //

    if ( pScb->OpenFileCount != 0 ) {

        DebugTrace( 0, Dbg, "NdsLogoff: Seed connection in use.\n", 0 );

        NwAcquireExclusiveCredList( pLogon );
        pCredentials->CredentialLocked = FALSE;
        NwReleaseCredList( pLogon );

        return STATUS_CONNECTION_IN_USE;
    }

    //
    // We can actually do the logout, so remove the credentials from
    // the resource list, release the resource, and logout.
    //
    // If we are deleting the preferred tree credentials,
    // then we need to clear the preferred server.
    //

    if ( (pLogon->NdsCredentialList).Flink == &(pCredentials->Next) ) {

        if ( pLogon->ServerName.Buffer != NULL ) {

            DebugTrace( 0, Dbg, "Clearing preferred server at logout time.\n", 0 );

            FREE_POOL( pLogon->ServerName.Buffer );
            pLogon->ServerName.Length = pLogon->ServerName.MaximumLength = 0;
            pLogon->ServerName.Buffer = NULL;

        }
    }

    NwAcquireExclusiveCredList( pLogon );
    RemoveEntryList( &pCredentials->Next );
    NwReleaseCredList( pLogon );

    FreeNdsContext( pCredentials );

    pIrpContext->pNpScb = pNpScb;
    pIrpContext->pScb = pScb;

    Status = NdsAllocateLockedBuffer( &NdsRequest, NDS_BUFFER_SIZE );

    if ( NT_SUCCESS( Status ) ) {

        Status = FragExWithWait( pIrpContext,
                                 NDSV_LOGOUT,
                                 &NdsRequest,
                                 NULL );

        NdsFreeLockedBuffer( &NdsRequest );

    }

    NwAppendToQueueAndWait( pIrpContext );

    ASSERT( pScb->UserName.Buffer == NULL );
    pNpScb->State = SCB_STATE_LOGIN_REQUIRED;

    NwDequeueIrpContext( pIrpContext, FALSE );

    return STATUS_SUCCESS;

}