summaryrefslogtreecommitdiff
path: root/source3/libsmb/clikrb5.c
blob: 4eb43cfff1d1f005241ef4a5f6999d82e0a2c633 (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
/* 
   Unix SMB/CIFS implementation.
   simple kerberos5 routines for active directory
   Copyright (C) Andrew Tridgell 2001
   Copyright (C) Luke Howard 2002-2003
   Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
   Copyright (C) Guenther Deschner 2005-2009
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "includes.h"
#include "smb_krb5.h"
#include "../librpc/gen_ndr/krb5pac.h"

#ifndef KRB5_AUTHDATA_WIN2K_PAC
#define KRB5_AUTHDATA_WIN2K_PAC 128
#endif

#ifndef KRB5_AUTHDATA_IF_RELEVANT
#define KRB5_AUTHDATA_IF_RELEVANT 1
#endif

#ifdef HAVE_KRB5

#define GSSAPI_CHECKSUM      0x8003             /* Checksum type value for Kerberos */
#define GSSAPI_BNDLENGTH     16                 /* Bind Length (rfc-1964 pg.3) */
#define GSSAPI_CHECKSUM_SIZE (4+GSSAPI_BNDLENGTH+4) /* Length of bind length,
							bind field, flags field. */

/* MIT krb5 1.7beta3 (in Ubuntu Karmic) is missing the prototype,
   but still has the symbol */
#if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
krb5_error_code krb5_auth_con_set_req_cksumtype(  
	krb5_context     context,
	krb5_auth_context      auth_context,  
	krb5_cksumtype     cksumtype);
#endif

/**************************************************************
 Wrappers around kerberos string functions that convert from
 utf8 -> unix charset and vica versa.
**************************************************************/

/**************************************************************
 krb5_parse_name that takes a UNIX charset.
**************************************************************/

 krb5_error_code smb_krb5_parse_name(krb5_context context,
				const char *name, /* in unix charset */
				krb5_principal *principal)
{
	krb5_error_code ret;
	char *utf8_name;
	size_t converted_size;

	if (!push_utf8_talloc(talloc_tos(), &utf8_name, name, &converted_size)) {
		return ENOMEM;
	}

	ret = krb5_parse_name(context, utf8_name, principal);
	TALLOC_FREE(utf8_name);
	return ret;
}

#ifdef HAVE_KRB5_PARSE_NAME_NOREALM
/**************************************************************
 krb5_parse_name_norealm that takes a UNIX charset.
**************************************************************/

static krb5_error_code smb_krb5_parse_name_norealm_conv(krb5_context context,
				const char *name, /* in unix charset */
				krb5_principal *principal)
{
	krb5_error_code ret;
	char *utf8_name;
	size_t converted_size;

	*principal = NULL;
	if (!push_utf8_talloc(talloc_tos(), &utf8_name, name, &converted_size)) {
		return ENOMEM;
	}

	ret = krb5_parse_name_norealm(context, utf8_name, principal);
	TALLOC_FREE(utf8_name);
	return ret;
}
#endif

/**************************************************************
 krb5_parse_name that returns a UNIX charset name. Must
 be freed with talloc_free() call.
**************************************************************/

krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
				      krb5_context context,
				      krb5_const_principal principal,
				      char **unix_name)
{
	krb5_error_code ret;
	char *utf8_name;
	size_t converted_size;

	*unix_name = NULL;
	ret = krb5_unparse_name(context, principal, &utf8_name);
	if (ret) {
		return ret;
	}

	if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
		krb5_free_unparsed_name(context, utf8_name);
		return ENOMEM;
	}
	krb5_free_unparsed_name(context, utf8_name);
	return 0;
}

#ifndef HAVE_KRB5_SET_REAL_TIME
/*
 * This function is not in the Heimdal mainline.
 */
 krb5_error_code krb5_set_real_time(krb5_context context, int32_t seconds, int32_t microseconds)
{
	krb5_error_code ret;
	int32_t sec, usec;

	ret = krb5_us_timeofday(context, &sec, &usec);
	if (ret)
		return ret;

	context->kdc_sec_offset = seconds - sec;
	context->kdc_usec_offset = microseconds - usec;

	return 0;
}
#endif

#if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)

#if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)

/* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
 * to krb5_set_default_tgs_ktypes. See
 *         http://lists.samba.org/archive/samba-technical/2006-July/048271.html
 *
 * If the MIT libraries are not exporting internal symbols, we will end up in
 * this branch, which is correct. Otherwise we will continue to use the
 * internal symbol
 */
 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
{
    return krb5_set_default_tgs_enctypes(ctx, enc);
}

#elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)

/* Heimdal */
 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
{
	return krb5_set_default_in_tkt_etypes(ctx, enc);
}

#endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */

#endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */

#if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
/* HEIMDAL */
 bool setup_kaddr( krb5_address *pkaddr, struct sockaddr_storage *paddr)
{
	memset(pkaddr, '\0', sizeof(krb5_address));
#if defined(HAVE_IPV6) && defined(KRB5_ADDRESS_INET6)
	if (paddr->ss_family == AF_INET6) {
		pkaddr->addr_type = KRB5_ADDRESS_INET6;
		pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
		pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
		return true;
	}
#endif
	if (paddr->ss_family == AF_INET) {
		pkaddr->addr_type = KRB5_ADDRESS_INET;
		pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
		pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
		return true;
	}
	return false;
}
#elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
/* MIT */
 bool setup_kaddr( krb5_address *pkaddr, struct sockaddr_storage *paddr)
{
	memset(pkaddr, '\0', sizeof(krb5_address));
#if defined(HAVE_IPV6) && defined(ADDRTYPE_INET6)
	if (paddr->ss_family == AF_INET6) {
		pkaddr->addrtype = ADDRTYPE_INET6;
		pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
		pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
		return true;
	}
#endif
	if (paddr->ss_family == AF_INET) {
		pkaddr->addrtype = ADDRTYPE_INET;
		pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
		pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
		return true;
	}
	return false;
}
#else
#error UNKNOWN_ADDRTYPE
#endif

#if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_USE_ENCTYPE) && defined(HAVE_KRB5_STRING_TO_KEY) && defined(HAVE_KRB5_ENCRYPT_BLOCK)
static int create_kerberos_key_from_string_direct(krb5_context context,
						  krb5_principal host_princ,
						  krb5_data *password,
						  krb5_keyblock *key,
						  krb5_enctype enctype)
{
	int ret = 0;
	krb5_data salt;
	krb5_encrypt_block eblock;

	ret = krb5_principal2salt(context, host_princ, &salt);
	if (ret) {
		DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
		return ret;
	}
	krb5_use_enctype(context, &eblock, enctype);
	ret = krb5_string_to_key(context, &eblock, key, password, &salt);
	SAFE_FREE(salt.data);

	return ret;
}
#elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
static int create_kerberos_key_from_string_direct(krb5_context context,
						  krb5_principal host_princ,
						  krb5_data *password,
						  krb5_keyblock *key,
						  krb5_enctype enctype)
{
	int ret;
	krb5_salt salt;

	ret = krb5_get_pw_salt(context, host_princ, &salt);
	if (ret) {
		DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
		return ret;
	}

	ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, salt, key);
	krb5_free_salt(context, salt);

	return ret;
}
#else
#error UNKNOWN_CREATE_KEY_FUNCTIONS
#endif

 int create_kerberos_key_from_string(krb5_context context,
					krb5_principal host_princ,
					krb5_data *password,
					krb5_keyblock *key,
					krb5_enctype enctype,
					bool no_salt)
{
	krb5_principal salt_princ = NULL;
	int ret;
	/*
	 * Check if we've determined that the KDC is salting keys for this
	 * principal/enctype in a non-obvious way.  If it is, try to match
	 * its behavior.
	 */
	if (no_salt) {
		KRB5_KEY_DATA(key) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
		if (!KRB5_KEY_DATA(key)) {
			return ENOMEM;
		}
		memcpy(KRB5_KEY_DATA(key), password->data, password->length);
		KRB5_KEY_LENGTH(key) = password->length;
		KRB5_KEY_TYPE(key) = enctype;
		return 0;
	}
	salt_princ = kerberos_fetch_salt_princ_for_host_princ(context, host_princ, enctype);
	ret = create_kerberos_key_from_string_direct(context, salt_princ ? salt_princ : host_princ, password, key, enctype);
	if (salt_princ) {
		krb5_free_principal(context, salt_princ);
	}
	return ret;
}

