summaryrefslogtreecommitdiffstats
path: root/src/lib/krb5/ccache/cc_mslsa.c
blob: 416a7a52f404b6dc7e961dc33c0a6b9cf8588e61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/ccache/cc_mslsa.c */
/*
 * Copyright 2007 Secure Endpoints Inc.
 *
 * Copyright 2003,2004 by the Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * Export of this software from the United States of America may
 *   require a specific license from the United States Government.
 *   It is the responsibility of any person or organization contemplating
 *   export to obtain such a license before exporting.
 *
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of M.I.T. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  Furthermore if you modify this software you must label
 * your software as modified software and not distribute it in such a
 * fashion that it might be confused with the original M.I.T. software.
 * M.I.T. makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 *
 * Copyright 2000 by Carnegie Mellon University
 *
 * All Rights Reserved
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and that
 * both that copyright notice and this permission notice appear in
 * supporting documentation, and that the name of Carnegie Mellon
 * University not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior
 * permission.
 *
 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE FOR
 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Implementation of microsoft windows lsa credentials cache
 */

#ifdef _WIN32
#define UNICODE
#define _UNICODE

#include <ntstatus.h>
#define WIN32_NO_STATUS
#include "k5-int.h"
#include "com_err.h"
#include "cc-int.h"

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

#define SECURITY_WIN32
#include <security.h>
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#include <ntsecapi.h>


/* The following two features can only be built using the version of the
 * Platform SDK for Microsoft Windows Vista.  If AES support is defined
 * in NTSecAPI.h then we know that we have the required data structures.
 *
 * To build with the Windows XP SP2 SDK, the NTSecAPI.h from the Vista
 * SDK should be used in place of the XP SP2 SDK version.
 */
#ifdef TRUST_ATTRIBUTE_TRUST_USES_AES_KEYS
#define KERB_SUBMIT_TICKET 1
#define HAVE_CACHE_INFO_EX2 1
#endif

#define MAX_MSG_SIZE 256
#define MAX_MSPRINC_SIZE 1024

/* THREAD SAFETY
 * The functions is_windows_2000(), is_windows_xp(),
 * does_retrieve_ticket_cache_ticket() and does_query_ticket_cache_ex2()
 * contain static variables to cache the responses of the tests being
 * performed.  There is no harm in the test being performed more than
 * once since the result will always be the same.
 */

static BOOL
is_windows_2000 (void)
{
    static BOOL fChecked = FALSE;
    static BOOL fIsWin2K = FALSE;

    if (!fChecked)
    {
        OSVERSIONINFO Version;

        memset (&Version, 0x00, sizeof(Version));
        Version.dwOSVersionInfoSize = sizeof(Version);

        if (GetVersionEx (&Version))
        {
            if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
                Version.dwMajorVersion >= 5)
                fIsWin2K = TRUE;
        }
        fChecked = TRUE;
    }

    return fIsWin2K;
}

static BOOL
is_windows_xp (void)
{
    static BOOL fChecked = FALSE;
    static BOOL fIsWinXP = FALSE;

    if (!fChecked)
    {
        OSVERSIONINFO Version;

        memset (&Version, 0x00, sizeof(Version));
        Version.dwOSVersionInfoSize = sizeof(Version);

        if (GetVersionEx (&Version))
        {
            if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
                (Version.dwMajorVersion > 5 ||
                 Version.dwMajorVersion == 5 && Version.dwMinorVersion >= 1) )
                fIsWinXP = TRUE;
        }
        fChecked = TRUE;
    }

    return fIsWinXP;
}

static BOOL
is_windows_vista (void)
{
    static BOOL fChecked = FALSE;
    static BOOL fIsVista = FALSE;

    if (!fChecked)
    {
        OSVERSIONINFO Version;

        memset (&Version, 0x00, sizeof(Version));
        Version.dwOSVersionInfoSize = sizeof(Version);

        if (GetVersionEx (&Version))
        {
            if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT && Version.dwMajorVersion >= 6)
                fIsVista = TRUE;
        }
        fChecked = TRUE;
    }

    return fIsVista;
}

typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);

static BOOL
is_broken_wow64(void)
{
    static BOOL fChecked = FALSE;
    static BOOL fIsBrokenWow64 = FALSE;

    if (!fChecked)
    {
        BOOL isWow64 = FALSE;
        OSVERSIONINFO Version;
        HANDLE h1 = NULL;
        LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;

        h1 = GetModuleHandle(L"kernel32.dll");
        fnIsWow64Process =
            (LPFN_ISWOW64PROCESS)GetProcAddress(h1, "IsWow64Process");

        /* If we don't find the fnIsWow64Process function then we
         * are not running in a broken Wow64
         */
        if (fnIsWow64Process) {
            memset (&Version, 0x00, sizeof(Version));
            Version.dwOSVersionInfoSize = sizeof(Version);

            if (fnIsWow64Process(GetCurrentProcess(), &isWow64) &&
                GetVersionEx (&Version)) {
                if (isWow64 &&
                    Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
                    Version.dwMajorVersion < 6)
                    fIsBrokenWow64 = TRUE;
            }
        }
        fChecked = TRUE;
    }

    return fIsBrokenWow64;
}

/* This flag is only supported by versions of Windows which have obtained
 * a code change from Microsoft.   When the code change is installed,
 * setting this flag will cause all retrieved credentials to be stored
 * in the LSA cache.
 */
#ifndef KERB_RETRIEVE_TICKET_CACHE_TICKET
#define KERB_RETRIEVE_TICKET_CACHE_TICKET  0x20
#endif

static VOID
ShowWinError(LPSTR szAPI, DWORD dwError)
{

    // TODO - Write errors to event log so that scripts that don't
    // check for errors will still get something in the event log

    // This code is completely unsafe for use on non-English systems
    // Any call to this function will result in the FormatMessage
    // call failing and the program terminating.  This might have
    // been acceptable when this code was part of ms2mit.exe as
    // a standalone executable but it is not appropriate for a library

#ifdef COMMENT
    WCHAR szMsgBuf[MAX_MSG_SIZE];
    DWORD dwRes;

    printf("Error calling function %s: %lu\n", szAPI, dwError);

    dwRes = FormatMessage (
        FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        dwError,
        MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
        szMsgBuf,
        MAX_MSG_SIZE,
        NULL);
    if (0 == dwRes) {
        printf("FormatMessage failed with %d\n", GetLastError());
        ExitProcess(EXIT_FAILURE);
    }

    printf("%S",szMsgBuf);
#endif /* COMMENT */
}

static VOID
ShowLsaError(LPSTR szAPI, NTSTATUS Status)
{
    //
    // Convert the NTSTATUS to Winerror. Then call ShowWinError().
    //
    ShowWinError(szAPI, LsaNtStatusToWinError(Status));
}

static BOOL
WINAPI
UnicodeToANSI(LPTSTR lpInputString, LPSTR lpszOutputString, int nOutStringLen)
{
    CPINFO CodePageInfo;

    GetCPInfo(CP_ACP, &CodePageInfo);

    if (CodePageInfo.MaxCharSize > 1) {
        // Only supporting non-Unicode strings
        int reqLen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR) lpInputString, -1,
                                         NULL, 0, NULL, NULL);
        if ( reqLen > nOutStringLen)
        {
            return FALSE;
        } else {
            if (WideCharToMultiByte(CP_ACP,
                                    /* WC_NO_BEST_FIT_CHARS | */ WC_COMPOSITECHECK,
                                    (LPCWSTR) lpInputString, -1,
                                    lpszOutputString,
                                    nOutStringLen, NULL, NULL) == 0)
                return FALSE;
        }
    }
    else
    {
        // Looks like unicode, better translate it
        if (WideCharToMultiByte(CP_ACP,
                                /* WC_NO_BEST_FIT_CHARS | */ WC_COMPOSITECHECK,
                                (LPCWSTR) lpInputString, -1,
                                lpszOutputString,
                                nOutStringLen, NULL, NULL) == 0)
            return FALSE;
    }

    return TRUE;
}  // UnicodeToANSI

static VOID
WINAPI
ANSIToUnicode(LPCSTR lpInputString, LPWSTR lpszOutputString, int nOutStringLen)
{

    CPINFO CodePageInfo;

    GetCPInfo(CP_ACP, &CodePageInfo);

    MultiByteToWideChar(CP_ACP, 0, lpInputString, -1,
                        lpszOutputString, nOutStringLen);
}  // ANSIToUnicode


static void
MITPrincToMSPrinc(krb5_context context, krb5_principal principal, UNICODE_STRING * msprinc)
{
    char *aname = NULL;

    if (!krb5_unparse_name(context, principal, &aname)) {
        msprinc->Length = strlen(aname) * sizeof(WCHAR);
        if ( msprinc->Length <= msprinc->MaximumLength )
            ANSIToUnicode(aname, msprinc->Buffer, msprinc->MaximumLength);
        else
            msprinc->Length = 0;
        krb5_free_unparsed_name(context,aname);
    }
}

static BOOL
UnicodeStringToMITPrinc(UNICODE_STRING *service, WCHAR *realm, krb5_context context,
                        krb5_principal *principal)
{
    WCHAR princbuf[512];
    char aname[512];

    princbuf[0]=0;
    wcsncpy(princbuf, service->Buffer, service->Length/sizeof(WCHAR));
    princbuf[service->Length/sizeof(WCHAR)]=0;
    wcscat(princbuf, L"@");
    wcscat(princbuf, realm);
    if (UnicodeToANSI(princbuf, aname, sizeof(aname))) {
        if (krb5_parse_name(context, aname, principal) == 0)
            return TRUE;
    }
    return FALSE;
}


static BOOL
KerbExternalNameToMITPrinc(KERB_EXTERNAL_NAME *msprinc, WCHAR *realm, krb5_context context,
                           krb5_principal *principal)
{
    WCHAR princbuf[512],tmpbuf[128];
    char aname[512];
    USHORT i;
    princbuf[0]=0;
    for (i=0;i<msprinc->NameCount;i++) {
        wcsncpy(tmpbuf, msprinc->Names[i].Buffer,
                msprinc->Names[i].Length/sizeof(WCHAR));
        tmpbuf[msprinc->Names[i].Length/sizeof(WCHAR)]=0;
        if (princbuf[0])
            wcscat(princbuf, L"/");
        wcscat(princbuf, tmpbuf);
    }
    wcscat(princbuf, L"@");
    wcscat(princbuf, realm);
    if (UnicodeToANSI(princbuf, aname, sizeof(aname))) {
        if (krb5_parse_name(context, aname, principal) == 0)
            return TRUE;
    }
    return FALSE;
}

static time_t
FileTimeToUnixTime(LARGE_INTEGER *ltime)
{
    FILETIME filetime, localfiletime;
    SYSTEMTIME systime;
    struct tm utime;
    filetime.dwLowDateTime=ltime->LowPart;
    filetime.dwHighDateTime=ltime->HighPart;
    FileTimeToLocalFileTime(&filetime, &localfiletime);
    FileTimeToSystemTime(&localfiletime, &systime);
    utime.tm_sec=systime.wSecond;
    utime.tm_min=systime.wMinute;
    utime.tm_hour=systime.wHour;
    utime.tm_mday=systime.wDay;
    utime.tm_mon=systime.wMonth-1;
    utime.tm_year=systime.wYear-1900;
    utime.tm_isdst=-1;
    return(mktime(&utime));
}

static void
MSSessionKeyToMITKeyblock(KERB_CRYPTO_KEY *mskey, krb5_context context, krb5_keyblock *keyblock)
{
    krb5_keyblock tmpblock;
    tmpblock.magic=KV5M_KEYBLOCK;
    tmpblock.enctype=mskey->KeyType;
    tmpblock.length=mskey->Length;
    tmpblock.contents=mskey->Value;
    krb5_copy_keyblock_contents(context, &tmpblock, keyblock);
}

static BOOL
IsMSSessionKeyNull(KERB_CRYPTO_KEY *mskey)
{
    DWORD i;

    if (mskey->KeyType == KERB_ETYPE_NULL)
        return TRUE;

    for ( i=0; i<mskey->Length; i++ ) {
        if (mskey->Value[i])
            return FALSE;
    }

    return TRUE;
}

static void
MSFlagsToMITFlags(ULONG msflags, ULONG *mitflags)
{
    *mitflags=msflags;
}

static BOOL
MSTicketToMITTicket(KERB_EXTERNAL_TICKET *msticket, krb5_context context, krb5_data *ticket)
{
    krb5_data tmpdata, *newdata = 0;
    krb5_error_code rc;

    tmpdata.magic=KV5M_DATA;
    tmpdata.length=msticket->EncodedTicketSize;
    tmpdata.data=msticket->EncodedTicket;

    // this is ugly and will break krb5_free_data()
    // now that this is being done within the library it won't break krb5_free_data()
    rc = krb5_copy_data(context, &tmpdata, &newdata);
    if (rc)
        return FALSE;

    memcpy(ticket, newdata, sizeof(krb5_data));
    free(newdata);
    return TRUE;
}

/*
 * PreserveInitialTicketIdentity()
 *
 * This will find the "PreserveInitialTicketIdentity" key in the registry.
 * Returns 1 to preserve and 0 to not.
 */

static DWORD
PreserveInitialTicketIdentity(void)
{
    HKEY hKey;
    DWORD size = sizeof(DWORD);
    DWORD type = REG_DWORD;
    const char *key_path = "Software\\MIT\\Kerberos5";
    const char *value_name = "PreserveInitialTicketIdentity";
    DWORD retval = 1;     /* default to Preserve */

    if (RegOpenKeyExA(HKEY_CURRENT_USER, key_path, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
        goto syskey;
    if (RegQueryValueExA(hKey, value_name, 0, &type, (LPBYTE)&retval, &size) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        goto syskey;
    }
    RegCloseKey(hKey);
    goto done;

syskey:
    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, key_path, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
        goto done;
    if (RegQueryValueExA(hKey, value_name, 0, &type, (LPBYTE)&retval, &size) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        goto done;
    }
    RegCloseKey(hKey);

done:
    return retval;
}


static BOOL
MSCredToMITCred(KERB_EXTERNAL_TICKET *msticket, UNICODE_STRING ClientRealm,
                krb5_context context, krb5_creds *creds)
{
    WCHAR wrealm[128];
    ZeroMemory(creds, sizeof(krb5_creds));
    creds->magic=KV5M_CREDS;

    // construct Client Principal
    wcsncpy(wrealm, ClientRealm.Buffer, ClientRealm.Length/sizeof(WCHAR));
    wrealm[ClientRealm.Length/sizeof(WCHAR)]=0;
    if (!KerbExternalNameToMITPrinc(msticket->ClientName, wrealm, context, &creds->client))
        return FALSE;

    // construct Service Principal
    wcsncpy(wrealm, msticket->DomainName.Buffer,
            msticket->DomainName.Length/sizeof(WCHAR));
    wrealm[msticket->DomainName.Length/sizeof(WCHAR)]=0;
    if (!KerbExternalNameToMITPrinc(msticket->ServiceName, wrealm, context, &creds->server))
        return FALSE;
    MSSessionKeyToMITKeyblock(&msticket->SessionKey, context,
                              &creds->keyblock);
    MSFlagsToMITFlags(msticket->TicketFlags, &creds->ticket_flags);
    creds->times.starttime=FileTimeToUnixTime(&msticket->StartTime);
    creds->times.endtime=FileTimeToUnixTime(&msticket->EndTime);
    creds->times.renew_till=FileTimeToUnixTime(&msticket->RenewUntil);

    creds->addresses = NULL;

    return MSTicketToMITTicket(msticket, context, &creds->ticket);
}

#ifdef HAVE_CACHE_INFO_EX2
/* CacheInfoEx2ToMITCred is used when we do not need the real ticket */
static BOOL
CacheInfoEx2ToMITCred(KERB_TICKET_CACHE_INFO_EX2 *info,
                      krb5_context context, krb5_creds *creds)
{
    WCHAR wrealm[128];
    ZeroMemory(creds, sizeof(krb5_creds));
    creds->magic=KV5M_CREDS;

    // construct Client Principal
    wcsncpy(wrealm, info->ClientRealm.Buffer, info->ClientRealm.Length/sizeof(WCHAR));
    wrealm[info->ClientRealm.Length/sizeof(WCHAR)]=0;
    if (!UnicodeStringToMITPrinc(&info->ClientName, wrealm, context, &creds->client))
        return FALSE;

    // construct Service Principal
    wcsncpy(wrealm, info->ServerRealm.Buffer,
            info->ServerRealm.Length/sizeof(WCHAR));
    wrealm[info->ServerRealm.Length/sizeof(WCHAR)]=0;
    if (!UnicodeStringToMITPrinc(&info->ServerName, wrealm, context, &creds->server))
        return FALSE;

    creds->keyblock.magic = KV5M_KEYBLOCK;
    creds->keyblock.enctype = info->SessionKeyType;
    creds->ticket_flags = info->TicketFlags;
    MSFlagsToMITFlags(info->TicketFlags, &creds->ticket_flags);
    creds->times.starttime=FileTimeToUnixTime(&info->StartTime);
    creds->times.endtime=FileTimeToUnixTime(&info->EndTime);
    creds->times.renew_till=FileTimeToUnixTime(&info->RenewTime);

    /* MS Tickets are addressless.  MIT requires an empty address
     * not a NULL list of addresses.
     */
    creds->addresses = (krb5_address **)malloc(sizeof(krb5_address *));
    memset(creds->addresses, 0, sizeof(krb5_address *));

    return TRUE;
}
#endif /* HAVE_CACHE_INFO_EX2 */

static BOOL
PackageConnectLookup(HANDLE *pLogonHandle, ULONG *pPackageId)
{
    LSA_STRING Name;
    NTSTATUS Status;

    Status = LsaConnectUntrusted(
        pLogonHandle
    );

    if (FAILED(Status))
    {
        ShowLsaError("LsaConnectUntrusted", Status);
        return FALSE;
    }

    Name.Buffer = MICROSOFT_KERBEROS_NAME_A;
    Name.Length = strlen(Name.Buffer);
    Name.MaximumLength = Name.Length + 1;

    Status = LsaLookupAuthenticationPackage(
        *pLogonHandle,
        &Name,
        pPackageId
    );

    if (FAILED(Status))
    {
        ShowLsaError("LsaLookupAuthenticationPackage", Status);
        return FALSE;
    }

    return TRUE;

}

static BOOL
does_retrieve_ticket_cache_ticket (void)
{
    static BOOL fChecked = FALSE;
    static BOOL fCachesTicket = FALSE;

    if (!fChecked)
    {
        NTSTATUS Status = 0;
        NTSTATUS SubStatus = 0;
        HANDLE LogonHandle;
        ULONG  PackageId;
        ULONG RequestSize;
        PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
        PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
        ULONG ResponseSize;

        RequestSize = sizeof(*pTicketRequest) + 1;

        if (!PackageConnectLookup(&LogonHandle, &PackageId))
            return FALSE;

        pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
        if (!pTicketRequest) {
            LsaDeregisterLogonProcess(LogonHandle);
            return FALSE;
        }

        pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
        pTicketRequest->LogonId.LowPart = 0;
        pTicketRequest->LogonId.HighPart = 0;
        pTicketRequest->TargetName.Length = 0;
        pTicketRequest->TargetName.MaximumLength = 0;
        pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
        pTicketRequest->CacheOptions =
            KERB_RETRIEVE_TICKET_DONT_USE_CACHE | KERB_RETRIEVE_TICKET_CACHE_TICKET;
        pTicketRequest->EncryptionType = 0;
        pTicketRequest->TicketFlags = 0;

        Status = LsaCallAuthenticationPackage( LogonHandle,
                                               PackageId,
                                               pTicketRequest,
                                               RequestSize,
                                               &pTicketResponse,
                                               &ResponseSize,
                                               &SubStatus
        );

        LocalFree(pTicketRequest);
        LsaDeregisterLogonProcess(LogonHandle);

        if (FAILED(Status) || FAILED(SubStatus)) {
            if (SubStatus == STATUS_NOT_SUPPORTED ||
                SubStatus == SEC_E_NO_CREDENTIALS)
                /* The combination of the two CacheOption flags
                 * is not supported; therefore, the new flag is supported
                 */
                fCachesTicket = TRUE;
        }
        fChecked = TRUE;
    }

    return fCachesTicket;
}

#ifdef HAVE_CACHE_INFO_EX2
static BOOL
does_query_ticket_cache_ex2 (void)
{
    static BOOL fChecked = FALSE;
    static BOOL fEx2Response = FALSE;

    if (!fChecked)
    {
        NTSTATUS Status = 0;
        NTSTATUS SubStatus = 0;
        HANDLE LogonHandle;
        ULONG  PackageId;
        ULONG RequestSize;
        PKERB_QUERY_TKT_CACHE_REQUEST pCacheRequest = NULL;
        PKERB_QUERY_TKT_CACHE_EX2_RESPONSE pCacheResponse = NULL;
        ULONG ResponseSize;

        RequestSize = sizeof(*pCacheRequest) + 1;

        if (!PackageConnectLookup(&LogonHandle, &PackageId))
            return FALSE;

        pCacheRequest = (PKERB_QUERY_TKT_CACHE_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
        if (!pCacheRequest) {
            LsaDeregisterLogonProcess(LogonHandle);
            return FALSE;
        }

        pCacheRequest->MessageType = KerbQueryTicketCacheEx2Message;
        pCacheRequest->LogonId.LowPart = 0;
        pCacheRequest->LogonId.HighPart = 0;

        Status = LsaCallAuthenticationPackage( LogonHandle,
                                               PackageId,
                                               pCacheRequest,
                                               RequestSize,
                                               &pCacheResponse,
                                               &ResponseSize,
                                               &SubStatus
        );

        LocalFree(pCacheRequest);
        LsaDeregisterLogonProcess(LogonHandle);

        if (!(FAILED(Status) || FAILED(SubStatus))) {
            LsaFreeReturnBuffer(pCacheResponse);
            fEx2Response = TRUE;
        }
        fChecked = TRUE;
    }

    return fEx2Response;
}
#endif /* HAVE_CACHE_INFO_EX2 */

static DWORD
ConcatenateUnicodeStrings(UNICODE_STRING *pTarget, UNICODE_STRING Source1, UNICODE_STRING Source2)
{
    //
    // The buffers for Source1 and Source2 cannot overlap pTarget's
    // buffer.  Source1.Length + Source2.Length must be <= 0xFFFF,
    // otherwise we overflow...
    //

    USHORT TotalSize = Source1.Length + Source2.Length;
    PBYTE buffer = (PBYTE) pTarget->Buffer;

    if (TotalSize > pTarget->MaximumLength)
        return ERROR_INSUFFICIENT_BUFFER;

    if ( pTarget->Buffer != Source1.Buffer )
        memcpy(buffer, Source1.Buffer, Source1.Length);
    memcpy(buffer + Source1.Length, Source2.Buffer, Source2.Length);

    pTarget->Length = TotalSize;
    return ERROR_SUCCESS;
}

static BOOL
get_STRING_from_registry(HKEY hBaseKey, char * key, char * value, char * outbuf, DWORD  outlen)
{
    HKEY hKey;
    DWORD dwCount;
    LONG rc;

    if (!outbuf || outlen == 0)
        return FALSE;

    rc = RegOpenKeyExA(hBaseKey, key, 0, KEY_QUERY_VALUE, &hKey);
    if (rc)
        return FALSE;

    dwCount = outlen;
    rc = RegQueryValueExA(hKey, value, 0, 0, (LPBYTE) outbuf, &dwCount);
    RegCloseKey(hKey);

    return rc?FALSE:TRUE;
}

static BOOL
GetSecurityLogonSessionData(PSECURITY_LOGON_SESSION_DATA * ppSessionData)
{
    NTSTATUS Status = 0;
    HANDLE  TokenHandle;
    TOKEN_STATISTICS Stats;
    DWORD   ReqLen;
    BOOL    Success;

    if (!ppSessionData)
        return FALSE;
    *ppSessionData = NULL;

    Success = OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &TokenHandle );
    if ( !Success )
        return FALSE;

    Success = GetTokenInformation( TokenHandle, TokenStatistics, &Stats, sizeof(TOKEN_STATISTICS), &ReqLen );
    CloseHandle( TokenHandle );
    if ( !Success )
        return FALSE;

    Status = LsaGetLogonSessionData( &Stats.AuthenticationId, ppSessionData );
    if ( FAILED(Status) || !ppSessionData )
        return FALSE;

    return TRUE;
}

//
// IsKerberosLogon() does not validate whether or not there are valid tickets in the
// cache.  It validates whether or not it is reasonable to assume that if we
// attempted to retrieve valid tickets we could do so.  Microsoft does not
// automatically renew expired tickets.  Therefore, the cache could contain
// expired or invalid tickets.  Microsoft also caches the user's password
// and will use it to retrieve new TGTs if the cache is empty and tickets
// are requested.

static BOOL
IsKerberosLogon(VOID)
{
    PSECURITY_LOGON_SESSION_DATA pSessionData = NULL;
    BOOL    Success = FALSE;

    if ( GetSecurityLogonSessionData(&pSessionData) ) {
        if ( pSessionData->AuthenticationPackage.Buffer ) {
            WCHAR buffer[256];
            WCHAR *usBuffer;
            int usLength;

            Success = FALSE;
            usBuffer = (pSessionData->AuthenticationPackage).Buffer;
            usLength = (pSessionData->AuthenticationPackage).Length;
            if (usLength < 256)
            {
                lstrcpynW (buffer, usBuffer, usLength);
                lstrcatW (buffer,L"");
                if ( !lstrcmpW(L"Kerberos",buffer) )
                    Success = TRUE;
            }
        }
        LsaFreeReturnBuffer(pSessionData);
    }
    return Success;
}

static DWORD
ConstructTicketRequest(UNICODE_STRING DomainName, PKERB_RETRIEVE_TKT_REQUEST * outRequest, ULONG * outSize)
{
    DWORD Error;
    UNICODE_STRING TargetPrefix;
    USHORT TargetSize;
    ULONG RequestSize;
    PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;

    *outRequest = NULL;
    *outSize = 0;

    //
    // Set up the "krbtgt/" target prefix into a UNICODE_STRING so we
    // can easily concatenate it later.
    //

    TargetPrefix.Buffer = L"krbtgt/";
    TargetPrefix.Length = wcslen(TargetPrefix.Buffer) * sizeof(WCHAR);
    TargetPrefix.MaximumLength = TargetPrefix.Length;

    //
    // We will need to concatenate the "krbtgt/" prefix and the
    // Logon Session's DnsDomainName into our request's target name.
    //
    // Therefore, first compute the necessary buffer size for that.
    //
    // Note that we might theoretically have integer overflow.
    //

    TargetSize = TargetPrefix.Length + DomainName.Length;

    //
    // The ticket request buffer needs to be a single buffer.  That buffer
    // needs to include the buffer for the target name.
    //

    RequestSize = sizeof(*pTicketRequest) + TargetSize;

    //
    // Allocate the request buffer and make sure it's zero-filled.
    //

    pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
    if (!pTicketRequest)
        return GetLastError();

    //
    // Concatenate the target prefix with the previous reponse's
    // target domain.
    //

    pTicketRequest->TargetName.Length = 0;
    pTicketRequest->TargetName.MaximumLength = TargetSize;
    pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
    Error = ConcatenateUnicodeStrings(&(pTicketRequest->TargetName),
                                      TargetPrefix,
                                      DomainName);
    *outRequest = pTicketRequest;
    *outSize    = RequestSize;
    return Error;
}

static BOOL
PurgeAllTickets(HANDLE LogonHandle, ULONG  PackageId)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    KERB_PURGE_TKT_CACHE_REQUEST PurgeRequest;

    PurgeRequest.MessageType = KerbPurgeTicketCacheMessage;
    PurgeRequest.LogonId.LowPart = 0;
    PurgeRequest.LogonId.HighPart = 0;
    PurgeRequest.ServerName.Buffer = L"";
    PurgeRequest.ServerName.Length = 0;
    PurgeRequest.ServerName.MaximumLength = 0;
    PurgeRequest.RealmName.Buffer = L"";
    PurgeRequest.RealmName.Length = 0;
    PurgeRequest.RealmName.MaximumLength = 0;
    Status = LsaCallAuthenticationPackage(LogonHandle,
                                          PackageId,
                                          &PurgeRequest,
                                          sizeof(PurgeRequest),
                                          NULL,
                                          NULL,
                                          &SubStatus
    );
    if (FAILED(Status) || FAILED(SubStatus))
        return FALSE;
    return TRUE;
}

static BOOL
PurgeTicket2000( HANDLE LogonHandle, ULONG  PackageId,
                 krb5_context context, krb5_creds *cred )
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    KERB_PURGE_TKT_CACHE_REQUEST * pPurgeRequest;
    DWORD dwRequestLen = sizeof(KERB_PURGE_TKT_CACHE_REQUEST) + 2048;
    char * sname = NULL, * srealm = NULL;

    if (krb5_unparse_name(context, cred->server, &sname))
        return FALSE;

    pPurgeRequest = malloc(dwRequestLen);
    if ( pPurgeRequest == NULL )
        return FALSE;
    memset(pPurgeRequest, 0, dwRequestLen);

    srealm = strrchr(sname, '@');
    *srealm = '\0';
    srealm++;

    pPurgeRequest->MessageType = KerbPurgeTicketCacheMessage;
    pPurgeRequest->LogonId.LowPart = 0;
    pPurgeRequest->LogonId.HighPart = 0;
    pPurgeRequest->ServerName.Buffer = (PWSTR)(((CHAR *)pPurgeRequest)+sizeof(KERB_PURGE_TKT_CACHE_REQUEST));
    pPurgeRequest->ServerName.Length = strlen(sname)*sizeof(WCHAR);
    pPurgeRequest->ServerName.MaximumLength = 256;
    ANSIToUnicode(sname, pPurgeRequest->ServerName.Buffer,
                  pPurgeRequest->ServerName.MaximumLength);
    pPurgeRequest->RealmName.Buffer = (PWSTR)(((CHAR *)pPurgeRequest)+sizeof(KERB_PURGE_TKT_CACHE_REQUEST)+512);
    pPurgeRequest->RealmName.Length = strlen(srealm)*sizeof(WCHAR);
    pPurgeRequest->RealmName.MaximumLength = 256;
    ANSIToUnicode(srealm, pPurgeRequest->RealmName.Buffer,
                  pPurgeRequest->RealmName.MaximumLength);

    Status = LsaCallAuthenticationPackage( LogonHandle,
                                           PackageId,
                                           pPurgeRequest,
                                           dwRequestLen,
                                           NULL,
                                           NULL,
                                           &SubStatus
    );
    free(pPurgeRequest);
    krb5_free_unparsed_name(context, sname);

    if (FAILED(Status) || FAILED(SubStatus))
        return FALSE;

    return TRUE;
}