#if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
 krb5_error_code get_kerberos_allowed_etypes(krb5_context context, 
					    krb5_enctype **enctypes)
{
	return krb5_get_permitted_enctypes(context, enctypes);
}
#elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
 krb5_error_code get_kerberos_allowed_etypes(krb5_context context, 
					    krb5_enctype **enctypes)
{
	return krb5_get_default_in_tkt_etypes(context, enctypes);
}
#else
#error UNKNOWN_GET_ENCTYPES_FUNCTIONS
#endif

#if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
 krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
					krb5_auth_context auth_context,
					krb5_keyblock *keyblock)
{
	return krb5_auth_con_setkey(context, auth_context, keyblock);
}
#endif

bool unwrap_edata_ntstatus(TALLOC_CTX *mem_ctx, 
			   DATA_BLOB *edata, 
			   DATA_BLOB *edata_out)
{
	DATA_BLOB edata_contents;
	ASN1_DATA *data;
	int edata_type;

	if (!edata->length) {
		return False;
	}

	data = asn1_init(mem_ctx);
	if (data == NULL) {
		return false;
	}

	asn1_load(data, *edata);
	asn1_start_tag(data, ASN1_SEQUENCE(0));
	asn1_start_tag(data, ASN1_CONTEXT(1));
	asn1_read_Integer(data, &edata_type);

	if (edata_type != KRB5_PADATA_PW_SALT) {
		DEBUG(0,("edata is not of required type %d but of type %d\n", 
			KRB5_PADATA_PW_SALT, edata_type));
		asn1_free(data);
		return False;
	}
	
	asn1_start_tag(data, ASN1_CONTEXT(2));
	asn1_read_OctetString(data, talloc_autofree_context(), &edata_contents);
	asn1_end_tag(data);
	asn1_end_tag(data);
	asn1_end_tag(data);
	asn1_free(data);

	*edata_out = data_blob_talloc(mem_ctx, edata_contents.data, edata_contents.length);

	data_blob_free(&edata_contents);

	return True;
}


bool unwrap_pac(TALLOC_CTX *mem_ctx, DATA_BLOB *auth_data, DATA_BLOB *unwrapped_pac_data)
{
	DATA_BLOB pac_contents;
	ASN1_DATA *data;
	int data_type;

	if (!auth_data->length) {
		return False;
	}

	data = asn1_init(mem_ctx);
	if (data == NULL) {
		return false;
	}

	asn1_load(data, *auth_data);
	asn1_start_tag(data, ASN1_SEQUENCE(0));
	asn1_start_tag(data, ASN1_SEQUENCE(0));
	asn1_start_tag(data, ASN1_CONTEXT(0));
	asn1_read_Integer(data, &data_type);
	
	if (data_type != KRB5_AUTHDATA_WIN2K_PAC ) {
		DEBUG(10,("authorization data is not a Windows PAC (type: %d)\n", data_type));
		asn1_free(data);
		return False;
	}
	
	asn1_end_tag(data);
	asn1_start_tag(data, ASN1_CONTEXT(1));
	asn1_read_OctetString(data, talloc_autofree_context(), &pac_contents);
	asn1_end_tag(data);
	asn1_end_tag(data);
	asn1_end_tag(data);
	asn1_free(data);

	*unwrapped_pac_data = data_blob_talloc(mem_ctx, pac_contents.data, pac_contents.length);

	data_blob_free(&pac_contents);

	return True;
}

 bool get_auth_data_from_tkt(TALLOC_CTX *mem_ctx, DATA_BLOB *auth_data, krb5_ticket *tkt)
{
	DATA_BLOB auth_data_wrapped;
	bool got_auth_data_pac = False;
	int i;
	
#if defined(HAVE_KRB5_TKT_ENC_PART2)
	if (tkt->enc_part2 && tkt->enc_part2->authorization_data && 
	    tkt->enc_part2->authorization_data[0] && 
	    tkt->enc_part2->authorization_data[0]->length)
	{
		for (i = 0; tkt->enc_part2->authorization_data[i] != NULL; i++) {
		
			if (tkt->enc_part2->authorization_data[i]->ad_type != 
			    KRB5_AUTHDATA_IF_RELEVANT) {
				DEBUG(10,("get_auth_data_from_tkt: ad_type is %d\n", 
					tkt->enc_part2->authorization_data[i]->ad_type));
				continue;
			}

			auth_data_wrapped = data_blob(tkt->enc_part2->authorization_data[i]->contents,
						      tkt->enc_part2->authorization_data[i]->length);

			/* check if it is a PAC */
			got_auth_data_pac = unwrap_pac(mem_ctx, &auth_data_wrapped, auth_data);
			data_blob_free(&auth_data_wrapped);

			if (got_auth_data_pac) {
				return true;
			}
		}

		return got_auth_data_pac;
	}
		
#else
	if (tkt->ticket.authorization_data && 
	    tkt->ticket.authorization_data->len)
	{
		for (i = 0; i < tkt->ticket.authorization_data->len; i++) {
			
			if (tkt->ticket.authorization_data->val[i].ad_type != 
			    KRB5_AUTHDATA_IF_RELEVANT) {
				DEBUG(10,("get_auth_data_from_tkt: ad_type is %d\n", 
					tkt->ticket.authorization_data->val[i].ad_type));
				continue;
			}

			auth_data_wrapped = data_blob(tkt->ticket.authorization_data->val[i].ad_data.data,
						      tkt->ticket.authorization_data->val[i].ad_data.length);

			/* check if it is a PAC */
			got_auth_data_pac = unwrap_pac(mem_ctx, &auth_data_wrapped, auth_data);
			data_blob_free(&auth_data_wrapped);

			if (got_auth_data_pac) {
				return true;
			}
		}

		return got_auth_data_pac;
	}
#endif
	return False;
}

 krb5_const_principal get_principal_from_tkt(krb5_ticket *tkt)
{
#if defined(HAVE_KRB5_TKT_ENC_PART2)
	return tkt->enc_part2->client;
#else
	return tkt->client;
#endif
}

#if !defined(HAVE_KRB5_LOCATE_KDC)

/* krb5_locate_kdc is an internal MIT symbol. MIT are not yet willing to commit
 * to a public interface for this functionality, so we have to be able to live
 * without it if the MIT libraries are hiding their internal symbols.
 */

#if defined(KRB5_KRBHST_INIT)
/* Heimdal */
 krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm, struct sockaddr **addr_pp, int *naddrs, int get_masters)
{
	krb5_krbhst_handle hnd;
	krb5_krbhst_info *hinfo;
	krb5_error_code rc;
	int num_kdcs, i;
	struct sockaddr *sa;
	struct addrinfo *ai;

	*addr_pp = NULL;
	*naddrs = 0;

	rc = krb5_krbhst_init(ctx, realm->data, KRB5_KRBHST_KDC, &hnd);
	if (rc) {
		DEBUG(0, ("smb_krb5_locate_kdc: krb5_krbhst_init failed (%s)\n", error_message(rc)));
		return rc;
	}

	for ( num_kdcs = 0; (rc = krb5_krbhst_next(ctx, hnd, &hinfo) == 0); num_kdcs++)
		;

	krb5_krbhst_reset(ctx, hnd);

	if (!num_kdcs) {
		DEBUG(0, ("smb_krb5_locate_kdc: zero kdcs found !\n"));
		krb5_krbhst_free(ctx, hnd);
		return -1;
	}

	sa = SMB_MALLOC_ARRAY( struct sockaddr, num_kdcs );
	if (!sa) {
		DEBUG(0, ("smb_krb5_locate_kdc: malloc failed\n"));
		krb5_krbhst_free(ctx, hnd);
		naddrs = 0;
		return -1;
	}

	memset(sa, '\0', sizeof(struct sockaddr) * num_kdcs );

	for (i = 0; i < num_kdcs && (rc = krb5_krbhst_next(ctx, hnd, &hinfo) == 0); i++) {

#if defined(HAVE_KRB5_KRBHST_GET_ADDRINFO)
		rc = krb5_krbhst_get_addrinfo(ctx, hinfo, &ai);
		if (rc) {
			DEBUG(0,("krb5_krbhst_get_addrinfo failed: %s\n", error_message(rc)));
			continue;
		}
#endif
		if (hinfo->ai && hinfo->ai->ai_family == AF_INET) 
			memcpy(&sa[i], hinfo->ai->ai_addr, sizeof(struct sockaddr));
	}

	krb5_krbhst_free(ctx, hnd);

	*naddrs = num_kdcs;
	*addr_pp = sa;
	return 0;
}