static BOOL
PurgeTicketXP( HANDLE LogonHandle, ULONG  PackageId,
               krb5_context context, krb5_flags flags, krb5_creds *cred)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    KERB_PURGE_TKT_CACHE_EX_REQUEST * pPurgeRequest;
    DWORD dwRequestLen = sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST) + 4096;
    char * cname = NULL, * crealm = NULL;
    char * sname = NULL, * srealm = NULL;

    if (krb5_unparse_name(context, cred->client, &cname))
        return FALSE;

    if (krb5_unparse_name(context, cred->server, &sname)) {
        krb5_free_unparsed_name(context, cname);
        return FALSE;
    }

    pPurgeRequest = malloc(dwRequestLen);
    if ( pPurgeRequest == NULL )
        return FALSE;
    memset(pPurgeRequest, 0, dwRequestLen);

    crealm = strrchr(cname, '@');
    *crealm = '\0';
    crealm++;

    srealm = strrchr(sname, '@');
    *srealm = '\0';
    srealm++;

    pPurgeRequest->MessageType = KerbPurgeTicketCacheExMessage;
    pPurgeRequest->LogonId.LowPart = 0;
    pPurgeRequest->LogonId.HighPart = 0;
    pPurgeRequest->Flags = 0;
    pPurgeRequest->TicketTemplate.ClientName.Buffer = (PWSTR)((CHAR *)pPurgeRequest + sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST));
    pPurgeRequest->TicketTemplate.ClientName.Length = strlen(cname)*sizeof(WCHAR);
    pPurgeRequest->TicketTemplate.ClientName.MaximumLength = 256;
    ANSIToUnicode(cname, pPurgeRequest->TicketTemplate.ClientName.Buffer,
                  pPurgeRequest->TicketTemplate.ClientName.MaximumLength);

    pPurgeRequest->TicketTemplate.ClientRealm.Buffer = (PWSTR)(((CHAR *)pPurgeRequest)+sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST) + 512);
    pPurgeRequest->TicketTemplate.ClientRealm.Length = strlen(crealm)*sizeof(WCHAR);
    pPurgeRequest->TicketTemplate.ClientRealm.MaximumLength = 256;
    ANSIToUnicode(crealm, pPurgeRequest->TicketTemplate.ClientRealm.Buffer,
                  pPurgeRequest->TicketTemplate.ClientRealm.MaximumLength);

    pPurgeRequest->TicketTemplate.ServerName.Buffer = (PWSTR)(((CHAR *)pPurgeRequest)+sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST) + 1024);
    pPurgeRequest->TicketTemplate.ServerName.Length = strlen(sname)*sizeof(WCHAR);
    pPurgeRequest->TicketTemplate.ServerName.MaximumLength = 256;
    ANSIToUnicode(sname, pPurgeRequest->TicketTemplate.ServerName.Buffer,
                  pPurgeRequest->TicketTemplate.ServerName.MaximumLength);

    pPurgeRequest->TicketTemplate.ServerRealm.Buffer = (PWSTR)(((CHAR *)pPurgeRequest)+sizeof(KERB_PURGE_TKT_CACHE_EX_REQUEST) + 1536);
    pPurgeRequest->TicketTemplate.ServerRealm.Length = strlen(srealm)*sizeof(WCHAR);
    pPurgeRequest->TicketTemplate.ServerRealm.MaximumLength = 256;
    ANSIToUnicode(srealm, pPurgeRequest->TicketTemplate.ServerRealm.Buffer,
                  pPurgeRequest->TicketTemplate.ServerRealm.MaximumLength);

    pPurgeRequest->TicketTemplate.StartTime;
    pPurgeRequest->TicketTemplate.EndTime;
    pPurgeRequest->TicketTemplate.RenewTime;
    pPurgeRequest->TicketTemplate.EncryptionType = cred->keyblock.enctype;
    pPurgeRequest->TicketTemplate.TicketFlags = flags;

    Status = LsaCallAuthenticationPackage( LogonHandle,
                                           PackageId,
                                           pPurgeRequest,
                                           dwRequestLen,
                                           NULL,
                                           NULL,
                                           &SubStatus
    );
    free(pPurgeRequest);
    krb5_free_unparsed_name(context,cname);
    krb5_free_unparsed_name(context,sname);

    if (FAILED(Status) || FAILED(SubStatus))
        return FALSE;
    return TRUE;
}