#else /* ! defined(KRB5_KRBHST_INIT) */

 krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm,
		struct sockaddr **addr_pp, int *naddrs, int get_masters)
{
	DEBUG(0, ("unable to explicitly locate the KDC on this platform\n"));
	return KRB5_KDC_UNREACH;
}

#endif /* KRB5_KRBHST_INIT */

#else /* ! HAVE_KRB5_LOCATE_KDC */

 krb5_error_code smb_krb5_locate_kdc(krb5_context ctx, const krb5_data *realm,
		struct sockaddr **addr_pp, int *naddrs, int get_masters)
{
	return krb5_locate_kdc(ctx, realm, addr_pp, naddrs, get_masters);
}

#endif /* HAVE_KRB5_LOCATE_KDC */

#if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
 void krb5_free_unparsed_name(krb5_context context, char *val)
{
	SAFE_FREE(val);
}
#endif

 void kerberos_free_data_contents(krb5_context context, krb5_data *pdata)
{
#if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
	if (pdata->data) {
		krb5_free_data_contents(context, pdata);
	}
#else
	SAFE_FREE(pdata->data);
#endif
}

 void kerberos_set_creds_enctype(krb5_creds *pcreds, int enctype)
{
#if defined(HAVE_KRB5_KEYBLOCK_IN_CREDS)
	KRB5_KEY_TYPE((&pcreds->keyblock)) = enctype;
#elif defined(HAVE_KRB5_SESSION_IN_CREDS)
	KRB5_KEY_TYPE((&pcreds->session)) = enctype;
#else
#error UNKNOWN_KEYBLOCK_MEMBER_IN_KRB5_CREDS_STRUCT
#endif
}

 bool kerberos_compatible_enctypes(krb5_context context,
				  krb5_enctype enctype1,
				  krb5_enctype enctype2)
{
#if defined(HAVE_KRB5_C_ENCTYPE_COMPARE)
	krb5_boolean similar = 0;

	krb5_c_enctype_compare(context, enctype1, enctype2, &similar);
	return similar ? True : False;
#elif defined(HAVE_KRB5_ENCTYPES_COMPATIBLE_KEYS)
	return krb5_enctypes_compatible_keys(context, enctype1, enctype2) ? True : False;
#endif
}

static bool ads_cleanup_expired_creds(krb5_context context, 
				      krb5_ccache  ccache,
				      krb5_creds  *credsp)
{
	krb5_error_code retval;
	const char *cc_type = krb5_cc_get_type(context, ccache);

	DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
		  cc_type, krb5_cc_get_name(context, ccache),
		  http_timestring(talloc_tos(), credsp->times.endtime)));

	/* we will probably need new tickets if the current ones
	   will expire within 10 seconds.
	*/
	if (credsp->times.endtime >= (time(NULL) + 10))
		return False;

	/* heimdal won't remove creds from a file ccache, and 
	   perhaps we shouldn't anyway, since internally we 
	   use memory ccaches, and a FILE one probably means that
	   we're using creds obtained outside of our exectuable
	*/
	if (strequal(cc_type, "FILE")) {
		DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
		return False;
	}

	retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
	if (retval) {
		DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
			  error_message(retval)));
		/* If we have an error in this, we want to display it,
		   but continue as though we deleted it */
	}
	return True;
}

/* Allocate and setup the auth context into the state we need. */

static krb5_error_code setup_auth_context(krb5_context context,
			krb5_auth_context *auth_context)
{
	krb5_error_code retval;

	retval = krb5_auth_con_init(context, auth_context );
	if (retval) {
		DEBUG(1,("krb5_auth_con_init failed (%s)\n",
			error_message(retval)));
		return retval;
	}

	/* Ensure this is an addressless ticket. */
	retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
	if (retval) {
		DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
			error_message(retval)));
	}

	return retval;
}

static krb5_error_code create_gss_checksum(krb5_data *in_data, /* [inout] */
						uint32_t gss_flags)
{
	unsigned int orig_length = in_data->length;
	unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
	char *gss_cksum = NULL;

	if (orig_length) {
		/* Extra length field for delgated ticket. */
		base_cksum_size += 4;
	}

	if ((unsigned int)base_cksum_size + orig_length <
			(unsigned int)base_cksum_size) {
                return EINVAL;
        }

	gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
	if (gss_cksum == NULL) {
		return ENOMEM;
        }

	memset(gss_cksum, '\0', base_cksum_size + orig_length);
	SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);

	/* Precalculated MD5sum of NULL channel bindings (20 bytes) */
	/* Channel bindings are: (all ints encoded as little endian)

		[4 bytes] initiator_addrtype (255 for null bindings)
		[4 bytes] initiator_address length
			[n bytes] .. initiator_address data - not present
				     in null bindings.
		[4 bytes] acceptor_addrtype (255 for null bindings)
		[4 bytes] acceptor_address length
			[n bytes] .. acceptor_address data - not present
				     in null bindings.
		[4 bytes] application_data length
			[n bytes] .. application_ data - not present
				     in null bindings.
		MD5 of this is ""\x14\x8f\x0c\xf7\xb1u\xdey*J\x9a%\xdfV\xc5\x18"
	*/

	memcpy(&gss_cksum[4],
		"\x14\x8f\x0c\xf7\xb1u\xdey*J\x9a%\xdfV\xc5\x18",
		GSSAPI_BNDLENGTH);

	SIVAL(gss_cksum, 20, gss_flags);

	if (orig_length) {
		SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
		SSVAL(gss_cksum, 26, orig_length);
		/* Copy the kerberos KRB_CRED data */
		memcpy(gss_cksum + 28, in_data->data, orig_length);
		free(in_data->data);
		in_data->data = NULL;
		in_data->length = 0;
	}
	in_data->data = gss_cksum;
	in_data->length = base_cksum_size + orig_length;
	return 0;
}

/*
  we can't use krb5_mk_req because w2k wants the service to be in a particular format
*/
static krb5_error_code ads_krb5_mk_req(krb5_context context, 
				       krb5_auth_context *auth_context, 
				       const krb5_flags ap_req_options,
				       const char *principal,
				       krb5_ccache ccache, 
				       krb5_data *outbuf, 
				       time_t *expire_time,
				       const char *impersonate_princ_s)
{
	krb5_error_code 	  retval;
	krb5_principal	  server;
	krb5_principal impersonate_princ = NULL;
	krb5_creds 		* credsp;
	krb5_creds 		  creds;
	krb5_data in_data;
	bool creds_ready = False;
	int i = 0, maxtries = 3;
	uint32_t gss_flags = 0;

	ZERO_STRUCT(in_data);

	retval = smb_krb5_parse_name(context, principal, &server);
	if (retval) {
		DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
		return retval;
	}

	if (impersonate_princ_s) {
		retval = smb_krb5_parse_name(context, impersonate_princ_s,
					     &impersonate_princ);
		if (retval) {
			DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
			goto cleanup_princ;
		}
	}

	/* obtain ticket & session key */
	ZERO_STRUCT(creds);
	if ((retval = krb5_copy_principal(context, server, &creds.server))) {
		DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n", 
			 error_message(retval)));
		goto cleanup_princ;
	}
	
	if ((retval = krb5_cc_get_principal(context, ccache, &creds.client))) {
		/* This can commonly fail on smbd startup with no ticket in the cache.
		 * Report at higher level than 1. */
		DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
			 error_message(retval)));
		goto cleanup_creds;
	}

	while (!creds_ready && (i < maxtries)) {

		if ((retval = smb_krb5_get_credentials(context, ccache,
						       creds.client,
						       creds.server,
						       impersonate_princ,
						       &credsp))) {
			DEBUG(1,("ads_krb5_mk_req: smb_krb5_get_credentials failed for %s (%s)\n",
				principal, error_message(retval)));
			goto cleanup_creds;
		}

		/* cope with ticket being in the future due to clock skew */
		if ((unsigned)credsp->times.starttime > time(NULL)) {
			time_t t = time(NULL);
			int time_offset =(int)((unsigned)credsp->times.starttime-t);
			DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
			krb5_set_real_time(context, t + time_offset + 1, 0);
		}

		if (!ads_cleanup_expired_creds(context, ccache, credsp)) {
			creds_ready = True;
		}

		i++;
	}

	DEBUG(10,("ads_krb5_mk_req: Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
		  principal, krb5_cc_get_type(context, ccache), krb5_cc_get_name(context, ccache),
		  http_timestring(talloc_tos(), (unsigned)credsp->times.endtime), 
		  (unsigned)credsp->times.endtime));

	if (expire_time) {
		*expire_time = (time_t)credsp->times.endtime;
	}

	/* Allocate the auth_context. */
	retval = setup_auth_context(context, auth_context);
	if (retval) {
		DEBUG(1,("setup_auth_context failed (%s)\n",
			error_message(retval)));
		goto cleanup_creds;
	}

#if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_FWD_TGT_CREDS) && defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY)
	if( credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE ) {
		/* Fetch a forwarded TGT from the KDC so that we can hand off a 2nd ticket
		 as part of the kerberos exchange. */

		DEBUG( 3, ("ads_krb5_mk_req: server marked as OK to delegate to, building forwardable TGT\n")  );

		retval = krb5_auth_con_setuseruserkey(context,
					*auth_context,
					&credsp->keyblock );
		if (retval) {
			DEBUG(1,("krb5_auth_con_setuseruserkey failed (%s)\n",
				error_message(retval)));
			goto cleanup_creds;
		}

		/* Must use a subkey for forwarded tickets. */
		retval = krb5_auth_con_setflags(context,
				*auth_context,
				KRB5_AUTH_CONTEXT_USE_SUBKEY);
		if (retval) {
			DEBUG(1,("krb5_auth_con_setflags failed (%s)\n",
				error_message(retval)));
			goto cleanup_creds;
		}

		retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
				*auth_context,  /* Authentication context [in] */
				CONST_DISCARD(char *, KRB5_TGS_NAME),  /* Ticket service name ("krbtgt") [in] */
				credsp->client, /* Client principal for the tgt [in] */
				credsp->server, /* Server principal for the tgt [in] */
				ccache,         /* Credential cache to use for storage [in] */
				1,              /* Turn on for "Forwardable ticket" [in] */
				&in_data );     /* Resulting response [out] */

		if (retval) {
			DEBUG( 3, ("krb5_fwd_tgt_creds failed (%s)\n",
				   error_message( retval ) ) );

			/*
			 * This is not fatal. Delete the *auth_context and continue
			 * with krb5_mk_req_extended to get a non-forwardable ticket.
			 */

			if (in_data.data) {
				free( in_data.data );
				in_data.data = NULL;
				in_data.length = 0;
			}
			krb5_auth_con_free(context, *auth_context);
			*auth_context = NULL;
			retval = setup_auth_context(context, auth_context);
			if (retval) {
				DEBUG(1,("setup_auth_context failed (%s)\n",
					error_message(retval)));
				goto cleanup_creds;
			}
		} else {
			/* We got a delegated ticket. */
			gss_flags |= GSS_C_DELEG_FLAG;
		}
	}
#endif

	/* Frees and reallocates in_data into a GSS checksum blob. */
	retval = create_gss_checksum(&in_data, gss_flags);
	if (retval) {
		goto cleanup_data;
	}

#if defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
	/* We always want GSS-checksum types. */
	retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
	if (retval) {
		DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
			error_message(retval)));
		goto cleanup_data;
	}
#endif

	retval = krb5_mk_req_extended(context, auth_context, ap_req_options, 
				      &in_data, credsp, outbuf);
	if (retval) {
		DEBUG(1,("ads_krb5_mk_req: krb5_mk_req_extended failed (%s)\n", 
			 error_message(retval)));
	}

cleanup_data:
	if (in_data.data) {
		free( in_data.data );
		in_data.length = 0;
	}

	krb5_free_creds(context, credsp);

cleanup_creds:
	krb5_free_cred_contents(context, &creds);

cleanup_princ:
	krb5_free_principal(context, server);
	if (impersonate_princ) {
		krb5_free_principal(context, impersonate_princ);
	}

	return retval;
}

/*
  get a kerberos5 ticket for the given service
*/
int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
			const char *principal, time_t time_offset,
			DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
			uint32_t extra_ap_opts, const char *ccname,
			time_t *tgs_expire,
			const char *impersonate_princ_s)

{
	krb5_error_code retval;
	krb5_data packet;
	krb5_context context = NULL;
	krb5_ccache ccdef = NULL;
	krb5_auth_context auth_context = NULL;
	krb5_enctype enc_types[] = {
#ifdef ENCTYPE_ARCFOUR_HMAC
		ENCTYPE_ARCFOUR_HMAC,
#endif
		ENCTYPE_DES_CBC_MD5,
		ENCTYPE_DES_CBC_CRC,
		ENCTYPE_NULL};

	initialize_krb5_error_table();
	retval = krb5_init_context(&context);
	if (retval) {
		DEBUG(1, ("krb5_init_context failed (%s)\n",
			 error_message(retval)));
		goto failed;
	}

	if (time_offset != 0) {
		krb5_set_real_time(context, time(NULL) + time_offset, 0);
	}

	if ((retval = krb5_cc_resolve(context, ccname ?
			ccname : krb5_cc_default_name(context), &ccdef))) {
		DEBUG(1, ("krb5_cc_default failed (%s)\n",
			 error_message(retval)));
		goto failed;
	}

	if ((retval = krb5_set_default_tgs_ktypes(context, enc_types))) {
		DEBUG(1, ("krb5_set_default_tgs_ktypes failed (%s)\n",
			 error_message(retval)));
		goto failed;
	}

	retval = ads_krb5_mk_req(context, &auth_context,
				AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
				principal, ccdef, &packet,
				tgs_expire, impersonate_princ_s);
	if (retval) {
		goto failed;
	}

	get_krb5_smb_session_key(mem_ctx, context, auth_context,
				 session_key_krb5, false);

	*ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);

 	kerberos_free_data_contents(context, &packet);

failed:

	if (context) {
		if (ccdef)
			krb5_cc_close(context, ccdef);
		if (auth_context)
			krb5_auth_con_free(context, auth_context);
		krb5_free_context(context);
	}

	return retval;
}

bool get_krb5_smb_session_key(TALLOC_CTX *mem_ctx,
			      krb5_context context,
			      krb5_auth_context auth_context,
			      DATA_BLOB *session_key, bool remote)
{
	krb5_keyblock *skey = NULL;
	krb5_error_code err = 0;
	bool ret = false;

	if (remote) {
		err = krb5_auth_con_getremotesubkey(context,
						    auth_context, &skey);
	} else {
		err = krb5_auth_con_getlocalsubkey(context,
						   auth_context, &skey);
	}

	if (err || skey == NULL) {
		DEBUG(10, ("KRB5 error getting session key %d\n", err));
		goto done;
	}

	DEBUG(10, ("Got KRB5 session key of length %d\n",
		   (int)KRB5_KEY_LENGTH(skey)));

	*session_key = data_blob_talloc(mem_ctx,
					 KRB5_KEY_DATA(skey),
					 KRB5_KEY_LENGTH(skey));
	dump_data_pw("KRB5 Session Key:\n",
		     session_key->data,
		     session_key->length);

	ret = true;

done:
	if (skey) {
		krb5_free_keyblock(context, skey);
	}

	return ret;
}