#ifdef KERB_SUBMIT_TICKET
static BOOL
KerbSubmitTicket( HANDLE LogonHandle, ULONG  PackageId,
                  krb5_context context, krb5_creds *cred)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    KERB_SUBMIT_TKT_REQUEST * pSubmitRequest;
    DWORD dwRequestLen;
    krb5_auth_context auth_context;
    krb5_keyblock * keyblock = 0;
    krb5_replay_data replaydata;
    krb5_data * krb_cred = 0;
    krb5_error_code rc;

    if (krb5_auth_con_init(context, &auth_context)) {
        return FALSE;
    }

    if (krb5_auth_con_setflags(context, auth_context,
                               KRB5_AUTH_CONTEXT_RET_TIME)) {
        return FALSE;
    }

    krb5_auth_con_getsendsubkey(context, auth_context, &keyblock);
    if (keyblock == NULL)
        krb5_auth_con_getkey(context, auth_context, &keyblock);

    /* make up a key, any key, that can be used to generate the
     * encrypted KRB_CRED pdu.  The Vista release LSA requires
     * that an enctype other than NULL be used. */
    if (keyblock == NULL) {
        keyblock = (krb5_keyblock *)malloc(sizeof(krb5_keyblock));
        keyblock->enctype = ENCTYPE_ARCFOUR_HMAC;
        keyblock->length = 16;
        keyblock->contents = (krb5_octet *)malloc(16);
        keyblock->contents[0] = 0xde;
        keyblock->contents[1] = 0xad;
        keyblock->contents[2] = 0xbe;
        keyblock->contents[3] = 0xef;
        keyblock->contents[4] = 0xfe;
        keyblock->contents[5] = 0xed;
        keyblock->contents[6] = 0xf0;
        keyblock->contents[7] = 0xd;
        keyblock->contents[8] = 0xde;
        keyblock->contents[9] = 0xad;
        keyblock->contents[10] = 0xbe;
        keyblock->contents[11] = 0xef;
        keyblock->contents[12] = 0xfe;
        keyblock->contents[13] = 0xed;
        keyblock->contents[14] = 0xf0;
        keyblock->contents[15] = 0xd;
        krb5_auth_con_setsendsubkey(context, auth_context, keyblock);
    }
    rc = krb5_mk_1cred(context, auth_context, cred, &krb_cred, &replaydata);
    if (rc) {
        krb5_auth_con_free(context, auth_context);
        if (keyblock)
            krb5_free_keyblock(context, keyblock);
        if (krb_cred)
            krb5_free_data(context, krb_cred);
        return FALSE;
    }

    dwRequestLen = sizeof(KERB_SUBMIT_TKT_REQUEST) + krb_cred->length + (keyblock ? keyblock->length : 0);

    pSubmitRequest = (PKERB_SUBMIT_TKT_REQUEST)malloc(dwRequestLen);
    memset(pSubmitRequest, 0, dwRequestLen);

    pSubmitRequest->MessageType = KerbSubmitTicketMessage;
    pSubmitRequest->LogonId.LowPart = 0;
    pSubmitRequest->LogonId.HighPart = 0;
    pSubmitRequest->Flags = 0;

    if (keyblock) {
        pSubmitRequest->Key.KeyType = keyblock->enctype;
        pSubmitRequest->Key.Length = keyblock->length;
        pSubmitRequest->Key.Offset = sizeof(KERB_SUBMIT_TKT_REQUEST)+krb_cred->length;
    } else {
        pSubmitRequest->Key.KeyType = ENCTYPE_NULL;
        pSubmitRequest->Key.Length = 0;
        pSubmitRequest->Key.Offset = 0;
    }
    pSubmitRequest->KerbCredSize = krb_cred->length;
    pSubmitRequest->KerbCredOffset = sizeof(KERB_SUBMIT_TKT_REQUEST);
    memcpy(((CHAR *)pSubmitRequest)+sizeof(KERB_SUBMIT_TKT_REQUEST),
           krb_cred->data, krb_cred->length);
    if (keyblock)
        memcpy(((CHAR *)pSubmitRequest)+sizeof(KERB_SUBMIT_TKT_REQUEST)+krb_cred->length,
               keyblock->contents, keyblock->length);
    krb5_free_data(context, krb_cred);

    Status = LsaCallAuthenticationPackage( LogonHandle,
                                           PackageId,
                                           pSubmitRequest,
                                           dwRequestLen,
                                           NULL,
                                           NULL,
                                           &SubStatus
    );
    free(pSubmitRequest);
    if (keyblock)
        krb5_free_keyblock(context, keyblock);
    krb5_auth_con_free(context, auth_context);

    if (FAILED(Status) || FAILED(SubStatus)) {
        return FALSE;
    }
    return TRUE;
}
#endif /* KERB_SUBMIT_TICKET */

/*
 * A simple function to determine if there is an exact match between two tickets
 * We rely on the fact that the external tickets contain the raw Kerberos ticket.
 * If the EncodedTicket fields match, the KERB_EXTERNAL_TICKETs must be the same.
 */
static BOOL
KerbExternalTicketMatch( PKERB_EXTERNAL_TICKET one, PKERB_EXTERNAL_TICKET two )
{
    if ( one->EncodedTicketSize != two->EncodedTicketSize )
        return FALSE;

    if ( memcmp(one->EncodedTicket, two->EncodedTicket, one->EncodedTicketSize) )
        return FALSE;

    return TRUE;
}

krb5_boolean
krb5_is_permitted_tgs_enctype(krb5_context context, krb5_const_principal princ, krb5_enctype etype)
{
    krb5_enctype *list, *ptr;
    krb5_boolean ret;

    if (krb5_get_tgs_ktypes(context, princ, &list))
        return(0);

    ret = 0;

    for (ptr = list; *ptr; ptr++)
        if (*ptr == etype)
            ret = 1;

    krb5_free_enctypes(context, list);

    return(ret);
}

#define ENABLE_PURGING 1
// to allow the purging of expired tickets from LSA cache.  This is necessary
// to force the retrieval of new TGTs.  Microsoft does not appear to retrieve
// new tickets when they expire.  Instead they continue to accept the expired
// tickets.  This is safe to do because the LSA purges its cache when it
// retrieves a new TGT (ms calls this renew) but not when it renews the TGT
// (ms calls this refresh).
// UAC-limited processes are not allowed to obtain a copy of the MSTGT
// session key.  We used to check for UAC-limited processes and refuse all
// access to the TGT, but this makes the MSLSA ccache completely unusable.
// Instead we ought to just flag that the tgt session key is not valid.