#if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
 const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i );

 const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i )
{
	static krb5_data kdata;

	kdata.data = (char *)krb5_principal_get_comp_string(context, principal, i);
	kdata.length = strlen((const char *)kdata.data);
	return &kdata;
}
#endif

 krb5_error_code smb_krb5_kt_free_entry(krb5_context context, krb5_keytab_entry *kt_entry)
{
/* Try krb5_free_keytab_entry_contents first, since 
 * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and 
 * krb5_kt_free_entry but only has a prototype for the first, while the 
 * second is considered private. 
 */
#if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
	return krb5_free_keytab_entry_contents(context, kt_entry);
#elif defined(HAVE_KRB5_KT_FREE_ENTRY)
	return krb5_kt_free_entry(context, kt_entry);
#else
#error UNKNOWN_KT_FREE_FUNCTION
#endif
}

 void smb_krb5_checksum_from_pac_sig(krb5_checksum *cksum,
				     struct PAC_SIGNATURE_DATA *sig)
{
#ifdef HAVE_CHECKSUM_IN_KRB5_CHECKSUM
	cksum->cksumtype	= (krb5_cksumtype)sig->type;
	cksum->checksum.length	= sig->signature.length;
	cksum->checksum.data	= sig->signature.data;
#else
	cksum->checksum_type	= (krb5_cksumtype)sig->type;
	cksum->length		= sig->signature.length;
	cksum->contents		= sig->signature.data;
#endif
}

 krb5_error_code smb_krb5_verify_checksum(krb5_context context,
					  const krb5_keyblock *keyblock,
					 krb5_keyusage usage,
					 krb5_checksum *cksum,
					 uint8 *data,
					 size_t length)
{
	krb5_error_code ret;

	/* verify the checksum */

	/* welcome to the wonderful world of samba's kerberos abstraction layer:
	 * 
	 * function			heimdal 0.6.1rc3	heimdal 0.7	MIT krb 1.4.2
	 * -----------------------------------------------------------------------------
	 * krb5_c_verify_checksum	-			works		works
	 * krb5_verify_checksum		works (6 args)		works (6 args)	broken (7 args) 
	 */

#if defined(HAVE_KRB5_C_VERIFY_CHECKSUM)
	{
		krb5_boolean checksum_valid = False;
		krb5_data input;

		input.data = (char *)data;
		input.length = length;

		ret = krb5_c_verify_checksum(context, 
					     keyblock, 
					     usage,
					     &input, 
					     cksum,
					     &checksum_valid);
		if (ret) {
			DEBUG(3,("smb_krb5_verify_checksum: krb5_c_verify_checksum() failed: %s\n", 
				error_message(ret)));
			return ret;
		}

		if (!checksum_valid)
			ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
	}

#elif KRB5_VERIFY_CHECKSUM_ARGS == 6 && defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CRYPTO) && defined(HAVE_KRB5_CRYPTO_DESTROY)

	/* Warning: MIT's krb5_verify_checksum cannot be used as it will use a key
	 * without enctype and it ignores any key_usage types - Guenther */

	{

		krb5_crypto crypto;
		ret = krb5_crypto_init(context,
				       keyblock,
				       0,
				       &crypto);
		if (ret) {
			DEBUG(0,("smb_krb5_verify_checksum: krb5_crypto_init() failed: %s\n", 
				error_message(ret)));
			return ret;
		}

		ret = krb5_verify_checksum(context,
					   crypto,
					   usage,
					   data,
					   length,
					   cksum);

		krb5_crypto_destroy(context, crypto);
	}

#else
#error UNKNOWN_KRB5_VERIFY_CHECKSUM_FUNCTION
#endif

	return ret;
}

 time_t get_authtime_from_tkt(krb5_ticket *tkt)
{
#if defined(HAVE_KRB5_TKT_ENC_PART2)
	return tkt->enc_part2->times.authtime;
#else
	return tkt->ticket.authtime;
#endif
}

#ifdef HAVE_KRB5_DECODE_AP_REQ	/* Heimdal */
static int get_kvno_from_ap_req(krb5_ap_req *ap_req)
{
#ifdef HAVE_TICKET_POINTER_IN_KRB5_AP_REQ /* MIT */
	if (ap_req->ticket->enc_part.kvno)
		return ap_req->ticket->enc_part.kvno;
#else /* Heimdal */
	if (ap_req->ticket.enc_part.kvno) 
		return *ap_req->ticket.enc_part.kvno;
#endif
	return 0;
}

static krb5_enctype get_enctype_from_ap_req(krb5_ap_req *ap_req)
{
#ifdef HAVE_ETYPE_IN_ENCRYPTEDDATA /* Heimdal */
	return ap_req->ticket.enc_part.etype;
#else /* MIT */
	return ap_req->ticket->enc_part.enctype;
#endif
}
#endif	/* HAVE_KRB5_DECODE_AP_REQ */

static krb5_error_code
get_key_from_keytab(krb5_context context,
		    krb5_const_principal server,
		    krb5_enctype enctype,
		    krb5_kvno kvno,
		    krb5_keyblock **out_key)
{
	krb5_keytab_entry entry;
	krb5_error_code ret;
	krb5_keytab keytab;
	char *name = NULL;
	krb5_keyblock *keyp;

	/* We have to open a new keytab handle here, as MIT does
	   an implicit open/getnext/close on krb5_kt_get_entry. We
	   may be in the middle of a keytab enumeration when this is
	   called. JRA. */

	ret = smb_krb5_open_keytab(context, NULL, False, &keytab);
	if (ret) {
		DEBUG(1,("get_key_from_keytab: smb_krb5_open_keytab failed (%s)\n", error_message(ret)));
		return ret;
	}

	if ( DEBUGLEVEL >= 10 ) {
		if (smb_krb5_unparse_name(talloc_tos(), context, server, &name) == 0) {
			DEBUG(10,("get_key_from_keytab: will look for kvno %d, enctype %d and name: %s\n", 
				kvno, enctype, name));
			TALLOC_FREE(name);
		}
	}

	ret = krb5_kt_get_entry(context,
				keytab,
				server,
				kvno,
				enctype,
				&entry);

	if (ret) {
		DEBUG(0,("get_key_from_keytab: failed to retrieve key: %s\n", error_message(ret)));
		goto out;
	}

	keyp = KRB5_KT_KEY(&entry);

	ret = krb5_copy_keyblock(context, keyp, out_key);
	if (ret) {
		DEBUG(0,("get_key_from_keytab: failed to copy key: %s\n", error_message(ret)));
		goto out;
	}
		
	smb_krb5_kt_free_entry(context, &entry);
	
out:    
	krb5_kt_close(context, keytab);
	return ret;
}

/* Prototypes */

 krb5_error_code smb_krb5_get_keyinfo_from_ap_req(krb5_context context, 
						 const krb5_data *inbuf, 
						 krb5_kvno *kvno, 
						 krb5_enctype *enctype)
{
#ifdef HAVE_KRB5_DECODE_AP_REQ /* Heimdal */
	{
		krb5_error_code ret;
		krb5_ap_req ap_req;
		
		ret = krb5_decode_ap_req(context, inbuf, &ap_req);
		if (ret)
			return ret;

		*kvno = get_kvno_from_ap_req(&ap_req);
		*enctype = get_enctype_from_ap_req(&ap_req);

 		free_AP_REQ(&ap_req);
 		return 0;
	}
#endif

 	/* Possibly not an appropriate error code. */
 	return KRB5KDC_ERR_BADOPTION;
}

 krb5_error_code krb5_rd_req_return_keyblock_from_keytab(krb5_context context,
							krb5_auth_context *auth_context,
							const krb5_data *inbuf,
							krb5_const_principal server,
							krb5_keytab keytab,
							krb5_flags *ap_req_options,
							krb5_ticket **ticket, 
							krb5_keyblock **keyblock)
{
	krb5_error_code ret;
	krb5_kvno kvno;
	krb5_enctype enctype;
	krb5_keyblock *local_keyblock;

	ret = krb5_rd_req(context, 
			  auth_context, 
			  inbuf, 
			  server, 
			  keytab, 
			  ap_req_options, 
			  ticket);
	if (ret) {
		return ret;
	}
	
#ifdef KRB5_TICKET_HAS_KEYINFO
	enctype = (*ticket)->enc_part.enctype;
	kvno = (*ticket)->enc_part.kvno;
#else
	ret = smb_krb5_get_keyinfo_from_ap_req(context, inbuf, &kvno, &enctype);
	if (ret) {
		return ret;
	}
#endif

	ret = get_key_from_keytab(context, 
				  server,
				  enctype,
				  kvno,
				  &local_keyblock);
	if (ret) {
		DEBUG(0,("krb5_rd_req_return_keyblock_from_keytab: failed to call get_key_from_keytab\n"));
		goto out;
	}

out:
	if (ret && local_keyblock != NULL) {
	        krb5_free_keyblock(context, local_keyblock);
	} else {
		*keyblock = local_keyblock;
	}

	return ret;
}

 krb5_error_code smb_krb5_parse_name_norealm(krb5_context context, 
					    const char *name, 
					    krb5_principal *principal)
{
#ifdef HAVE_KRB5_PARSE_NAME_NOREALM
	return smb_krb5_parse_name_norealm_conv(context, name, principal);
#endif

	/* we are cheating here because parse_name will in fact set the realm.
	 * We don't care as the only caller of smb_krb5_parse_name_norealm
	 * ignores the realm anyway when calling
	 * smb_krb5_principal_compare_any_realm later - Guenther */

	return smb_krb5_parse_name(context, name, principal);
}

 bool smb_krb5_principal_compare_any_realm(krb5_context context, 
					  krb5_const_principal princ1, 
					  krb5_const_principal princ2)
{
#ifdef HAVE_KRB5_PRINCIPAL_COMPARE_ANY_REALM

	return krb5_principal_compare_any_realm(context, princ1, princ2);

/* krb5_princ_size is a macro in MIT */
#elif defined(HAVE_KRB5_PRINC_SIZE) || defined(krb5_princ_size)

	int i, len1, len2;
	const krb5_data *p1, *p2;

	len1 = krb5_princ_size(context, princ1);
	len2 = krb5_princ_size(context, princ2);

	if (len1 != len2)
		return False;

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

		p1 = krb5_princ_component(context, CONST_DISCARD(krb5_principal, princ1), i);
		p2 = krb5_princ_component(context, CONST_DISCARD(krb5_principal, princ2), i);

		if (p1->length != p2->length ||	memcmp(p1->data, p2->data, p1->length))
			return False;
	}

	return True;
#else
#error NO_SUITABLE_PRINCIPAL_COMPARE_FUNCTION
#endif
}

 krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,	/* FILE:/tmp/krb5cc_0 */
				       const char *client_string,	/* gd@BER.SUSE.DE */
				       const char *service_string,	/* krbtgt/BER.SUSE.DE@BER.SUSE.DE */
				       time_t *expire_time)
{
	krb5_error_code ret;
	krb5_context context = NULL;
	krb5_ccache ccache = NULL;
	krb5_principal client = NULL;
	krb5_creds creds, creds_in, *creds_out = NULL;

	ZERO_STRUCT(creds);
	ZERO_STRUCT(creds_in);

	initialize_krb5_error_table();
	ret = krb5_init_context(&context);
	if (ret) {
		goto done;
	}

	if (!ccache_string) {
		ccache_string = krb5_cc_default_name(context);
	}

	if (!ccache_string) {
		ret = EINVAL;
		goto done;
	}

	DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));

	/* FIXME: we should not fall back to defaults */
	ret = krb5_cc_resolve(context, CONST_DISCARD(char *, ccache_string), &ccache);
	if (ret) {
		goto done;
	}

	if (client_string) {
		ret = smb_krb5_parse_name(context, client_string, &client);
		if (ret) {
			goto done;
		}
	} else {
		ret = krb5_cc_get_principal(context, ccache, &client);
		if (ret) {
			goto done;
		}
	}

#ifdef HAVE_KRB5_GET_RENEWED_CREDS	/* MIT */
	{
		ret = krb5_get_renewed_creds(context, &creds, client, ccache, CONST_DISCARD(char *, service_string));
		if (ret) {
			DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
			goto done;
		}
	}
#elif defined(HAVE_KRB5_GET_KDC_CRED)	/* Heimdal */
	{
		krb5_kdc_flags flags;
		krb5_realm *client_realm = NULL;

		ret = krb5_copy_principal(context, client, &creds_in.client);
		if (ret) {
			goto done;
		}

		if (service_string) {
			ret = smb_krb5_parse_name(context, service_string, &creds_in.server);
			if (ret) { 
				goto done;
			}
		} else {
			/* build tgt service by default */
			client_realm = krb5_princ_realm(context, creds_in.client);
			if (!client_realm) {
				ret = ENOMEM;
				goto done;
			}
			ret = krb5_make_principal(context, &creds_in.server, *client_realm, KRB5_TGS_NAME, *client_realm, NULL);
			if (ret) {
				goto done;
			}
		}

		flags.i = 0;
		flags.b.renewable = flags.b.renew = True;

		ret = krb5_get_kdc_cred(context, ccache, flags, NULL, NULL, &creds_in, &creds_out);
		if (ret) {
			DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
			goto done;
		}

		creds = *creds_out;
	}
#else
#error NO_SUITABLE_KRB5_TICKET_RENEW_FUNCTION_AVAILABLE
#endif

	/* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
	ret = krb5_cc_initialize(context, ccache, client);
	if (ret) {
		goto done;
	}
	
	ret = krb5_cc_store_cred(context, ccache, &creds);

	if (expire_time) {
		*expire_time = (time_t) creds.times.endtime;
	}

done:
	krb5_free_cred_contents(context, &creds_in);

	if (creds_out) {
		krb5_free_creds(context, creds_out);
	} else {
		krb5_free_cred_contents(context, &creds);
	}

	if (client) {
		krb5_free_principal(context, client);
	}
	if (ccache) {
		krb5_cc_close(context, ccache);
	}
	if (context) {
		krb5_free_context(context);
	}

	return ret;
}

 krb5_error_code smb_krb5_free_addresses(krb5_context context, smb_krb5_addresses *addr)
{
	krb5_error_code ret = 0;
	if (addr == NULL) {
		return ret;
	}
#if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
	krb5_free_addresses(context, addr->addrs);
#elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
	ret = krb5_free_addresses(context, addr->addrs);
	SAFE_FREE(addr->addrs);
#endif
	SAFE_FREE(addr);
	addr = NULL;
	return ret;
}

 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr)
{
	krb5_error_code ret = 0;
	nstring buf;
#if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
	krb5_address **addrs = NULL;
#elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
	krb5_addresses *addrs = NULL;
#endif

	*kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
	if (*kerb_addr == NULL) {
		return ENOMEM;
	}

	put_name(buf, global_myname(), ' ', 0x20);

#if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
	{
		int num_addr = 2;

		addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
		if (addrs == NULL) {
			SAFE_FREE(*kerb_addr);
			return ENOMEM;
		}

		memset(addrs, 0, sizeof(krb5_address *) * num_addr);

		addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
		if (addrs[0] == NULL) {
			SAFE_FREE(addrs);
			SAFE_FREE(*kerb_addr);
			return ENOMEM;
		}

		addrs[0]->magic = KV5M_ADDRESS;
		addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
		addrs[0]->length = MAX_NETBIOSNAME_LEN;
		addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
		if (addrs[0]->contents == NULL) {
			SAFE_FREE(addrs[0]);
			SAFE_FREE(addrs);
			SAFE_FREE(*kerb_addr);
			return ENOMEM;
		}

		memcpy(addrs[0]->contents, buf, addrs[0]->length);

		addrs[1] = NULL;
	}
#elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
	{
		addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
		if (addrs == NULL) {
			SAFE_FREE(*kerb_addr);
			return ENOMEM;
		}

		memset(addrs, 0, sizeof(krb5_addresses));

		addrs->len = 1;
		addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
		if (addrs->val == NULL) {
			SAFE_FREE(addrs);
			SAFE_FREE(kerb_addr);
			return ENOMEM;
		}

		addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
		addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
		addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
		if (addrs->val[0].address.data == NULL) {
			SAFE_FREE(addrs->val);
			SAFE_FREE(addrs);
			SAFE_FREE(*kerb_addr);
			return ENOMEM;
		}

		memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
	}
#else
#error UNKNOWN_KRB5_ADDRESS_FORMAT
#endif
	(*kerb_addr)->addrs = addrs;

	return ret;
}

 void smb_krb5_free_error(krb5_context context, krb5_error *krberror)
{
#ifdef HAVE_KRB5_FREE_ERROR_CONTENTS /* Heimdal */
	krb5_free_error_contents(context, krberror);