static BOOL
GetMSTGT(krb5_context context, HANDLE LogonHandle, ULONG PackageId, KERB_EXTERNAL_TICKET **ticket, BOOL enforce_tgs_enctypes)
{
    //
    // INVARIANTS:
    //
    //   (FAILED(Status) || FAILED(SubStatus)) ==> error
    //   bIsLsaError ==> LsaCallAuthenticationPackage() error
    //

    BOOL bIsLsaError = FALSE;
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    DWORD   Error;

    KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
    PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
    PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
    ULONG RequestSize;
    ULONG ResponseSize;
#ifdef ENABLE_PURGING
    int    purge_cache = 0;
#endif /* ENABLE_PURGING */
    int    ignore_cache = 0;
    krb5_enctype *etype_list = NULL, *ptr = NULL, etype = 0;

    memset(&CacheRequest, 0, sizeof(KERB_QUERY_TKT_CACHE_REQUEST));
    CacheRequest.MessageType = KerbRetrieveTicketMessage;
    CacheRequest.LogonId.LowPart = 0;
    CacheRequest.LogonId.HighPart = 0;

    Status = LsaCallAuthenticationPackage(
        LogonHandle,
        PackageId,
        &CacheRequest,
        sizeof(CacheRequest),
        &pTicketResponse,
        &ResponseSize,
        &SubStatus
    );

    if (FAILED(Status))
    {
        // if the call to LsaCallAuthenticationPackage failed we cannot
        // perform any queries most likely because the Kerberos package
        // is not available or we do not have access
        bIsLsaError = TRUE;
        goto cleanup;
    }

    if (FAILED(SubStatus)) {
        PSECURITY_LOGON_SESSION_DATA pSessionData = NULL;
        BOOL    Success = FALSE;
        OSVERSIONINFOEX verinfo;
        int supported = 0;

        // SubStatus 0x8009030E is not documented.  However, it appears
        // to mean there is no TGT
        if (SubStatus != 0x8009030E) {
            bIsLsaError = TRUE;
            goto cleanup;
        }

        verinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
        GetVersionEx((OSVERSIONINFO *)&verinfo);
        supported = (verinfo.dwMajorVersion > 5) ||
            (verinfo.dwMajorVersion == 5 && verinfo.dwMinorVersion >= 1);

        // If we could not get a TGT from the cache we won't know what the
        // Kerberos Domain should have been.  On Windows XP and 2003 Server
        // we can extract it from the Security Logon Session Data.  However,
        // the required fields are not supported on Windows 2000.  :(
        if ( supported && GetSecurityLogonSessionData(&pSessionData) ) {
            if ( pSessionData->DnsDomainName.Buffer ) {
                Error = ConstructTicketRequest(pSessionData->DnsDomainName,
                                               &pTicketRequest, &RequestSize);
                LsaFreeReturnBuffer(pSessionData);
                if ( Error )
                    goto cleanup;
            } else {
                LsaFreeReturnBuffer(pSessionData);
                bIsLsaError = TRUE;
                goto cleanup;
            }
        } else {
            CHAR  UserDnsDomain[256];
            WCHAR UnicodeUserDnsDomain[256];
            UNICODE_STRING wrapper;
            if ( !get_STRING_from_registry(HKEY_CURRENT_USER,
                                           "Volatile Environment",
                                           "USERDNSDOMAIN",
                                           UserDnsDomain,
                                           sizeof(UserDnsDomain)
                 ) )
            {
                goto cleanup;
            }

            ANSIToUnicode(UserDnsDomain,UnicodeUserDnsDomain,256);
            wrapper.Buffer = UnicodeUserDnsDomain;
            wrapper.Length = wcslen(UnicodeUserDnsDomain) * sizeof(WCHAR);
            wrapper.MaximumLength = 256;

            Error = ConstructTicketRequest(wrapper,
                                           &pTicketRequest, &RequestSize);
            if ( Error )
                goto cleanup;
        }
    } else {
        /* We have succeeded in obtaining a credential from the cache.
         * Assuming the enctype is one that we support and the ticket
         * has not expired and is not marked invalid we will use it.
         * Otherwise, we must create a new ticket request and obtain
         * a credential we can use.
         */

#ifdef PURGE_ALL
        purge_cache = 1;
#else
        /* Check Supported Enctypes */
        if ( !enforce_tgs_enctypes ||
             IsMSSessionKeyNull(&pTicketResponse->Ticket.SessionKey) ||
             krb5_is_permitted_tgs_enctype(context, NULL, pTicketResponse->Ticket.SessionKey.KeyType) ) {
            FILETIME Now, MinLife, EndTime, LocalEndTime;
            __int64  temp;
            // FILETIME is in units of 100 nano-seconds
            // If obtained tickets are either expired or have a lifetime
            // less than 20 minutes, retry ...
            GetSystemTimeAsFileTime(&Now);
            EndTime.dwLowDateTime=pTicketResponse->Ticket.EndTime.LowPart;
            EndTime.dwHighDateTime=pTicketResponse->Ticket.EndTime.HighPart;
            FileTimeToLocalFileTime(&EndTime, &LocalEndTime);
            temp = Now.dwHighDateTime;
            temp <<= 32;
            temp = Now.dwLowDateTime;
            temp += 1200 * 10000;
            MinLife.dwHighDateTime = (DWORD)((temp >> 32) & 0xFFFFFFFF);
            MinLife.dwLowDateTime = (DWORD)(temp & 0xFFFFFFFF);
            if (CompareFileTime(&MinLife, &LocalEndTime) >= 0) {
#ifdef ENABLE_PURGING
                purge_cache = 1;
#else
                ignore_cache = 1;
#endif /* ENABLE_PURGING */
            }
            if (pTicketResponse->Ticket.TicketFlags & KERB_TICKET_FLAGS_invalid) {
                ignore_cache = 1;   // invalid, need to attempt a TGT request
            }
            goto cleanup;           // we have a valid ticket, all done
        } else {
            // not supported
            ignore_cache = 1;
        }
#endif /* PURGE_ALL */

        Error = ConstructTicketRequest(pTicketResponse->Ticket.TargetDomainName,
                                       &pTicketRequest, &RequestSize);
        if ( Error ) {
            goto cleanup;
        }

        //
        // Free the previous response buffer so we can get the new response.
        //

        if ( pTicketResponse ) {
            memset(pTicketResponse,0,sizeof(KERB_RETRIEVE_TKT_RESPONSE));
            LsaFreeReturnBuffer(pTicketResponse);
            pTicketResponse = NULL;
        }

#ifdef ENABLE_PURGING
        if ( purge_cache ) {
            //
            // Purge the existing tickets which we cannot use so new ones can
            // be requested.  It is not possible to purge just the TGT.  All
            // service tickets must be purged.
            //
            PurgeAllTickets(LogonHandle, PackageId);
        }
#endif /* ENABLE_PURGING */
    }

    //
    // Intialize the request of the request.
    //

    pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
    pTicketRequest->LogonId.LowPart = 0;
    pTicketRequest->LogonId.HighPart = 0;
    // Note: pTicketRequest->TargetName set up above
#ifdef ENABLE_PURGING
    pTicketRequest->CacheOptions = ((ignore_cache || !purge_cache) ?
                                    KERB_RETRIEVE_TICKET_DONT_USE_CACHE : 0L);
#else
    pTicketRequest->CacheOptions = (ignore_cache ? KERB_RETRIEVE_TICKET_DONT_USE_CACHE : 0L);
#endif /* ENABLE_PURGING */
    pTicketRequest->TicketFlags = 0L;
    pTicketRequest->EncryptionType = 0L;

    Status = LsaCallAuthenticationPackage( LogonHandle,
                                           PackageId,
                                           pTicketRequest,
                                           RequestSize,
                                           &pTicketResponse,
                                           &ResponseSize,
                                           &SubStatus
    );

    if (FAILED(Status) || FAILED(SubStatus))
    {
        bIsLsaError = TRUE;
        goto cleanup;
    }

    //
    // Check to make sure the new tickets we received are of a type we support
    //

    /* Check Supported Enctypes */
    if ( !enforce_tgs_enctypes ||
         krb5_is_permitted_tgs_enctype(context, NULL, pTicketResponse->Ticket.SessionKey.KeyType) ) {
        goto cleanup;       // we have a valid ticket, all done
    }

    if (krb5_get_tgs_ktypes(context, NULL, &etype_list)) {
        ptr = etype_list = NULL;
        etype = ENCTYPE_DES_CBC_CRC;
    } else {
        ptr = etype_list + 1;
        etype = *etype_list;
    }

    while ( etype ) {
        // Try once more but this time specify the Encryption Type
        // (This will not store the retrieved tickets in the LSA cache unless
        // 0 is supported.)
        pTicketRequest->EncryptionType = etype;
        pTicketRequest->CacheOptions = 0;
        if ( does_retrieve_ticket_cache_ticket() )
            pTicketRequest->CacheOptions |= KERB_RETRIEVE_TICKET_CACHE_TICKET;

        if ( pTicketResponse ) {
            memset(pTicketResponse,0,sizeof(KERB_RETRIEVE_TKT_RESPONSE));
            LsaFreeReturnBuffer(pTicketResponse);
            pTicketResponse = NULL;
        }

        Status = LsaCallAuthenticationPackage( LogonHandle,
                                               PackageId,
                                               pTicketRequest,
                                               RequestSize,
                                               &pTicketResponse,
                                               &ResponseSize,
                                               &SubStatus
        );

        if (FAILED(Status) || FAILED(SubStatus))
        {
            bIsLsaError = TRUE;
            goto cleanup;
        }

        if ( pTicketResponse->Ticket.SessionKey.KeyType == etype &&
             (!enforce_tgs_enctypes ||
              krb5_is_permitted_tgs_enctype(context, NULL, pTicketResponse->Ticket.SessionKey.KeyType)) ) {
            goto cleanup;       // we have a valid ticket, all done
        }

        if ( ptr ) {
            etype = *ptr++;
        } else {
            etype = 0;
        }
    }

cleanup:
    if ( etype_list )
        krb5_free_enctypes(context, etype_list);

    if ( pTicketRequest )
        LocalFree(pTicketRequest);

    if (FAILED(Status) || FAILED(SubStatus))
    {
        if (bIsLsaError)
        {
            // XXX - Will be fixed later
            if (FAILED(Status))
                ShowLsaError("LsaCallAuthenticationPackage", Status);
            if (FAILED(SubStatus))
                ShowLsaError("LsaCallAuthenticationPackage", SubStatus);
        }
        else
        {
            ShowWinError("GetMSTGT", Status);
        }

        if (pTicketResponse) {
            memset(pTicketResponse,0,sizeof(KERB_RETRIEVE_TKT_RESPONSE));
            LsaFreeReturnBuffer(pTicketResponse);
            pTicketResponse = NULL;
        }
        return(FALSE);
    }

    *ticket = &(pTicketResponse->Ticket);
    return(TRUE);
}

static BOOL
GetQueryTktCacheResponseW2K( HANDLE LogonHandle, ULONG PackageId,
                             PKERB_QUERY_TKT_CACHE_RESPONSE * ppResponse)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;

    KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
    PKERB_QUERY_TKT_CACHE_RESPONSE pQueryResponse = NULL;
    ULONG ResponseSize;

    CacheRequest.MessageType = KerbQueryTicketCacheMessage;
    CacheRequest.LogonId.LowPart = 0;
    CacheRequest.LogonId.HighPart = 0;

    Status = LsaCallAuthenticationPackage(
        LogonHandle,
        PackageId,
        &CacheRequest,
        sizeof(CacheRequest),
        &pQueryResponse,
        &ResponseSize,
        &SubStatus
    );

    if ( !(FAILED(Status) || FAILED(SubStatus)) ) {
        *ppResponse = pQueryResponse;
        return TRUE;
    }

    return FALSE;
}

static BOOL
GetQueryTktCacheResponseXP( HANDLE LogonHandle, ULONG PackageId,
                            PKERB_QUERY_TKT_CACHE_EX_RESPONSE * ppResponse)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;

    KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
    PKERB_QUERY_TKT_CACHE_EX_RESPONSE pQueryResponse = NULL;
    ULONG ResponseSize;

    CacheRequest.MessageType = KerbQueryTicketCacheExMessage;
    CacheRequest.LogonId.LowPart = 0;
    CacheRequest.LogonId.HighPart = 0;

    Status = LsaCallAuthenticationPackage(
        LogonHandle,
        PackageId,
        &CacheRequest,
        sizeof(CacheRequest),
        &pQueryResponse,
        &ResponseSize,
        &SubStatus
    );

    if ( !(FAILED(Status) || FAILED(SubStatus)) ) {
        *ppResponse = pQueryResponse;
        return TRUE;
    }

    return FALSE;
}

#ifdef HAVE_CACHE_INFO_EX2
static BOOL
GetQueryTktCacheResponseEX2( HANDLE LogonHandle, ULONG PackageId,
                             PKERB_QUERY_TKT_CACHE_EX2_RESPONSE * ppResponse)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;

    KERB_QUERY_TKT_CACHE_REQUEST CacheRequest;
    PKERB_QUERY_TKT_CACHE_EX2_RESPONSE pQueryResponse = NULL;
    ULONG ResponseSize;

    CacheRequest.MessageType = KerbQueryTicketCacheEx2Message;
    CacheRequest.LogonId.LowPart = 0;
    CacheRequest.LogonId.HighPart = 0;

    Status = LsaCallAuthenticationPackage(
        LogonHandle,
        PackageId,
        &CacheRequest,
        sizeof(CacheRequest),
        &pQueryResponse,
        &ResponseSize,
        &SubStatus
    );

    if ( !(FAILED(Status) || FAILED(SubStatus)) ) {
        *ppResponse = pQueryResponse;
        return TRUE;
    }

    return FALSE;
}
#endif /* HAVE_CACHE_INFO_EX2 */

static BOOL
GetMSCacheTicketFromMITCred( HANDLE LogonHandle, ULONG PackageId,
                             krb5_context context, krb5_creds *creds,
                             PKERB_EXTERNAL_TICKET *ticket)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    ULONG RequestSize;
    PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
    PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
    ULONG ResponseSize;

    RequestSize = sizeof(*pTicketRequest) + MAX_MSPRINC_SIZE;

    pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
    if (!pTicketRequest)
        return FALSE;

    pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
    pTicketRequest->LogonId.LowPart = 0;
    pTicketRequest->LogonId.HighPart = 0;

    pTicketRequest->TargetName.Length = 0;
    pTicketRequest->TargetName.MaximumLength = MAX_MSPRINC_SIZE;
    pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
    MITPrincToMSPrinc(context, creds->server, &pTicketRequest->TargetName);
    pTicketRequest->CacheOptions = 0;
    if ( does_retrieve_ticket_cache_ticket() )
        pTicketRequest->CacheOptions |= KERB_RETRIEVE_TICKET_CACHE_TICKET;
    pTicketRequest->TicketFlags = creds->ticket_flags;
    pTicketRequest->EncryptionType = creds->keyblock.enctype;

    Status = LsaCallAuthenticationPackage( LogonHandle,
                                           PackageId,
                                           pTicketRequest,
                                           RequestSize,
                                           &pTicketResponse,
                                           &ResponseSize,
                                           &SubStatus
    );

    LocalFree(pTicketRequest);

    if (FAILED(Status) || FAILED(SubStatus))
        return(FALSE);

    /* otherwise return ticket */
    *ticket = &(pTicketResponse->Ticket);
    return(TRUE);
}

static BOOL
GetMSCacheTicketFromCacheInfoW2K( HANDLE LogonHandle, ULONG PackageId,
                                  PKERB_TICKET_CACHE_INFO tktinfo, PKERB_EXTERNAL_TICKET *ticket)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    ULONG RequestSize;
    PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
    PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
    ULONG ResponseSize;

    RequestSize = sizeof(*pTicketRequest) + tktinfo->ServerName.Length;

    pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
    if (!pTicketRequest)
        return FALSE;

    pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
    pTicketRequest->LogonId.LowPart = 0;
    pTicketRequest->LogonId.HighPart = 0;
    pTicketRequest->TargetName.Length = tktinfo->ServerName.Length;
    pTicketRequest->TargetName.MaximumLength = tktinfo->ServerName.Length;
    pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
    memcpy(pTicketRequest->TargetName.Buffer,tktinfo->ServerName.Buffer, tktinfo->ServerName.Length);
    pTicketRequest->CacheOptions = 0;
    if ( does_retrieve_ticket_cache_ticket() )
        pTicketRequest->CacheOptions |= KERB_RETRIEVE_TICKET_CACHE_TICKET;
    pTicketRequest->EncryptionType = tktinfo->EncryptionType;
    pTicketRequest->TicketFlags = 0;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwardable )
        pTicketRequest->TicketFlags |= KDC_OPT_FORWARDABLE;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwarded )
        pTicketRequest->TicketFlags |= KDC_OPT_FORWARDED;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_proxiable )
        pTicketRequest->TicketFlags |= KDC_OPT_PROXIABLE;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_renewable )
        pTicketRequest->TicketFlags |= KDC_OPT_RENEWABLE;

    Status = LsaCallAuthenticationPackage(
        LogonHandle,
        PackageId,
        pTicketRequest,
        RequestSize,
        &pTicketResponse,
        &ResponseSize,
        &SubStatus
    );

    LocalFree(pTicketRequest);

    if (FAILED(Status) || FAILED(SubStatus))
        return(FALSE);

    /* otherwise return ticket */
    *ticket = &(pTicketResponse->Ticket);

    /* set the initial flag if we were attempting to retrieve one
     * because Windows won't necessarily return the initial ticket
     * to us.
     */
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_initial )
        (*ticket)->TicketFlags |= KERB_TICKET_FLAGS_initial;

    return(TRUE);
}

static BOOL
GetMSCacheTicketFromCacheInfoXP( HANDLE LogonHandle, ULONG PackageId,
                                 PKERB_TICKET_CACHE_INFO_EX tktinfo, PKERB_EXTERNAL_TICKET *ticket)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    ULONG RequestSize;
    PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
    PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
    ULONG ResponseSize;

    RequestSize = sizeof(*pTicketRequest) + tktinfo->ServerName.Length;

    pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
    if (!pTicketRequest)
        return FALSE;

    pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
    pTicketRequest->LogonId.LowPart = 0;
    pTicketRequest->LogonId.HighPart = 0;
    pTicketRequest->TargetName.Length = tktinfo->ServerName.Length;
    pTicketRequest->TargetName.MaximumLength = tktinfo->ServerName.Length;
    pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
    memcpy(pTicketRequest->TargetName.Buffer,tktinfo->ServerName.Buffer, tktinfo->ServerName.Length);
    pTicketRequest->CacheOptions = 0;
    pTicketRequest->EncryptionType = tktinfo->EncryptionType;
    pTicketRequest->TicketFlags = 0;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwardable )
        pTicketRequest->TicketFlags |= KDC_OPT_FORWARDABLE;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwarded )
        pTicketRequest->TicketFlags |= KDC_OPT_FORWARDED;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_proxiable )
        pTicketRequest->TicketFlags |= KDC_OPT_PROXIABLE;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_renewable )
        pTicketRequest->TicketFlags |= KDC_OPT_RENEWABLE;

    Status = LsaCallAuthenticationPackage(
        LogonHandle,
        PackageId,
        pTicketRequest,
        RequestSize,
        &pTicketResponse,
        &ResponseSize,
        &SubStatus
    );

    LocalFree(pTicketRequest);

    if (FAILED(Status) || FAILED(SubStatus))
        return(FALSE);

    /* otherwise return ticket */
    *ticket = &(pTicketResponse->Ticket);

    /* set the initial flag if we were attempting to retrieve one
     * because Windows won't necessarily return the initial ticket
     * to us.
     */
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_initial )
        (*ticket)->TicketFlags |= KERB_TICKET_FLAGS_initial;

    return(TRUE);
}

#ifdef HAVE_CACHE_INFO_EX2
static BOOL
GetMSCacheTicketFromCacheInfoEX2( HANDLE LogonHandle, ULONG PackageId,
                                  PKERB_TICKET_CACHE_INFO_EX2 tktinfo, PKERB_EXTERNAL_TICKET *ticket)
{
    NTSTATUS Status = 0;
    NTSTATUS SubStatus = 0;
    ULONG RequestSize;
    PKERB_RETRIEVE_TKT_REQUEST pTicketRequest = NULL;
    PKERB_RETRIEVE_TKT_RESPONSE pTicketResponse = NULL;
    ULONG ResponseSize;

    RequestSize = sizeof(*pTicketRequest) + tktinfo->ServerName.Length;

    pTicketRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LMEM_ZEROINIT, RequestSize);
    if (!pTicketRequest)
        return FALSE;

    pTicketRequest->MessageType = KerbRetrieveEncodedTicketMessage;
    pTicketRequest->LogonId.LowPart = 0;
    pTicketRequest->LogonId.HighPart = 0;
    pTicketRequest->TargetName.Length = tktinfo->ServerName.Length;
    pTicketRequest->TargetName.MaximumLength = tktinfo->ServerName.Length;
    pTicketRequest->TargetName.Buffer = (PWSTR) (pTicketRequest + 1);
    memcpy(pTicketRequest->TargetName.Buffer,tktinfo->ServerName.Buffer, tktinfo->ServerName.Length);
    pTicketRequest->CacheOptions = KERB_RETRIEVE_TICKET_CACHE_TICKET;
    pTicketRequest->EncryptionType = tktinfo->SessionKeyType;
    pTicketRequest->TicketFlags = 0;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwardable )
        pTicketRequest->TicketFlags |= KDC_OPT_FORWARDABLE;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_forwarded )
        pTicketRequest->TicketFlags |= KDC_OPT_FORWARDED;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_proxiable )
        pTicketRequest->TicketFlags |= KDC_OPT_PROXIABLE;
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_renewable )
        pTicketRequest->TicketFlags |= KDC_OPT_RENEWABLE;

    Status = LsaCallAuthenticationPackage(
        LogonHandle,
        PackageId,
        pTicketRequest,
        RequestSize,
        &pTicketResponse,
        &ResponseSize,
        &SubStatus
    );

    LocalFree(pTicketRequest);

    if (FAILED(Status) || FAILED(SubStatus))
        return(FALSE);

    /* otherwise return ticket */
    *ticket = &(pTicketResponse->Ticket);


    /* set the initial flag if we were attempting to retrieve one
     * because Windows won't necessarily return the initial ticket
     * to us.
     */
    if ( tktinfo->TicketFlags & KERB_TICKET_FLAGS_initial )
        (*ticket)->TicketFlags |= KERB_TICKET_FLAGS_initial;

    return(TRUE);
}
#endif /* HAVE_CACHE_INFO_EX2 */

static krb5_error_code KRB5_CALLCONV krb5_lcc_close
(krb5_context, krb5_ccache id);

static krb5_error_code KRB5_CALLCONV krb5_lcc_destroy
(krb5_context, krb5_ccache id);

static krb5_error_code KRB5_CALLCONV krb5_lcc_end_seq_get
(krb5_context, krb5_ccache id, krb5_cc_cursor *cursor);

static krb5_error_code KRB5_CALLCONV krb5_lcc_generate_new
(krb5_context, krb5_ccache *id);

static const char * KRB5_CALLCONV krb5_lcc_get_name
(krb5_context, krb5_ccache id);

static krb5_error_code KRB5_CALLCONV krb5_lcc_get_principal
(krb5_context, krb5_ccache id, krb5_principal *princ);

static krb5_error_code KRB5_CALLCONV krb5_lcc_initialize
(krb5_context, krb5_ccache id, krb5_principal princ);

static krb5_error_code KRB5_CALLCONV krb5_lcc_next_cred
(krb5_context, krb5_ccache id, krb5_cc_cursor *cursor,
 krb5_creds *creds);

static krb5_error_code KRB5_CALLCONV krb5_lcc_resolve
(krb5_context, krb5_ccache *id, const char *residual);

static krb5_error_code KRB5_CALLCONV krb5_lcc_retrieve
(krb5_context, krb5_ccache id, krb5_flags whichfields,
 krb5_creds *mcreds, krb5_creds *creds);

static krb5_error_code KRB5_CALLCONV krb5_lcc_start_seq_get
(krb5_context, krb5_ccache id, krb5_cc_cursor *cursor);

static krb5_error_code KRB5_CALLCONV krb5_lcc_store
(krb5_context, krb5_ccache id, krb5_creds *creds);

static krb5_error_code KRB5_CALLCONV krb5_lcc_set_flags
(krb5_context, krb5_ccache id, krb5_flags flags);

static krb5_error_code KRB5_CALLCONV krb5_lcc_get_flags
(krb5_context, krb5_ccache id, krb5_flags *flags);

extern const krb5_cc_ops krb5_lcc_ops;

krb5_error_code krb5_change_cache (void);

krb5_boolean
krb5int_cc_creds_match_request(krb5_context, krb5_flags whichfields, krb5_creds *mcreds, krb5_creds *creds);

#define KRB5_OK 0

typedef struct _krb5_lcc_data {
    HANDLE LogonHandle;
    ULONG  PackageId;
    char * cc_name;
    krb5_principal princ;
    krb5_flags flags;
} krb5_lcc_data;

typedef struct _krb5_lcc_cursor {
    union {
        PKERB_QUERY_TKT_CACHE_RESPONSE w2k;
        PKERB_QUERY_TKT_CACHE_EX_RESPONSE xp;
#ifdef HAVE_CACHE_INFO_EX2
        PKERB_QUERY_TKT_CACHE_EX2_RESPONSE ex2;
#endif /* HAVE_CACHE_INFO_EX2 */
    } response;
    unsigned int index;
    PKERB_EXTERNAL_TICKET mstgt;
} krb5_lcc_cursor;


/*
 * Requires:
 * residual is ignored
 *
 * Modifies:
 * id
 *
 * Effects:
 * Acccess the MS Kerberos LSA cache in the current logon session
 * Ignore the residual.
 *
 * Returns:
 * A filled in krb5_ccache structure "id".
 *
 * Errors:
 * KRB5_CC_NOMEM - there was insufficient memory to allocate the
 *
 *              krb5_ccache.  id is undefined.
 * permission errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_resolve (krb5_context context, krb5_ccache *id, const char *residual)
{
    krb5_ccache lid;
    krb5_lcc_data *data;
    HANDLE LogonHandle;
    ULONG  PackageId;
    KERB_EXTERNAL_TICKET *msticket;
    krb5_error_code retval = KRB5_OK;

    if (!is_windows_2000() || is_broken_wow64())
        return KRB5_FCC_NOFILE;

#ifdef COMMENT
    /* In at least one case on Win2003 it appears that it is possible
     * for the logon session to be authenticated via NTLM and yet for
     * there to be Kerberos credentials obtained by the LSA on behalf
     * of the logged in user.  Therefore, we are removing this test
     * which was meant to avoid the need to perform GetMSTGT() when
     * there was no possibility of credentials being found.
     */
    if (!IsKerberosLogon())
        return KRB5_FCC_NOFILE;