#else /* MIT */
	krb5_free_error(context, krberror);
#endif
}

 krb5_error_code handle_krberror_packet(krb5_context context,
					krb5_data *packet)
{
	krb5_error_code ret;
	bool got_error_code = False;

	DEBUG(10,("handle_krberror_packet: got error packet\n"));
	
#ifdef HAVE_E_DATA_POINTER_IN_KRB5_ERROR /* Heimdal */
	{
		krb5_error krberror;

		if ((ret = krb5_rd_error(context, packet, &krberror))) {
			DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
				error_message(ret)));
			return ret;
		}

		if (krberror.e_data == NULL || krberror.e_data->data == NULL) {
			ret = (krb5_error_code) krberror.error_code;
			got_error_code = True;
		}

		smb_krb5_free_error(context, &krberror);
	}
#else /* MIT */
	{
		krb5_error *krberror;

		if ((ret = krb5_rd_error(context, packet, &krberror))) {
			DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
				error_message(ret)));
			return ret;
		}

		if (krberror->e_data.data == NULL) {
#if defined(ERROR_TABLE_BASE_krb5)
			ret = ERROR_TABLE_BASE_krb5 + (krb5_error_code) krberror->error;
#else
			ret = (krb5_error_code)krberror->error;
#endif
			got_error_code = True;
		}
		smb_krb5_free_error(context, krberror);
	}
#endif
	if (got_error_code) {
		DEBUG(5,("handle_krberror_packet: got KERBERR from kpasswd: %s (%d)\n", 
			error_message(ret), ret));
	}
	return ret;
}

 krb5_error_code smb_krb5_get_init_creds_opt_alloc(krb5_context context,
					    krb5_get_init_creds_opt **opt)
{
#ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_ALLOC
	/* Heimdal or modern MIT version */
	return krb5_get_init_creds_opt_alloc(context, opt);
#else
	/* Historical MIT version */
	krb5_get_init_creds_opt *my_opt;

	*opt = NULL;

	if ((my_opt = SMB_MALLOC_P(krb5_get_init_creds_opt)) == NULL) {
		return ENOMEM;
	}

	krb5_get_init_creds_opt_init(my_opt);

	*opt =  my_opt;
	return 0;
#endif /* HAVE_KRB5_GET_INIT_CREDS_OPT_ALLOC  */
}

 void smb_krb5_get_init_creds_opt_free(krb5_context context,
				krb5_get_init_creds_opt *opt)
{
#ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_FREE

#ifdef KRB5_CREDS_OPT_FREE_REQUIRES_CONTEXT
	/* Modern MIT or Heimdal version */
	krb5_get_init_creds_opt_free(context, opt);
#else
	/* Heimdal version */
	krb5_get_init_creds_opt_free(opt);
#endif /* KRB5_CREDS_OPT_FREE_REQUIRES_CONTEXT */

#else /* HAVE_KRB5_GET_INIT_CREDS_OPT_FREE */
	/* Historical MIT version */
	SAFE_FREE(opt);
	opt = NULL;
#endif /* HAVE_KRB5_GET_INIT_CREDS_OPT_FREE */
}

 krb5_enctype smb_get_enctype_from_kt_entry(krb5_keytab_entry *kt_entry)
{
	return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
}


/* caller needs to free etype_s */
 krb5_error_code smb_krb5_enctype_to_string(krb5_context context, 
 					    krb5_enctype enctype, 
					    char **etype_s)
{
#ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
	return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
#elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
	char buf[256];
	krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
	if (ret) {
		return ret;
	}
	*etype_s = SMB_STRDUP(buf);
	if (!*etype_s) {
		return ENOMEM;
	}
	return ret;
#else
#error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
#endif
}

 krb5_error_code smb_krb5_mk_error(krb5_context context,
				krb5_error_code error_code,
				const krb5_principal server,
				krb5_data *reply)
{
#ifdef HAVE_SHORT_KRB5_MK_ERROR_INTERFACE /* MIT */
	/*
	 * The MIT interface is *terrible*.
	 * We have to construct this ourselves...
	 */
	krb5_error e;

	memset(&e, 0, sizeof(e));
	krb5_us_timeofday(context, &e.stime, &e.susec);
	e.server = server;
#if defined(krb5_err_base)
	e.error = error_code - krb5_err_base;
#elif defined(ERROR_TABLE_BASE_krb5)
	e.error = error_code - ERROR_TABLE_BASE_krb5;
#else
	e.error = error_code; /* Almost certainly wrong, but what can we do... ? */
#endif

	return krb5_mk_error(context, &e, reply);
#else /* Heimdal. */
	return krb5_mk_error(context,
				error_code,
				NULL,
				NULL, /* e_data */
				NULL,
				server,
				NULL,
				NULL,
				reply);
#endif
}

/**********************************************************************
 * Open a krb5 keytab with flags, handles readonly or readwrite access and
 * allows to process non-default keytab names.
 * @param context krb5_context 
 * @param keytab_name_req string
 * @param write_access bool if writable keytab is required
 * @param krb5_keytab pointer to krb5_keytab (close with krb5_kt_close())
 * @return krb5_error_code
**********************************************************************/

/* This MAX_NAME_LEN is a constant defined in krb5.h */
#ifndef MAX_KEYTAB_NAME_LEN
#define MAX_KEYTAB_NAME_LEN 1100
#endif

 krb5_error_code smb_krb5_open_keytab(krb5_context context,
				      const char *keytab_name_req,
				      bool write_access,
				      krb5_keytab *keytab)
{
	krb5_error_code ret = 0;
	TALLOC_CTX *mem_ctx;
	char keytab_string[MAX_KEYTAB_NAME_LEN];
	char *kt_str = NULL;
	bool found_valid_name = False;
	const char *pragma = "FILE";
	const char *tmp = NULL;

	if (!write_access && !keytab_name_req) {
		/* caller just wants to read the default keytab readonly, so be it */
		return krb5_kt_default(context, keytab);
	}

	mem_ctx = talloc_init("smb_krb5_open_keytab");
	if (!mem_ctx) {
		return ENOMEM;
	}

#ifdef HAVE_WRFILE_KEYTAB 
	if (write_access) {
		pragma = "WRFILE";
	}
#endif

	if (keytab_name_req) {

		if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
			ret = KRB5_CONFIG_NOTENUFSPACE;
			goto out;
		}

		if ((strncmp(keytab_name_req, "WRFILE:/", 8) == 0) || 
		    (strncmp(keytab_name_req, "FILE:/", 6) == 0)) {
		    	tmp = keytab_name_req;
			goto resolve;
		}

		if (keytab_name_req[0] != '/') {
			ret = KRB5_KT_BADNAME;
			goto out;
		}

		tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
		if (!tmp) {
			ret = ENOMEM;
			goto out;
		}

		goto resolve;
	}

	/* we need to handle more complex keytab_strings, like:
	 * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */

	ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
	if (ret) {
		goto out;
	}

	DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));

	tmp = talloc_strdup(mem_ctx, keytab_string);
	if (!tmp) {
		ret = ENOMEM;
		goto out;
	}

	if (strncmp(tmp, "ANY:", 4) == 0) {
		tmp += 4;
	}

	memset(&keytab_string, '\0', sizeof(keytab_string));

	while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
		if (strncmp(kt_str, "WRFILE:", 7) == 0) {
			found_valid_name = True;
			tmp = kt_str;
			tmp += 7;
		}

		if (strncmp(kt_str, "FILE:", 5) == 0) {
			found_valid_name = True;
			tmp = kt_str;
			tmp += 5;
		}

		if (tmp[0] == '/') {
			/* Treat as a FILE: keytab definition. */
			found_valid_name = true;
		}

		if (found_valid_name) {
			if (tmp[0] != '/') {
				ret = KRB5_KT_BADNAME;
				goto out;
			}

			tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
			if (!tmp) {
				ret = ENOMEM;
				goto out;
			}
			break;
		}
	}

	if (!found_valid_name) {
		ret = KRB5_KT_UNKNOWN_TYPE;
		goto out;
	}

 resolve:
 	DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
	ret = krb5_kt_resolve(context, tmp, keytab);

 out:
 	TALLOC_FREE(mem_ctx);
 	return ret;
}

krb5_error_code smb_krb5_keytab_name(TALLOC_CTX *mem_ctx,
				     krb5_context context,
				     krb5_keytab keytab,
				     const char **keytab_name)
{
	char keytab_string[MAX_KEYTAB_NAME_LEN];
	krb5_error_code ret = 0;

	ret = krb5_kt_get_name(context, keytab,
			       keytab_string, MAX_KEYTAB_NAME_LEN - 2);
	if (ret) {
		return ret;
	}

	*keytab_name = talloc_strdup(mem_ctx, keytab_string);
	if (!*keytab_name) {
		return ENOMEM;
	}

	return ret;
}

#if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
    defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
    defined(HAVE_KRB5_GET_CREDS)
static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
							     krb5_ccache ccache,
							     krb5_principal me,
							     krb5_principal server,
							     krb5_principal impersonate_princ,
							     krb5_creds **out_creds)
{
	krb5_error_code ret;
	krb5_get_creds_opt opt;

	ret = krb5_get_creds_opt_alloc(context, &opt);
	if (ret) {
		goto done;
	}
	krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);

	if (impersonate_princ) {
		ret = krb5_get_creds_opt_set_impersonate(context, opt,
							 impersonate_princ);
		if (ret) {
			goto done;
		}
	}

	ret = krb5_get_creds(context, opt, ccache, server, out_creds);
	if (ret) {
		goto done;
	}

 done:
	if (opt) {
		krb5_get_creds_opt_free(context, opt);
	}
	return ret;
}
#endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */

#ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
							 krb5_ccache ccache,
							 krb5_principal me,
							 krb5_principal server,
							 krb5_principal impersonate_princ,
							 krb5_creds **out_creds)
{
	krb5_error_code ret;
	krb5_creds in_creds;

#if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
krb5_error_code KRB5_CALLCONV
krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
                              krb5_ccache ccache, krb5_creds *in_creds,
                              krb5_data *subject_cert,
                              krb5_creds **out_creds);
#endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */

	ZERO_STRUCT(in_creds);

	if (impersonate_princ) {

		in_creds.server = me;
		in_creds.client = impersonate_princ;

		ret = krb5_get_credentials_for_user(context,
						    0, /* krb5_flags options */
						    ccache,
						    &in_creds,
						    NULL, /* krb5_data *subject_cert */
						    out_creds);
	} else {
		in_creds.client = me;
		in_creds.server = server;

		ret = krb5_get_credentials(context, 0, ccache,
					   &in_creds, out_creds);
	}

	return ret;
}
#endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */

/*
 * smb_krb5_get_credentials
 *
 * @brief Get krb5 credentials for a server
 *
 * @param[in] context		An initialized krb5_context
 * @param[in] ccache		An initialized krb5_ccache
 * @param[in] me		The krb5_principal of the caller
 * @param[in] server		The krb5_principal of the requested service
 * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
 * @param[out] out_creds	The returned krb5_creds structure
 * @return krb5_error_code
 *
 */
krb5_error_code smb_krb5_get_credentials(krb5_context context,
					 krb5_ccache ccache,
					 krb5_principal me,
					 krb5_principal server,
					 krb5_principal impersonate_princ,
					 krb5_creds **out_creds)
{
	krb5_error_code ret;
	krb5_creds *creds = NULL;

	*out_creds = NULL;

	if (impersonate_princ) {
#ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
		ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
#elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
		ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
#else
		ret = ENOTSUP;
#endif
	} else {
		krb5_creds in_creds;

		ZERO_STRUCT(in_creds);

		in_creds.client = me;
		in_creds.server = server;

		ret = krb5_get_credentials(context, 0, ccache,
					   &in_creds, &creds);
	}
	if (ret) {
		goto done;
	}

	ret = krb5_cc_store_cred(context, ccache, creds);
	if (ret) {
		goto done;
	}

	if (out_creds) {
		*out_creds = creds;
	}

 done:
	if (creds && ret) {
		krb5_free_creds(context, creds);
	}

	return ret;
}

/*
 * smb_krb5_get_creds
 *
 * @brief Get krb5 credentials for a server
 *
 * @param[in] server_s		The string name of the service
 * @param[in] time_offset	The offset to the KDCs time in seconds (optional)
 * @param[in] cc		The krb5 credential cache string name (optional)
 * @param[in] impersonate_princ_s The string principal name to impersonate (optional)
 * @param[out] creds_p		The returned krb5_creds structure
 * @return krb5_error_code
 *
 */
krb5_error_code smb_krb5_get_creds(const char *server_s,
				   time_t time_offset,
				   const char *cc,
				   const char *impersonate_princ_s,
				   krb5_creds **creds_p)
{
	krb5_error_code ret;
	krb5_context context = NULL;
	krb5_principal me = NULL;
	krb5_principal server = NULL;
	krb5_principal impersonate_princ = NULL;
	krb5_creds *creds = NULL;
	krb5_ccache ccache = NULL;

	*creds_p = NULL;

	initialize_krb5_error_table();
	ret = krb5_init_context(&context);
	if (ret) {
		goto done;
	}

	if (time_offset != 0) {
		krb5_set_real_time(context, time(NULL) + time_offset, 0);
	}

	ret = krb5_cc_resolve(context, cc ? cc :
		krb5_cc_default_name(context), &ccache);
	if (ret) {
		goto done;
	}

	ret = krb5_cc_get_principal(context, ccache, &me);
	if (ret) {
		goto done;
	}

	ret = smb_krb5_parse_name(context, server_s, &server);
	if (ret) {
		goto done;
	}

	if (impersonate_princ_s) {
		ret = smb_krb5_parse_name(context, impersonate_princ_s,
					  &impersonate_princ);
		if (ret) {
			goto done;
		}
	}

	ret = smb_krb5_get_credentials(context, ccache,
				       me, server, impersonate_princ,
				       &creds);
	if (ret) {
		goto done;
	}

	ret = krb5_cc_store_cred(context, ccache, creds);
	if (ret) {
		goto done;
	}

	if (creds_p) {
		*creds_p = creds;
	}

	DEBUG(1,("smb_krb5_get_creds: got ticket for %s\n",
		server_s));

	if (impersonate_princ_s) {
		char *client = NULL;

		ret = smb_krb5_unparse_name(talloc_tos(), context, creds->client, &client);
		if (ret) {
			goto done;
		}
		DEBUGADD(1,("smb_krb5_get_creds: using S4U2SELF impersonation as %s\n",
			client));
		TALLOC_FREE(client);
	}

 done:
	if (!context) {
		return ret;
	}

	if (creds && ret) {
		krb5_free_creds(context, creds);
	}
	if (server) {
		krb5_free_principal(context, server);
	}
	if (me) {
		krb5_free_principal(context, me);
	}
	if (impersonate_princ) {
		krb5_free_principal(context, impersonate_princ);
	}
	if (ccache) {
		krb5_cc_close(context, ccache);
	}
	krb5_free_context(context);

	return ret;
}

/*
 * smb_krb5_principal_get_realm
 *
 * @brief Get realm of a principal
 *
 * @param[in] context		The krb5_context
 * @param[in] principal		The principal
 * @return pointer to the realm
 *
 */

char *smb_krb5_principal_get_realm(krb5_context context,
				   krb5_principal principal)
{
#ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
	return krb5_principal_get_realm(context, principal);
#elif defined(krb5_princ_realm) /* MIT */
	krb5_data *realm;
	realm = krb5_princ_realm(context, principal);
	return (char *)realm->data;
#else
	return NULL;
#endif
}

#else /* HAVE_KRB5 */
 /* this saves a few linking headaches */
 int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
			const char *principal, time_t time_offset,
			DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
			uint32_t extra_ap_opts,
			const char *ccname, time_t *tgs_expire,
			const char *impersonate_princ_s)
{
	 DEBUG(0,("NO KERBEROS SUPPORT\n"));
	 return 1;
}

#endif