#endif

    if (!PackageConnectLookup(&LogonHandle, &PackageId))
        return KRB5_FCC_NOFILE;

    lid = (krb5_ccache) malloc(sizeof(struct _krb5_ccache));
    if (lid == NULL) {
        LsaDeregisterLogonProcess(LogonHandle);
        return KRB5_CC_NOMEM;
    }

    lid->ops = &krb5_lcc_ops;

    lid->data = (krb5_pointer) malloc(sizeof(krb5_lcc_data));
    if (lid->data == NULL) {
        free(lid);
        LsaDeregisterLogonProcess(LogonHandle);
        return KRB5_CC_NOMEM;
    }

    lid->magic = KV5M_CCACHE;
    data = (krb5_lcc_data *)lid->data;
    data->LogonHandle = LogonHandle;
    data->PackageId = PackageId;
    data->princ = 0;

    data->cc_name = (char *)malloc(strlen(residual)+1);
    if (data->cc_name == NULL) {
        free(lid->data);
        free(lid);
        LsaDeregisterLogonProcess(LogonHandle);
        return KRB5_CC_NOMEM;
    }
    strcpy(data->cc_name, residual);

    /*
     * we must obtain a tgt from the cache in order to determine the principal
     */
    if (GetMSTGT(context, data->LogonHandle, data->PackageId, &msticket, FALSE)) {
        /* convert the ticket */
        krb5_creds creds;
        if (!MSCredToMITCred(msticket, msticket->DomainName, context, &creds))
            retval = KRB5_FCC_INTERNAL;
        LsaFreeReturnBuffer(msticket);

        if (retval == KRB5_OK)
            krb5_copy_principal(context, creds.client, &data->princ);
        krb5_free_cred_contents(context,&creds);
    } else if (!does_retrieve_ticket_cache_ticket()) {
        free(data->cc_name);
        free(lid->data);
        free(lid);
        LsaDeregisterLogonProcess(LogonHandle);
        return KRB5_FCC_NOFILE;
    }

    /*
     * other routines will get errors on open, and callers must expect them,
     * if cache is non-existent/unusable
     */
    *id = lid;
    return retval;
}

/*
 *  return success although we do not do anything
 *  We should delete all tickets belonging to the specified principal
 */

static krb5_error_code KRB5_CALLCONV
krb5_lcc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags flags,
                     krb5_creds *creds);

static krb5_error_code KRB5_CALLCONV
krb5_lcc_initialize(krb5_context context, krb5_ccache id, krb5_principal princ)
{
    krb5_cc_cursor cursor;
    krb5_error_code code;
    krb5_creds cred;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    code = krb5_cc_start_seq_get(context, id, &cursor);
    if (code) {
        if (code == KRB5_CC_NOTFOUND)
            return KRB5_OK;
        return code;
    }

    while ( !(code = krb5_cc_next_cred(context, id, &cursor, &cred)) )
    {
        if ( krb5_principal_compare(context, princ, cred.client) ) {
            code = krb5_lcc_remove_cred(context, id, 0, &cred);
        }
        krb5_free_cred_contents(context, &cred);
    }

    if (code == KRB5_CC_END || code == KRB5_CC_NOTFOUND)
    {
        krb5_cc_end_seq_get(context, id, &cursor);
        return KRB5_OK;
    }
    return code;
}

/*
 * Modifies:
 * id
 *
 * Effects:
 * Closes the microsoft lsa cache, invalidates the id, and frees any resources
 * associated with the cache.
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_close(krb5_context context, krb5_ccache id)
{
    register int closeval = KRB5_OK;
    register krb5_lcc_data *data;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    if (id) {
        data = (krb5_lcc_data *) id->data;

        if (data) {
            LsaDeregisterLogonProcess(data->LogonHandle);
            if (data->cc_name)
                free(data->cc_name);
            free(data);
        }
        free(id);
    }
    return closeval;
}

/*
 * Effects:
 * Destroys the contents of id.
 *
 * Errors:
 * system errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_destroy(krb5_context context, krb5_ccache id)
{
    register krb5_lcc_data *data;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    if (id) {
        data = (krb5_lcc_data *) id->data;

        return PurgeAllTickets(data->LogonHandle, data->PackageId) ? KRB5_OK : KRB5_FCC_INTERNAL;
    }
    return KRB5_FCC_INTERNAL;
}

/*
 * Effects:
 * Prepares for a sequential search of the credentials cache.
 * Returns a krb5_cc_cursor to be used with krb5_lcc_next_cred and
 * krb5_lcc_end_seq_get.
 *
 * If the cache is modified between the time of this call and the time
 * of the final krb5_lcc_end_seq_get, the results are undefined.
 *
 * Errors:
 * KRB5_CC_NOMEM
 * KRB5_FCC_INTERNAL - system errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_start_seq_get(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor)
{
    krb5_lcc_cursor *lcursor;
    krb5_lcc_data *data = (krb5_lcc_data *)id->data;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    lcursor = (krb5_lcc_cursor *) malloc(sizeof(krb5_lcc_cursor));
    if (lcursor == NULL) {
        *cursor = 0;
        return KRB5_CC_NOMEM;
    }

    /*
     * obtain a tgt to refresh the ccache in case the ticket is expired
     */
    if (!GetMSTGT(context, data->LogonHandle, data->PackageId, &lcursor->mstgt, TRUE)) {
        free(lcursor);
        *cursor = 0;
        return KRB5_CC_NOTFOUND;
    }

#ifdef HAVE_CACHE_INFO_EX2
    if ( does_query_ticket_cache_ex2() ) {
        if ( !GetQueryTktCacheResponseEX2(data->LogonHandle, data->PackageId, &lcursor->response.ex2) ) {
            LsaFreeReturnBuffer(lcursor->mstgt);
            free(lcursor);
            *cursor = 0;
            return KRB5_FCC_INTERNAL;
        }
    } else
#endif /* HAVE_CACHE_INFO_EX2 */
        if ( is_windows_xp() ) {
            if ( !GetQueryTktCacheResponseXP(data->LogonHandle, data->PackageId, &lcursor->response.xp) ) {
                LsaFreeReturnBuffer(lcursor->mstgt);
                free(lcursor);
                *cursor = 0;
                return KRB5_FCC_INTERNAL;
            }
        } else {
            if ( !GetQueryTktCacheResponseW2K(data->LogonHandle, data->PackageId, &lcursor->response.w2k) ) {
                LsaFreeReturnBuffer(lcursor->mstgt);
                free(lcursor);
                *cursor = 0;
                return KRB5_FCC_INTERNAL;
            }
        }
    lcursor->index = 0;
    *cursor = (krb5_cc_cursor) lcursor;
    return KRB5_OK;
}


/*
 * Requires:
 * cursor is a krb5_cc_cursor originally obtained from
 * krb5_lcc_start_seq_get.
 *
 * Modifes:
 * cursor
 *
 * Effects:
 * Fills in creds with the TGT obtained from the MS LSA
 *
 * The cursor is updated to indicate TGT retrieval
 *
 * Errors:
 * KRB5_CC_END
 * KRB5_FCC_INTERNAL - system errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_next_cred(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor, krb5_creds *creds)
{
    krb5_lcc_cursor *lcursor = (krb5_lcc_cursor *) *cursor;
    krb5_lcc_data *data;
    KERB_EXTERNAL_TICKET *msticket;
    krb5_error_code  retval = KRB5_OK;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    data = (krb5_lcc_data *)id->data;

next_cred:
#ifdef HAVE_CACHE_INFO_EX2
    if ( does_query_ticket_cache_ex2() ) {
        if ( lcursor->index >= lcursor->response.ex2->CountOfTickets ) {
            if (retval == KRB5_OK)
                return KRB5_CC_END;
            else {
                LsaFreeReturnBuffer(lcursor->mstgt);
                LsaFreeReturnBuffer(lcursor->response.ex2);
                free(*cursor);
                *cursor = 0;
                return retval;
            }
        }

        if ( data->flags & KRB5_TC_NOTICKET ) {
            if (!CacheInfoEx2ToMITCred( &lcursor->response.ex2->Tickets[lcursor->index++],
                                        context, creds)) {
                retval = KRB5_FCC_INTERNAL;
                goto next_cred;
            }
            return KRB5_OK;
        } else {
            if (!GetMSCacheTicketFromCacheInfoEX2(data->LogonHandle, data->PackageId,
                                                  &lcursor->response.ex2->Tickets[lcursor->index++],&msticket)) {
                retval = KRB5_FCC_INTERNAL;
                goto next_cred;
            }
        }
    } else
#endif /* HAVE_CACHE_INFO_EX2 */
        if ( is_windows_xp() ) {
            if ( lcursor->index >= lcursor->response.xp->CountOfTickets ) {
                if (retval == KRB5_OK)
                    return KRB5_CC_END;
                else {
                    LsaFreeReturnBuffer(lcursor->mstgt);
                    LsaFreeReturnBuffer(lcursor->response.xp);
                    free(*cursor);
                    *cursor = 0;
                    return retval;
                }
            }

            if (!GetMSCacheTicketFromCacheInfoXP(data->LogonHandle, data->PackageId,
                                                 &lcursor->response.xp->Tickets[lcursor->index++],&msticket)) {
                retval = KRB5_FCC_INTERNAL;
                goto next_cred;
            }
        } else {
            if ( lcursor->index >= lcursor->response.w2k->CountOfTickets ) {
                if (retval == KRB5_OK)
                    return KRB5_CC_END;
                else {
                    LsaFreeReturnBuffer(lcursor->mstgt);
                    LsaFreeReturnBuffer(lcursor->response.w2k);
                    free(*cursor);
                    *cursor = 0;
                    return retval;
                }
            }

            if (!GetMSCacheTicketFromCacheInfoW2K(data->LogonHandle, data->PackageId,
                                                  &lcursor->response.w2k->Tickets[lcursor->index++],&msticket)) {
                retval = KRB5_FCC_INTERNAL;
                goto next_cred;
            }
        }

    /* Don't return tickets with NULL Session Keys */
    if ( IsMSSessionKeyNull(&msticket->SessionKey) ) {
        LsaFreeReturnBuffer(msticket);
        goto next_cred;
    }

    /* convert the ticket */
#ifdef HAVE_CACHE_INFO_EX2
    if ( does_query_ticket_cache_ex2() ) {
        if (!MSCredToMITCred(msticket, lcursor->response.ex2->Tickets[lcursor->index-1].ClientRealm, context, creds))
            retval = KRB5_FCC_INTERNAL;
    } else
#endif /* HAVE_CACHE_INFO_EX2 */
        if ( is_windows_xp() ) {
            if (!MSCredToMITCred(msticket, lcursor->response.xp->Tickets[lcursor->index-1].ClientRealm, context, creds))
                retval = KRB5_FCC_INTERNAL;
        } else {
            if (!MSCredToMITCred(msticket, lcursor->mstgt->DomainName, context, creds))
                retval = KRB5_FCC_INTERNAL;
        }
    LsaFreeReturnBuffer(msticket);
    return retval;
}

/*
 * Requires:
 * cursor is a krb5_cc_cursor originally obtained from
 * krb5_lcc_start_seq_get.
 *
 * Modifies:
 * id, cursor
 *
 * Effects:
 * Finishes sequential processing of the file credentials ccache id,
 * and invalidates the cursor (it must never be used after this call).
 */
/* ARGSUSED */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_end_seq_get(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor)
{
    krb5_lcc_cursor *lcursor = (krb5_lcc_cursor *) *cursor;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    if ( lcursor ) {
        LsaFreeReturnBuffer(lcursor->mstgt);
#ifdef HAVE_CACHE_INFO_EX2
        if ( does_query_ticket_cache_ex2() )
            LsaFreeReturnBuffer(lcursor->response.ex2);
        else
#endif /* HAVE_CACHE_INFO_EX2 */
            if ( is_windows_xp() )
                LsaFreeReturnBuffer(lcursor->response.xp);
            else
                LsaFreeReturnBuffer(lcursor->response.w2k);
        free(*cursor);
    }
    *cursor = 0;

    return KRB5_OK;
}


/*
 * Errors:
 * KRB5_CC_READONLY - not supported
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_generate_new (krb5_context context, krb5_ccache *id)
{
    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    return KRB5_CC_READONLY;
}

/*
 * Requires:
 * id is a ms lsa credential cache
 *
 * Returns:
 *   The ccname specified during the krb5_lcc_resolve call
 */
static const char * KRB5_CALLCONV
krb5_lcc_get_name (krb5_context context, krb5_ccache id)
{

    if (!is_windows_2000())
        return "";

    if ( !id )
        return "";

    return (char *) ((krb5_lcc_data *) id->data)->cc_name;
}

/*
 * Modifies:
 * id, princ
 *
 * Effects:
 * Retrieves the primary principal from id, as set with
 * krb5_lcc_initialize.  The principal is returned is allocated
 * storage that must be freed by the caller via krb5_free_principal.
 *
 * Errors:
 * system errors
 * KRB5_CC_NOT_KTYPE
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *princ)
{
    krb5_lcc_data *data = (krb5_lcc_data *)id->data;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    /* obtain principal */
    if (data->princ)
        return krb5_copy_principal(context, data->princ, princ);
    else {
        /*
         * we must obtain a tgt from the cache in order to determine the principal
         */
        KERB_EXTERNAL_TICKET *msticket;
        if (GetMSTGT(context, data->LogonHandle, data->PackageId, &msticket, FALSE)) {
            /* convert the ticket */
            krb5_creds creds;
            if (!MSCredToMITCred(msticket, msticket->DomainName, context, &creds))
            {
                LsaFreeReturnBuffer(msticket);
                return KRB5_FCC_INTERNAL;
            }
            LsaFreeReturnBuffer(msticket);

            krb5_copy_principal(context, creds.client, &data->princ);
            krb5_free_cred_contents(context,&creds);
            return krb5_copy_principal(context, data->princ, princ);
        }
    }
    return KRB5_CC_NOTFOUND;
}


static krb5_error_code KRB5_CALLCONV
krb5_lcc_retrieve(krb5_context context, krb5_ccache id, krb5_flags whichfields,
                  krb5_creds *mcreds, krb5_creds *creds)
{
    krb5_error_code kret = KRB5_OK;
    krb5_lcc_data *data = (krb5_lcc_data *)id->data;
    KERB_EXTERNAL_TICKET *msticket = 0, *mstgt = 0, *mstmp = 0;
    krb5_creds * mcreds_noflags = 0;
    krb5_creds   fetchcreds;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    memset(&fetchcreds, 0, sizeof(krb5_creds));

    /* first try to find out if we have an existing ticket which meets the requirements */
    kret = k5_cc_retrieve_cred_default(context, id, whichfields, mcreds,
                                       creds);
    /* This sometimes returns a zero-length ticket; work around it. */
    if ( !kret && creds->ticket.length > 0 )
        return KRB5_OK;

    /* if not, we must try to get a ticket without specifying any flags or etypes */
    kret = krb5_copy_creds(context, mcreds, &mcreds_noflags);
    if (kret)
        goto cleanup;
    mcreds_noflags->ticket_flags = 0;
    mcreds_noflags->keyblock.enctype = 0;

    if (!GetMSCacheTicketFromMITCred(data->LogonHandle, data->PackageId, context, mcreds_noflags, &msticket)) {
        kret = KRB5_CC_NOTFOUND;
        goto cleanup;
    }

    /* try again to find out if we have an existing ticket which meets the requirements */
    kret = k5_cc_retrieve_cred_default(context, id, whichfields, mcreds,
                                       creds);
    /* This sometimes returns a zero-length ticket; work around it. */
    if ( !kret && creds->ticket.length > 0 )
        goto cleanup;

    /* if not, obtain a ticket using the request flags and enctype even though it may not
     * be stored in the LSA cache for future use.
     */
    if ( msticket ) {
        LsaFreeReturnBuffer(msticket);
        msticket = 0;
    }

    if (!GetMSCacheTicketFromMITCred(data->LogonHandle, data->PackageId, context, mcreds, &msticket)) {
        kret = KRB5_CC_NOTFOUND;
        goto cleanup;
    }

    /* convert the ticket */
    if ( !is_windows_xp() || !does_retrieve_ticket_cache_ticket() ) {
        if ( PreserveInitialTicketIdentity() )
            GetMSTGT(context, data->LogonHandle, data->PackageId, &mstgt, FALSE);

        if (!MSCredToMITCred(msticket, mstgt ? mstgt->DomainName : msticket->DomainName, context, &fetchcreds))
        {
            kret = KRB5_FCC_INTERNAL;
            goto cleanup;
        }
    } else {
        /* We can obtain the correct client realm for a ticket by walking the
         * cache contents until we find the matching service ticket.
         */
        PKERB_QUERY_TKT_CACHE_EX_RESPONSE pResponse = 0;
        unsigned int i;

        if (!GetQueryTktCacheResponseXP( data->LogonHandle, data->PackageId, &pResponse)) {
            kret = KRB5_FCC_INTERNAL;
            goto cleanup;
        }

        for ( i=0; i<pResponse->CountOfTickets; i++ ) {
            if (!GetMSCacheTicketFromCacheInfoXP(data->LogonHandle, data->PackageId,
                                                 &pResponse->Tickets[i],&mstmp)) {
                continue;
            }

            if ( KerbExternalTicketMatch(msticket,mstmp) )
                break;

            LsaFreeReturnBuffer(mstmp);
            mstmp = 0;
        }

        if (!MSCredToMITCred(msticket, mstmp ? pResponse->Tickets[i].ClientRealm : msticket->DomainName, context, &fetchcreds))
        {
            LsaFreeReturnBuffer(pResponse);
            kret = KRB5_FCC_INTERNAL;
            goto cleanup;
        }
        LsaFreeReturnBuffer(pResponse);
    }


    /* check to see if this ticket matches the request using logic from
     * k5_cc_retrieve_cred_default()
     */
    if ( krb5int_cc_creds_match_request(context, whichfields, mcreds, &fetchcreds) ) {
        *creds = fetchcreds;
    } else {
        krb5_free_cred_contents(context, &fetchcreds);
        kret = KRB5_CC_NOTFOUND;
    }

cleanup:
    if ( mstmp )
        LsaFreeReturnBuffer(mstmp);
    if ( mstgt )
        LsaFreeReturnBuffer(mstgt);
    if ( msticket )
        LsaFreeReturnBuffer(msticket);
    if ( mcreds_noflags )
        krb5_free_creds(context, mcreds_noflags);
    return kret;
}


/*
 * We can't write to the MS LSA cache.  So we request the cache to obtain a ticket for the same
 * principal in the hope that next time the application requires a ticket for the service it
 * is attempt to store, the retrieved ticket will be good enough.
 *
 * Errors:
 * KRB5_CC_READONLY - not supported
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_store(krb5_context context, krb5_ccache id, krb5_creds *creds)
{
    krb5_error_code kret = KRB5_OK;
    krb5_lcc_data *data = (krb5_lcc_data *)id->data;
    KERB_EXTERNAL_TICKET *msticket = 0, *msticket2 = 0;
    krb5_creds * creds_noflags = 0;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    if (krb5_is_config_principal(context, creds->server)) {
        /* mslsa cannot store config creds, so we have to bail.
         * The 'right' thing to do would be to return an appropriate error,
         * but that would require modifying the calling code to check
         * for that error and ignore it.
         */
        return KRB5_OK;
    }

#ifdef KERB_SUBMIT_TICKET
    /* we can use the new KerbSubmitTicketMessage to store the ticket */
    if (KerbSubmitTicket( data->LogonHandle, data->PackageId, context, creds ))
        return KRB5_OK;
#endif /* KERB_SUBMIT_TICKET */

    /* If not, lets try to obtain a matching ticket from the KDC */
    if ( creds->ticket_flags != 0 && creds->keyblock.enctype != 0 ) {
        /* if not, we must try to get a ticket without specifying any flags or etypes */
        kret = krb5_copy_creds(context, creds, &creds_noflags);
        if (kret == 0) {
            creds_noflags->ticket_flags = 0;
            creds_noflags->keyblock.enctype = 0;

            GetMSCacheTicketFromMITCred(data->LogonHandle, data->PackageId, context, creds_noflags, &msticket2);
            krb5_free_creds(context, creds_noflags);
        }
    }

    GetMSCacheTicketFromMITCred(data->LogonHandle, data->PackageId, context, creds, &msticket);
    if (msticket || msticket2) {
        if (msticket)
            LsaFreeReturnBuffer(msticket);
        if (msticket2)
            LsaFreeReturnBuffer(msticket2);
        return KRB5_OK;
    }
    return KRB5_CC_READONLY;
}

/*
 * Individual credentials can be implemented differently depending
 * on the operating system version.  (undocumented.)
 *
 * Errors:
 *    KRB5_CC_READONLY:
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_remove_cred(krb5_context context, krb5_ccache id, krb5_flags flags,
                     krb5_creds *creds)
{
    krb5_lcc_data *data = (krb5_lcc_data *)id->data;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    if (!is_windows_xp()) {
        if ( PurgeTicket2000( data->LogonHandle, data->PackageId, context, creds) )
            return KRB5_OK;
    } else {
        if ( PurgeTicketXP( data->LogonHandle, data->PackageId, context, flags, creds) )
            return KRB5_OK;
    }

    return KRB5_CC_READONLY;
}


/*
 * Effects:
 *   Set
 */
static krb5_error_code KRB5_CALLCONV
krb5_lcc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags)
{
    krb5_lcc_data *data = (krb5_lcc_data *)id->data;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    data->flags = flags;
    return KRB5_OK;
}

static krb5_error_code KRB5_CALLCONV
krb5_lcc_get_flags(krb5_context context, krb5_ccache id, krb5_flags *flags)
{
    krb5_lcc_data *data = (krb5_lcc_data *)id->data;

    if (!is_windows_2000())
        return KRB5_FCC_NOFILE;

    *flags = data->flags;
    return KRB5_OK;
}

static krb5_error_code KRB5_CALLCONV
krb5_lcc_ptcursor_new(krb5_context context, krb5_cc_ptcursor *cursor)
{
    krb5_cc_ptcursor new_cursor = (krb5_cc_ptcursor )malloc(sizeof(*new_cursor));
    if (!new_cursor)
        return ENOMEM;
    new_cursor->ops = &krb5_lcc_ops;
    new_cursor->data = (krb5_pointer)(1);
    *cursor = new_cursor;
    new_cursor = NULL;
    return 0;
}

static krb5_error_code KRB5_CALLCONV
krb5_lcc_ptcursor_next(krb5_context context, krb5_cc_ptcursor cursor, krb5_ccache *ccache)
{
    krb5_error_code code = 0;
    *ccache = 0;
    if (cursor->data == NULL)
        return 0;

    cursor->data = NULL;
    if ((code = krb5_lcc_resolve(context, ccache, ""))) {
        if (code != KRB5_FCC_NOFILE)
            /* Note that we only want to return serious errors.
             * Any non-zero return code will prevent the cccol iterator
             * from advancing to the next ccache collection. */
            return code;
    }
    return 0;
}

static krb5_error_code KRB5_CALLCONV
krb5_lcc_ptcursor_free(krb5_context context, krb5_cc_ptcursor *cursor)
{
    if (*cursor) {
        free(*cursor);
        *cursor = NULL;
    }
    return 0;
}

const krb5_cc_ops krb5_lcc_ops = {
    0,
    "MSLSA",
    krb5_lcc_get_name,
    krb5_lcc_resolve,
    krb5_lcc_generate_new,
    krb5_lcc_initialize,
    krb5_lcc_destroy,
    krb5_lcc_close,
    krb5_lcc_store,
    krb5_lcc_retrieve,
    krb5_lcc_get_principal,
    krb5_lcc_start_seq_get,
    krb5_lcc_next_cred,
    krb5_lcc_end_seq_get,
    krb5_lcc_remove_cred,
    krb5_lcc_set_flags,
    krb5_lcc_get_flags,
    krb5_lcc_ptcursor_new,
    krb5_lcc_ptcursor_next,
    krb5_lcc_ptcursor_free,
    NULL, /* move */
    NULL, /* lastchange */
    NULL, /* wasdefault */
    NULL, /* lock */
    NULL, /* unlock */
    NULL, /* switch_to */
};
#endif /* _WIN32 */