Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*	$NetBSD: spnego.c,v 1.3 2019/01/09 16:55:12 christos Exp $	*/

/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
 */

#include <config.h>

/*! \file
 * \brief
 * Portable SPNEGO implementation.
 *
 * This is part of a portable implementation of the SPNEGO protocol
 * (RFCs 2478 and 4178).  This implementation uses the RFC 4178 ASN.1
 * module but is not a full implementation of the RFC 4178 protocol;
 * at the moment, we only support GSS-TSIG with Kerberos
 * authentication, so we only need enough of the SPNEGO protocol to
 * support that.
 *
 * The files that make up this portable SPNEGO implementation are:
 * \li	spnego.c	(this file)
 * \li	spnego.h	(API SPNEGO exports to the rest of lib/dns)
 * \li	spnego.asn1	(SPNEGO ASN.1 module)
 * \li	spnego_asn1.c	(routines generated from spngo.asn1)
 * \li	spnego_asn1.pl	(perl script to generate spnego_asn1.c)
 *
 * Everything but the functions exported in spnego.h is static, to
 * avoid possible conflicts with other libraries (particularly Heimdal,
 * since much of this code comes from Heimdal by way of mod_auth_kerb).
 *
 * spnego_asn1.c is shipped as part of lib/dns because generating it
 * requires both Perl and the Heimdal ASN.1 compiler.  See
 * spnego_asn1.pl for further details.  We've tried to eliminate all
 * compiler warnings from the generated code, but you may see a few
 * when using a compiler version we haven't tested yet.
 */

/*
 * Portions of this code were derived from mod_auth_kerb and Heimdal.
 * These packages are available from:
 *
 *   http://modauthkerb.sourceforge.net/
 *   http://www.pdc.kth.se/heimdal/
 *
 * and were released under the following licenses:
 *
 * ----------------------------------------------------------------
 *
 * Copyright (c) 2004 Masarykova universita
 * (Masaryk University, Brno, Czech Republic)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * ----------------------------------------------------------------
 *
 * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * XXXSRA We should omit this file entirely in Makefile.in via autoconf,
 * but this will keep it from generating errors until that's written.
 */

#ifdef GSSAPI

/*
 * XXXSRA Some of the following files are almost certainly unnecessary,
 * but using this list (borrowed from gssapictx.c) gets rid of some
 * whacky compilation errors when building with MSVC and should be
 * harmless in any case.
 */

#include <inttypes.h>
#include <stdbool.h>
#include <stdlib.h>
#include <errno.h>

#include <isc/buffer.h>
#include <isc/dir.h>
#include <isc/lex.h>
#include <isc/mem.h>
#include <isc/once.h>
#include <isc/random.h>
#include <isc/safe.h>
#include <isc/string.h>
#include <isc/time.h>
#include <isc/util.h>

#include <dns/fixedname.h>
#include <dns/name.h>
#include <dns/rdata.h>
#include <dns/rdataclass.h>
#include <dns/result.h>
#include <dns/types.h>
#include <dns/keyvalues.h>
#include <dns/log.h>

#include <dst/gssapi.h>
#include <dst/result.h>

#include "dst_internal.h"

/*
 * The API we export
 */
#include "spnego.h"

/* asn1_err.h */
/* Generated from ../../../lib/asn1/asn1_err.et */

#ifndef ERROR_TABLE_BASE_asn1
/* these may be brought in already via gssapi_krb5.h */
typedef enum asn1_error_number {
	ASN1_BAD_TIMEFORMAT = 1859794432,
	ASN1_MISSING_FIELD = 1859794433,
	ASN1_MISPLACED_FIELD = 1859794434,
	ASN1_TYPE_MISMATCH = 1859794435,
	ASN1_OVERFLOW = 1859794436,
	ASN1_OVERRUN = 1859794437,
	ASN1_BAD_ID = 1859794438,
	ASN1_BAD_LENGTH = 1859794439,
	ASN1_BAD_FORMAT = 1859794440,
	ASN1_PARSE_ERROR = 1859794441
} asn1_error_number;

#define ERROR_TABLE_BASE_asn1 1859794432
#endif

#define __asn1_common_definitions__

typedef struct octet_string {
	size_t length;
	void *data;
} octet_string;

typedef char *general_string;

typedef char *utf8_string;

typedef struct oid {
	size_t length;
	unsigned *components;
} oid;

/* der.h */

typedef enum {
	ASN1_C_UNIV = 0, ASN1_C_APPL = 1,
	ASN1_C_CONTEXT = 2, ASN1_C_PRIVATE = 3
} Der_class;

typedef enum {
	PRIM = 0, CONS = 1
} Der_type;

/* Universal tags */

enum {
	UT_Boolean = 1,
	UT_Integer = 2,
	UT_BitString = 3,
	UT_OctetString = 4,
	UT_Null = 5,
	UT_OID = 6,
	UT_Enumerated = 10,
	UT_Sequence = 16,
	UT_Set = 17,
	UT_PrintableString = 19,
	UT_IA5String = 22,
	UT_UTCTime = 23,
	UT_GeneralizedTime = 24,
	UT_VisibleString = 26,
	UT_GeneralString = 27
};

#define ASN1_INDEFINITE 0xdce0deed

static int
der_get_length(const unsigned char *p, size_t len,
	       size_t * val, size_t * size);

static int
der_get_octet_string(const unsigned char *p, size_t len,
		     octet_string * data, size_t * size);
static int
der_get_oid(const unsigned char *p, size_t len,
	    oid * data, size_t * size);
static int
der_get_tag(const unsigned char *p, size_t len,
	    Der_class * xclass, Der_type * type,
	    int *tag, size_t * size);

static int
der_match_tag(const unsigned char *p, size_t len,
	      Der_class xclass, Der_type type,
	      int tag, size_t * size);
static int
der_match_tag_and_length(const unsigned char *p, size_t len,
			 Der_class xclass, Der_type type, int tag,
			 size_t * length_ret, size_t * size);

static int
decode_oid(const unsigned char *p, size_t len,
	   oid * k, size_t * size);

static int
decode_enumerated(const unsigned char *p, size_t len, void *num, size_t *size);

static int
decode_octet_string(const unsigned char *, size_t, octet_string *, size_t *);

static int
der_put_int(unsigned char *p, size_t len, int val, size_t *);

static int
der_put_length(unsigned char *p, size_t len, size_t val, size_t *);

static int
der_put_octet_string(unsigned char *p, size_t len,
		     const octet_string * data, size_t *);
static int
der_put_oid(unsigned char *p, size_t len,
	    const oid * data, size_t * size);
static int
der_put_tag(unsigned char *p, size_t len, Der_class xclass, Der_type type,
	    int tag, size_t *);
static int
der_put_length_and_tag(unsigned char *, size_t, size_t,
		       Der_class, Der_type, int, size_t *);

static int
encode_enumerated(unsigned char *p, size_t len, const void *data, size_t *);

static int
encode_octet_string(unsigned char *p, size_t len,
		    const octet_string * k, size_t *);
static int
encode_oid(unsigned char *p, size_t len,
	   const oid * k, size_t *);

static void
free_octet_string(octet_string * k);

static void
free_oid  (oid * k);

static size_t
length_len(size_t len);

static int
fix_dce(size_t reallen, size_t * len);

/*
 * Include stuff generated by the ASN.1 compiler.
 */

#include "spnego_asn1.c"

/*
 * Force the oid arrays to be uint64_t aligned to silence warnings
 * about the arrays not being properly aligned for (void *).
 */
typedef union { unsigned char b[8]; uint64_t _align; } aligned8;
typedef union { unsigned char b[16]; uint64_t _align[2]; } aligned16;

static aligned16 gss_krb5_mech_oid_bytes = {
	{ 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02 }
};

static gss_OID_desc gss_krb5_mech_oid_desc = {
	9, gss_krb5_mech_oid_bytes.b
};

static gss_OID GSS_KRB5_MECH = &gss_krb5_mech_oid_desc;

static aligned16 gss_mskrb5_mech_oid_bytes = {
	{ 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02 }
};

static gss_OID_desc gss_mskrb5_mech_oid_desc = {
	9, gss_mskrb5_mech_oid_bytes.b
};

static gss_OID GSS_MSKRB5_MECH = &gss_mskrb5_mech_oid_desc;

static aligned8 gss_spnego_mech_oid_bytes = {
	{ 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02 }
};

static gss_OID_desc gss_spnego_mech_oid_desc = {
	6, gss_spnego_mech_oid_bytes.b
};

static gss_OID GSS_SPNEGO_MECH = &gss_spnego_mech_oid_desc;

/* spnegokrb5_locl.h */

static OM_uint32
gssapi_spnego_encapsulate(OM_uint32 *,
			  unsigned char *,
			  size_t,
			  gss_buffer_t,
			  const gss_OID);

static OM_uint32
gssapi_spnego_decapsulate(OM_uint32 *,
			  gss_buffer_t,
			  unsigned char **,
			  size_t *,
			  const gss_OID);

/* mod_auth_kerb.c */

static bool
cmp_gss_type(gss_buffer_t token, gss_OID gssoid)
{
	unsigned char *p;
	size_t len;

	if (token->length == 0U)
		return (GSS_S_DEFECTIVE_TOKEN);

	p = token->value;
	if (*p++ != 0x60)
		return (GSS_S_DEFECTIVE_TOKEN);
	len = *p++;
	if (len & 0x80) {
		if ((len & 0x7f) > 4U)
			return (GSS_S_DEFECTIVE_TOKEN);
		p += len & 0x7f;
	}
	if (*p++ != 0x06)
		return (GSS_S_DEFECTIVE_TOKEN);

	if (((OM_uint32) *p++) != gssoid->length)
		return (GSS_S_DEFECTIVE_TOKEN);

	return (!isc_safe_memequal(p, gssoid->elements, gssoid->length));
}

/* accept_sec_context.c */
/*
 * SPNEGO wrapper for Kerberos5 GSS-API kouril@ics.muni.cz, 2003 (mostly
 * based on Heimdal code)
 */

static OM_uint32
code_NegTokenArg(OM_uint32 * minor_status,
		 const NegTokenResp * resp,
		 unsigned char **outbuf,
		 size_t * outbuf_size)
{
	OM_uint32 ret;
	u_char *buf;
	size_t buf_size, buf_len = 0;

	buf_size = 1024;
	buf = malloc(buf_size);
	if (buf == NULL) {
		*minor_status = ENOMEM;
		return (GSS_S_FAILURE);
	}
	do {
		ret = encode_NegTokenResp(buf + buf_size - 1,
					  buf_size,
					  resp, &buf_len);
		if (ret == 0) {
			size_t tmp;

			ret = der_put_length_and_tag(buf + buf_size - buf_len - 1,
						     buf_size - buf_len,
						     buf_len,
						     ASN1_C_CONTEXT,
						     CONS,
						     1,
						     &tmp);
			if (ret == 0)
				buf_len += tmp;
		}
		if (ret) {
			if (ret == ASN1_OVERFLOW) {
				u_char *tmp;

				buf_size *= 2;
				tmp = realloc(buf, buf_size);
				if (tmp == NULL) {
					*minor_status = ENOMEM;
					free(buf);
					return (GSS_S_FAILURE);
				}
				buf = tmp;
			} else {
				*minor_status = ret;
				free(buf);
				return (GSS_S_FAILURE);
			}
		}
	} while (ret == ASN1_OVERFLOW);

	*outbuf = malloc(buf_len);
	if (*outbuf == NULL) {
		*minor_status = ENOMEM;
		free(buf);
		return (GSS_S_FAILURE);
	}
	memmove(*outbuf, buf + buf_size - buf_len, buf_len);
	*outbuf_size = buf_len;

	free(buf);

	return (GSS_S_COMPLETE);
}

static OM_uint32
send_reject(OM_uint32 * minor_status,
	    gss_buffer_t output_token)
{
	NegTokenResp resp;
	OM_uint32 ret;

	resp.negState = malloc(sizeof(*resp.negState));
	if (resp.negState == NULL) {
		*minor_status = ENOMEM;
		return (GSS_S_FAILURE);
	}
	*(resp.negState) = reject;

	resp.supportedMech = NULL;
	resp.responseToken = NULL;
	resp.mechListMIC = NULL;

	ret = code_NegTokenArg(minor_status, &resp,
			       (unsigned char **)&output_token->value,
			       &output_token->length);
	free_NegTokenResp(&resp);
	if (ret)
		return (ret);

	return (GSS_S_BAD_MECH);
}

static OM_uint32
send_accept(OM_uint32 * minor_status,
	    gss_buffer_t output_token,
	    gss_buffer_t mech_token,
	    const gss_OID pref)
{
	NegTokenResp resp;
	OM_uint32 ret;

	memset(&resp, 0, sizeof(resp));
	resp.negState = malloc(sizeof(*resp.negState));
	if (resp.negState == NULL) {
		*minor_status = ENOMEM;
		return (GSS_S_FAILURE);
	}
	*(resp.negState) = accept_completed;

	resp.supportedMech = malloc(sizeof(*resp.supportedMech));
	if (resp.supportedMech == NULL) {
		free_NegTokenResp(&resp);
		*minor_status = ENOMEM;
		return (GSS_S_FAILURE);
	}
	ret = der_get_oid(pref->elements,
			  pref->length,
			  resp.supportedMech,
			  NULL);
	if (ret) {
		free_NegTokenResp(&resp);
		*minor_status = ENOMEM;
		return (GSS_S_FAILURE);
	}
	if (mech_token != NULL && mech_token->length != 0U) {
		resp.responseToken = malloc(sizeof(*resp.responseToken));
		if (resp.responseToken == NULL) {
			free_NegTokenResp(&resp);
			*minor_status = ENOMEM;
			return (GSS_S_FAILURE);
		}
		resp.responseToken->length = mech_token->length;
		resp.responseToken->data = mech_token->value;
	}

	ret = code_NegTokenArg(minor_status, &resp,
			       (unsigned char **)&output_token->value,
			       &output_token->length);
	if (resp.responseToken != NULL) {
		free(resp.responseToken);
		resp.responseToken = NULL;
	}
	free_NegTokenResp(&resp);
	if (ret)
		return (ret);

	return (GSS_S_COMPLETE);
}

OM_uint32
gss_accept_sec_context_spnego(OM_uint32 *minor_status,
			      gss_ctx_id_t *context_handle,
			      const gss_cred_id_t acceptor_cred_handle,
			      const gss_buffer_t input_token_buffer,
			      const gss_channel_bindings_t input_chan_bindings,
			      gss_name_t *src_name,
			      gss_OID *mech_type,
			      gss_buffer_t output_token,
			      OM_uint32 *ret_flags,
			      OM_uint32 *time_rec,
			      gss_cred_id_t *delegated_cred_handle)
{
	NegTokenInit init_token;
	OM_uint32 major_status = GSS_S_COMPLETE;
	OM_uint32 minor_status2;
	gss_buffer_desc ibuf, obuf;
	gss_buffer_t ot = NULL;
	gss_OID pref = GSS_KRB5_MECH;
	unsigned char *buf;
	size_t buf_size;
	size_t len, taglen, ni_len;
	int found = 0;
	int ret;
	unsigned i;

	/*
	 * Before doing anything else, see whether this is a SPNEGO
	 * PDU.  If not, dispatch to the GSSAPI library and get out.
	 */

	if (cmp_gss_type(input_token_buffer, GSS_SPNEGO_MECH))
		return (gss_accept_sec_context(minor_status,
					       context_handle,
					       acceptor_cred_handle,
					       input_token_buffer,
					       input_chan_bindings,
					       src_name,
					       mech_type,
					       output_token,
					       ret_flags,
					       time_rec,
					       delegated_cred_handle));

	/*
	 * If we get here, it's SPNEGO.
	 */

	memset(&init_token, 0, sizeof(init_token));

	ret = gssapi_spnego_decapsulate(minor_status, input_token_buffer,
					&buf, &buf_size, GSS_SPNEGO_MECH);
	if (ret)
		return (ret);

	ret = der_match_tag_and_length(buf, buf_size, ASN1_C_CONTEXT, CONS,
				       0, &len, &taglen);
	if (ret)
		return (ret);

	ret = decode_NegTokenInit(buf + taglen, len, &init_token, &ni_len);
	if (ret) {
		*minor_status = EINVAL;	/* XXX */
		return (GSS_S_DEFECTIVE_TOKEN);
	}

	for (i = 0; !found && i < init_token.mechTypes.len; ++i) {
		unsigned char mechbuf[17];
		size_t mech_len;

		ret = der_put_oid(mechbuf + sizeof(mechbuf) - 1,
				  sizeof(mechbuf),
				  &init_token.mechTypes.val[i],
				  &mech_len);
		if (ret) {
			free_NegTokenInit(&init_token);
			return (GSS_S_DEFECTIVE_TOKEN);
		}
		if (mech_len == GSS_KRB5_MECH->length &&
		    isc_safe_memequal(GSS_KRB5_MECH->elements,
				      mechbuf + sizeof(mechbuf) - mech_len,
				      mech_len))
		{
			found = 1;
			break;
		}
		if (mech_len == GSS_MSKRB5_MECH->length &&
		    isc_safe_memequal(GSS_MSKRB5_MECH->elements,
				      mechbuf + sizeof(mechbuf) - mech_len,
				      mech_len))
		{
			found = 1;
			if (i == 0)
				pref = GSS_MSKRB5_MECH;
			break;
		}
	}

	if (!found) {
		free_NegTokenInit(&init_token);
		return (send_reject(minor_status, output_token));
	}

	if (i == 0 && init_token.mechToken != NULL) {
		ibuf.length = init_token.mechToken->length;
		ibuf.value = init_token.mechToken->data;

		major_status = gss_accept_sec_context(minor_status,
						      context_handle,
						      acceptor_cred_handle,
						      &ibuf,
						      input_chan_bindings,
						      src_name,
						      mech_type,
						      &obuf,
						      ret_flags,
						      time_rec,
						      delegated_cred_handle);
		if (GSS_ERROR(major_status)) {
			free_NegTokenInit(&init_token);
			send_reject(&minor_status2, output_token);
			return (major_status);
		}
		ot = &obuf;
	}
	ret = send_accept(&minor_status2, output_token, ot, pref);
	free_NegTokenInit(&init_token);
	if (ot != NULL && ot->length != 0U)
		gss_release_buffer(&minor_status2, ot);

	return (ret != GSS_S_COMPLETE ? (OM_uint32) ret : major_status);
}

/* decapsulate.c */

static OM_uint32
gssapi_verify_mech_header(u_char ** str,
			  size_t total_len,
			  const gss_OID mech)
{
	size_t len, len_len, mech_len, foo;
	int e;
	u_char *p = *str;

	if (total_len < 1U)
		return (GSS_S_DEFECTIVE_TOKEN);
	if (*p++ != 0x60)
		return (GSS_S_DEFECTIVE_TOKEN);
	e = der_get_length(p, total_len - 1, &len, &len_len);
	if (e || 1 + len_len + len != total_len)
		return (GSS_S_DEFECTIVE_TOKEN);
	p += len_len;
	if (*p++ != 0x06)
		return (GSS_S_DEFECTIVE_TOKEN);
	e = der_get_length(p, total_len - 1 - len_len - 1,
			   &mech_len, &foo);
	if (e)
		return (GSS_S_DEFECTIVE_TOKEN);
	p += foo;
	if (mech_len != mech->length)
		return (GSS_S_BAD_MECH);
	if (!isc_safe_memequal(p, mech->elements, mech->length))
		return (GSS_S_BAD_MECH);
	p += mech_len;
	*str = p;
	return (GSS_S_COMPLETE);
}

/*
 * Remove the GSS-API wrapping from `in_token' giving `buf and buf_size' Does
 * not copy data, so just free `in_token'.
 */

static OM_uint32
gssapi_spnego_decapsulate(OM_uint32 *minor_status,
			  gss_buffer_t input_token_buffer,
			  unsigned char **buf,
			  size_t *buf_len,
			  const gss_OID mech)
{
	u_char *p;
	OM_uint32 ret;

	p = input_token_buffer->value;
	ret = gssapi_verify_mech_header(&p,
					input_token_buffer->length,
					mech);
	if (ret) {
		*minor_status = ret;
		return (GSS_S_FAILURE);
	}
	*buf_len = input_token_buffer->length -
		(p - (u_char *) input_token_buffer->value);
	*buf = p;
	return (GSS_S_COMPLETE);
}

/* der_free.c */

static void
free_octet_string(octet_string *k)
{
	free(k->data);
	k->data = NULL;
}

static void
free_oid(oid *k)
{
	free(k->components);
	k->components = NULL;
}

/* der_get.c */

/*
 * All decoding functions take a pointer `p' to first position in which to
 * read, from the left, `len' which means the maximum number of characters we
 * are able to read, `ret' were the value will be returned and `size' where
 * the number of used bytes is stored. Either 0 or an error code is returned.
 */

static int
der_get_unsigned(const unsigned char *p, size_t len,
		 unsigned *ret, size_t *size)
{
	unsigned val = 0;
	size_t oldlen = len;

	while (len--)
		val = val * 256 + *p++;
	*ret = val;
	if (size)
		*size = oldlen;
	return (0);
}

static int
der_get_int(const unsigned char *p, size_t len,
	    int *ret, size_t *size)
{
	int val = 0;
	size_t oldlen = len;

	if (len > 0U) {
		val = (signed char)*p++;
		while (--len)
			val = val * 256 + *p++;
	}
	*ret = val;
	if (size)
		*size = oldlen;
	return (0);
}

static int
der_get_length(const unsigned char *p, size_t len,
	       size_t *val, size_t *size)
{
	size_t v;

	if (len <= 0U)
		return (ASN1_OVERRUN);
	--len;
	v = *p++;
	if (v < 128U) {
		*val = v;
		if (size)
			*size = 1;
	} else {
		int e;
		size_t l;
		unsigned tmp;

		if (v == 0x80U) {
			*val = ASN1_INDEFINITE;
			if (size)
				*size = 1;
			return (0);
		}
		v &= 0x7F;
		if (len < v)
			return (ASN1_OVERRUN);
		e = der_get_unsigned(p, v, &tmp, &l);
		if (e)
			return (e);
		*val = tmp;
		if (size)
			*size = l + 1;
	}
	return (0);
}

static int
der_get_octet_string(const unsigned char *p, size_t len,
		     octet_string *data, size_t *size)
{
	data->length = len;
	if (len != 0U) {
		data->data = malloc(len);
		if (data->data == NULL)
			return (ENOMEM);
		memmove(data->data, p, len);
	} else
		data->data = NULL;
	if (size)
		*size = len;
	return (0);
}

static int
der_get_oid(const unsigned char *p, size_t len, oid *data, size_t *size) {
	int n;
	size_t oldlen = len;

	data->components = NULL;
	data->length = 0;
	if (len < 1U) {
		return (ASN1_OVERRUN);
	}

	data->components = malloc(len * sizeof(*data->components));
	if (data->components == NULL) {
		return (ENOMEM);
	}
	data->components[0] = (*p) / 40;
	data->components[1] = (*p) % 40;
	--len;
	++p;
	for (n = 2; len > 0U; ++n) {
		unsigned u = 0;

		do {
			--len;
			u = u * 128 + (*p++ % 128);
		} while (len > 0U && p[-1] & 0x80);
		data->components[n] = u;
	}
	if (p[-1] & 0x80) {
		free_oid(data);
		return (ASN1_OVERRUN);
	}
	data->length = n;
	if (size) {
		*size = oldlen;
	}
	return (0);
}

static int
der_get_tag(const unsigned char *p, size_t len,
	    Der_class *xclass, Der_type *type,
	    int *tag, size_t *size)
{
	if (len < 1U)
		return (ASN1_OVERRUN);
	*xclass = (Der_class) (((*p) >> 6) & 0x03);
	*type = (Der_type) (((*p) >> 5) & 0x01);
	*tag = (*p) & 0x1F;
	if (size)
		*size = 1;
	return (0);
}

static int
der_match_tag(const unsigned char *p, size_t len,
	      Der_class xclass, Der_type type,
	      int tag, size_t *size)
{
	size_t l;
	Der_class thisclass;
	Der_type thistype;
	int thistag;
	int e;

	e = der_get_tag(p, len, &thisclass, &thistype, &thistag, &l);
	if (e)
		return (e);
	if (xclass != thisclass || type != thistype)
		return (ASN1_BAD_ID);
	if (tag > thistag)
		return (ASN1_MISPLACED_FIELD);
	if (tag < thistag)
		return (ASN1_MISSING_FIELD);
	if (size)
		*size = l;
	return (0);
}

static int
der_match_tag_and_length(const unsigned char *p, size_t len,
			 Der_class xclass, Der_type type, int tag,
			 size_t *length_ret, size_t *size)
{
	size_t l, ret = 0;
	int e;

	e = der_match_tag(p, len, xclass, type, tag, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	ret += l;
	e = der_get_length(p, len, length_ret, &l);
	if (e)
		return (e);
	/* p += l; */
	len -= l;
	POST(len);
	ret += l;
	if (size)
		*size = ret;
	return (0);
}

static int
decode_enumerated(const unsigned char *p, size_t len, void *num, size_t *size)
{
	size_t ret = 0;
	size_t l, reallen;
	int e;

	e = der_match_tag(p, len, ASN1_C_UNIV, PRIM, UT_Enumerated, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	ret += l;
	e = der_get_length(p, len, &reallen, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	ret += l;
	e = der_get_int(p, reallen, num, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	POST(p); POST(len);
	ret += l;
	if (size)
		*size = ret;
	return (0);
}

static int
decode_octet_string(const unsigned char *p, size_t len,
		    octet_string *k, size_t *size)
{
	size_t ret = 0;
	size_t l;
	int e;
	size_t slen;

	k->data = NULL;
	k->length = 0;

	e = der_match_tag(p, len, ASN1_C_UNIV, PRIM, UT_OctetString, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	ret += l;

	e = der_get_length(p, len, &slen, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	ret += l;
	if (len < slen)
		return (ASN1_OVERRUN);

	e = der_get_octet_string(p, slen, k, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	POST(p); POST(len);
	ret += l;
	if (size)
		*size = ret;
	return (0);
}

static int
decode_oid(const unsigned char *p, size_t len,
	   oid *k, size_t *size)
{
	size_t ret = 0;
	size_t l;
	int e;
	size_t slen;

	e = der_match_tag(p, len, ASN1_C_UNIV, PRIM, UT_OID, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	ret += l;

	e = der_get_length(p, len, &slen, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	ret += l;
	if (len < slen)
		return (ASN1_OVERRUN);

	e = der_get_oid(p, slen, k, &l);
	if (e)
		return (e);
	p += l;
	len -= l;
	POST(p); POST(len);
	ret += l;
	if (size)
		*size = ret;
	return (0);
}

static int
fix_dce(size_t reallen, size_t *len)
{
	if (reallen == ASN1_INDEFINITE)
		return (1);
	if (*len < reallen)
		return (-1);
	*len = reallen;
	return (0);
}

/* der_length.c */

static size_t
len_unsigned(unsigned val)
{
	size_t ret = 0;

	do {
		++ret;
		val /= 256;
	} while (val);
	return (ret);
}

static size_t
length_len(size_t len)
{
	if (len < 128U)
		return (1);
	else
		return (len_unsigned((unsigned int)len) + 1);
}


/* der_put.c */

/*
 * All encoding functions take a pointer `p' to first position in which to
 * write, from the right, `len' which means the maximum number of characters
 * we are able to write.  The function returns the number of characters
 * written in `size' (if non-NULL). The return value is 0 or an error.
 */

static int
der_put_unsigned(unsigned char *p, size_t len, unsigned val, size_t *size)
{
	unsigned char *base = p;

	if (val) {
		while (len > 0U && val) {
			*p-- = val % 256;
			val /= 256;
			--len;
		}
		if (val != 0)
			return (ASN1_OVERFLOW);
		else {
			*size = base - p;
			return (0);
		}
	} else if (len < 1U)
		return (ASN1_OVERFLOW);
	else {
		*p = 0;
		*size = 1;
		return (0);
	}
}

static int
der_put_int(unsigned char *p, size_t len, int val, size_t *size)
{
	unsigned char *base = p;

	if (val >= 0) {
		do {
			if (len < 1U)
				return (ASN1_OVERFLOW);
			*p-- = val % 256;
			len--;
			val /= 256;
		} while (val);
		if (p[1] >= 128) {
			if (len < 1U)
				return (ASN1_OVERFLOW);
			*p-- = 0;
			len--;
			POST(len);
		}
	} else {
		val = ~val;
		do {
			if (len < 1U)
				return (ASN1_OVERFLOW);
			*p-- = ~(val % 256);
			len--;
			val /= 256;
		} while (val);
		if (p[1] < 128) {
			if (len < 1U)
				return (ASN1_OVERFLOW);
			*p-- = 0xff;
			len--;
			POST(len);
		}
	}
	*size = base - p;
	return (0);
}

static int
der_put_length(unsigned char *p, size_t len, size_t val, size_t *size)
{
	if (len < 1U)
		return (ASN1_OVERFLOW);
	if (val < 128U) {
		*p = (unsigned char)val;
		*size = 1;
		return (0);
	} else {
		size_t l;
		int e;

		e = der_put_unsigned(p, len - 1, (unsigned int)val, &l);
		if (e)
			return (e);
		p -= l;
		*p = 0x80 | (unsigned char)l;
		*size = l + 1;
		return (0);
	}
}

static int
der_put_octet_string(unsigned char *p, size_t len,
		     const octet_string *data, size_t *size)
{
	if (len < data->length)
		return (ASN1_OVERFLOW);
	p -= data->length;
	len -= data->length;
	POST(len);
	memmove(p + 1, data->data, data->length);
	*size = data->length;
	return (0);
}

static int
der_put_oid(unsigned char *p, size_t len,
	    const oid *data, size_t *size)
{
	unsigned char *base = p;
	size_t n;

	for (n = data->length; n >= 3u; --n) {
		unsigned	u = data->components[n - 1];

		if (len < 1U)
			return (ASN1_OVERFLOW);
		*p-- = u % 128;
		u /= 128;
		--len;
		while (u > 0) {
			if (len < 1U)
				return (ASN1_OVERFLOW);
			*p-- = 128 + u % 128;
			u /= 128;
			--len;
		}
	}
	if (len < 1U)
		return (ASN1_OVERFLOW);
	*p-- = 40 * data->components[0] + data->components[1];
	*size = base - p;
	return (0);
}

static int
der_put_tag(unsigned char *p, size_t len, Der_class xclass, Der_type type,
	    int tag, size_t *size)
{
	if (len < 1U)
		return (ASN1_OVERFLOW);
	*p = (xclass << 6) | (type << 5) | tag;	/* XXX */
	*size = 1;
	return (0);
}

static int
der_put_length_and_tag(unsigned char *p, size_t len, size_t len_val,
		       Der_class xclass, Der_type type, int tag, size_t *size)
{
	size_t ret = 0;
	size_t l;
	int e;

	e = der_put_length(p, len, len_val, &l);
	if (e)
		return (e);
	p -= l;
	len -= l;
	ret += l;
	e = der_put_tag(p, len, xclass, type, tag, &l);
	if (e)
		return (e);
	p -= l;
	len -= l;
	POST(p); POST(len);
	ret += l;
	*size = ret;
	return (0);
}

static int
encode_enumerated(unsigned char *p, size_t len, const void *data, size_t *size)
{
	unsigned num = *(const unsigned *)data;
	size_t ret = 0;
	size_t l;
	int e;

	e = der_put_int(p, len, num, &l);
	if (e)
		return (e);
	p -= l;
	len -= l;
	ret += l;
	e = der_put_length_and_tag(p, len, l, ASN1_C_UNIV, PRIM, UT_Enumerated, &l);
	if (e)
		return (e);
	p -= l;
	len -= l;
	POST(p); POST(len);
	ret += l;
	*size = ret;
	return (0);
}

static int
encode_octet_string(unsigned char *p, size_t len,
		    const octet_string *k, size_t *size)
{
	size_t ret = 0;
	size_t l;
	int e;

	e = der_put_octet_string(p, len, k, &l);
	if (e)
		return (e);
	p -= l;
	len -= l;
	ret += l;
	e = der_put_length_and_tag(p, len, l, ASN1_C_UNIV, PRIM, UT_OctetString, &l);
	if (e)
		return (e);
	p -= l;
	len -= l;
	POST(p); POST(len);
	ret += l;
	*size = ret;
	return (0);
}

static int
encode_oid(unsigned char *p, size_t len,
	   const oid *k, size_t *size)
{
	size_t ret = 0;
	size_t l;
	int e;

	e = der_put_oid(p, len, k, &l);
	if (e)
		return (e);
	p -= l;
	len -= l;
	ret += l;
	e = der_put_length_and_tag(p, len, l, ASN1_C_UNIV, PRIM, UT_OID, &l);
	if (e)
		return (e);
	p -= l;
	len -= l;
	POST(p); POST(len);
	ret += l;
	*size = ret;
	return (0);
}


/* encapsulate.c */

static void
gssapi_encap_length(size_t data_len,
		    size_t *len,
		    size_t *total_len,
		    const gss_OID mech)
{
	size_t len_len;

	*len = 1 + 1 + mech->length + data_len;

	len_len = length_len(*len);

	*total_len = 1 + len_len + *len;
}

static u_char *
gssapi_mech_make_header(u_char *p,
			size_t len,
			const gss_OID mech)
{
	int e;
	size_t len_len, foo;

	*p++ = 0x60;
	len_len = length_len(len);
	e = der_put_length(p + len_len - 1, len_len, len, &foo);
	if (e || foo != len_len)
		return (NULL);
	p += len_len;
	*p++ = 0x06;
	*p++ = mech->length;
	memmove(p, mech->elements, mech->length);
	p += mech->length;
	return (p);
}

/*
 * Give it a krb5_data and it will encapsulate with extra GSS-API wrappings.
 */

static OM_uint32
gssapi_spnego_encapsulate(OM_uint32 * minor_status,
			  unsigned char *buf,
			  size_t buf_size,
			  gss_buffer_t output_token,
			  const gss_OID mech)
{
	size_t len, outer_len;
	u_char *p;

	gssapi_encap_length(buf_size, &len, &outer_len, mech);

	output_token->length = outer_len;
	output_token->value = malloc(outer_len);
	if (output_token->value == NULL) {
		*minor_status = ENOMEM;
		return (GSS_S_FAILURE);
	}
	p = gssapi_mech_make_header(output_token->value, len, mech);
	if (p == NULL) {
		if (output_token->length != 0U)
			gss_release_buffer(minor_status, output_token);
		return (GSS_S_FAILURE);
	}
	memmove(p, buf, buf_size);
	return (GSS_S_COMPLETE);
}

/* init_sec_context.c */
/*
 * SPNEGO wrapper for Kerberos5 GSS-API kouril@ics.muni.cz, 2003 (mostly
 * based on Heimdal code)
 */

static int
add_mech(MechTypeList * mech_list, gss_OID mech)
{
	MechType *tmp;
	int ret;

	tmp = realloc(mech_list->val, (mech_list->len + 1) * sizeof(*tmp));
	if (tmp == NULL)
		return (ENOMEM);
	mech_list->val = tmp;

	ret = der_get_oid(mech->elements, mech->length,
			  &mech_list->val[mech_list->len], NULL);
	if (ret)
		return (ret);

	mech_list->len++;
	return (0);
}

/*
 * return the length of the mechanism in token or -1
 * (which implies that the token was bad - GSS_S_DEFECTIVE_TOKEN
 */

static ssize_t
gssapi_krb5_get_mech(const u_char *ptr,
		     size_t total_len,
		     const u_char **mech_ret)
{
	size_t len, len_len, mech_len, foo;
	const u_char *p = ptr;
	int e;

	if (total_len < 1U)
		return (-1);
	if (*p++ != 0x60)
		return (-1);
	e = der_get_length (p, total_len - 1, &len, &len_len);
	if (e || 1 + len_len + len != total_len)
		return (-1);
	p += len_len;
	if (*p++ != 0x06)
		return (-1);
	e = der_get_length (p, total_len - 1 - len_len - 1,
			    &mech_len, &foo);
	if (e)
		return (-1);
	p += foo;
	*mech_ret = p;
	return (mech_len);
}

static OM_uint32
spnego_initial(OM_uint32 *minor_status,
	       const gss_cred_id_t initiator_cred_handle,
	       gss_ctx_id_t *context_handle,
	       const gss_name_t target_name,
	       const gss_OID mech_type,
	       OM_uint32 req_flags,
	       OM_uint32 time_req,
	       const gss_channel_bindings_t input_chan_bindings,
	       const gss_buffer_t input_token,
	       gss_OID *actual_mech_type,
	       gss_buffer_t output_token,
	       OM_uint32 *ret_flags,
	       OM_uint32 *time_rec)
{
	NegTokenInit token_init;
	OM_uint32 major_status, minor_status2;
	gss_buffer_desc	krb5_output_token = GSS_C_EMPTY_BUFFER;
	unsigned char *buf = NULL;
	size_t buf_size;
	size_t len = 0;	/* XXX: gcc */
	int ret;

	(void)mech_type;

	memset(&token_init, 0, sizeof(token_init));

	ret = add_mech(&token_init.mechTypes, GSS_KRB5_MECH);
	if (ret) {
		*minor_status = ret;
		ret = GSS_S_FAILURE;
		goto end;
	}

	major_status = gss_init_sec_context(minor_status,
					    initiator_cred_handle,
					    context_handle,
					    target_name,
					    GSS_KRB5_MECH,
					    req_flags,
					    time_req,
					    input_chan_bindings,
					    input_token,
					    actual_mech_type,
					    &krb5_output_token,
					    ret_flags,
					    time_rec);
	if (GSS_ERROR(major_status)) {
		ret = major_status;
		goto end;
	}
	if (krb5_output_token.length > 0U) {
		token_init.mechToken = malloc(sizeof(*token_init.mechToken));
		if (token_init.mechToken == NULL) {
			*minor_status = ENOMEM;
			ret = GSS_S_FAILURE;
			goto end;
		}
		token_init.mechToken->data = krb5_output_token.value;
		token_init.mechToken->length = krb5_output_token.length;
	}
	/*
	 * The MS implementation of SPNEGO seems to not like the mechListMIC
	 * field, so we omit it (it's optional anyway)
	 */

	buf_size = 1024;
	buf = malloc(buf_size);
	if (buf == NULL) {
		*minor_status = ENOMEM;
		ret = GSS_S_FAILURE;
		goto end;
	}

	do {
		ret = encode_NegTokenInit(buf + buf_size - 1,
					  buf_size,
					  &token_init, &len);
		if (ret == 0) {
			size_t tmp;

			ret = der_put_length_and_tag(buf + buf_size - len - 1,
						     buf_size - len,
						     len,
						     ASN1_C_CONTEXT,
						     CONS,
						     0,
						     &tmp);
			if (ret == 0)
				len += tmp;
		}
		if (ret) {
			if (ret == ASN1_OVERFLOW) {
				u_char *tmp;

				buf_size *= 2;
				tmp = realloc(buf, buf_size);
				if (tmp == NULL) {
					*minor_status = ENOMEM;
					ret = GSS_S_FAILURE;
					goto end;
				}
				buf = tmp;
			} else {
				*minor_status = ret;
				ret = GSS_S_FAILURE;
				goto end;
			}
		}
	} while (ret == ASN1_OVERFLOW);

	ret = gssapi_spnego_encapsulate(minor_status,
					buf + buf_size - len, len,
					output_token, GSS_SPNEGO_MECH);
	if (ret == GSS_S_COMPLETE)
		ret = major_status;

end:
	if (token_init.mechToken != NULL) {
		free(token_init.mechToken);
		token_init.mechToken = NULL;
	}
	free_NegTokenInit(&token_init);
	if (krb5_output_token.length != 0U)
		gss_release_buffer(&minor_status2, &krb5_output_token);
	if (buf)
		free(buf);

	return (ret);
}

static OM_uint32
spnego_reply(OM_uint32 *minor_status,
	     const gss_cred_id_t initiator_cred_handle,
	     gss_ctx_id_t *context_handle,
	     const gss_name_t target_name,
	     const gss_OID mech_type,
	     OM_uint32 req_flags,
	     OM_uint32 time_req,
	     const gss_channel_bindings_t input_chan_bindings,
	     const gss_buffer_t input_token,
	     gss_OID *actual_mech_type,
	     gss_buffer_t output_token,
	     OM_uint32 *ret_flags,
	     OM_uint32 *time_rec)
{
	OM_uint32 ret;
	NegTokenResp resp;
	unsigned char *buf;
	size_t buf_size;
	u_char oidbuf[17];
	size_t oidlen;
	gss_buffer_desc sub_token;
	ssize_t mech_len;
	const u_char *p;
	size_t len, taglen;

	(void)mech_type;

	output_token->length = 0;
	output_token->value  = NULL;

	/*
	 * SPNEGO doesn't include gss wrapping on SubsequentContextToken
	 * like the Kerberos 5 mech does. But lets check for it anyway.
	 */

	mech_len = gssapi_krb5_get_mech(input_token->value,
					input_token->length,
					&p);

	if (mech_len < 0) {
		buf = input_token->value;
		buf_size = input_token->length;
	} else if ((size_t)mech_len == GSS_KRB5_MECH->length &&
		   isc_safe_memequal(GSS_KRB5_MECH->elements, p, mech_len))
		return (gss_init_sec_context(minor_status,
					     initiator_cred_handle,
					     context_handle,
					     target_name,
					     GSS_KRB5_MECH,
					     req_flags,
					     time_req,
					     input_chan_bindings,
					     input_token,
					     actual_mech_type,
					     output_token,
					     ret_flags,
					     time_rec));
	else if ((size_t)mech_len == GSS_SPNEGO_MECH->length &&
		 isc_safe_memequal(GSS_SPNEGO_MECH->elements, p, mech_len)) {
		ret = gssapi_spnego_decapsulate(minor_status,
						input_token,
						&buf,
						&buf_size,
						GSS_SPNEGO_MECH);
		if (ret)
			return (ret);
	} else
		return (GSS_S_BAD_MECH);

	ret = der_match_tag_and_length(buf, buf_size,
				       ASN1_C_CONTEXT, CONS, 1, &len, &taglen);
	if (ret)
		return (ret);

	if(len > buf_size - taglen)
		return (ASN1_OVERRUN);

	ret = decode_NegTokenResp(buf + taglen, len, &resp, NULL);
	if (ret) {
		free_NegTokenResp(&resp);
		*minor_status = ENOMEM;
		return (GSS_S_FAILURE);
	}

	if (resp.negState == NULL ||
	    *(resp.negState) == reject ||
	    resp.supportedMech == NULL) {
		free_NegTokenResp(&resp);
		return (GSS_S_BAD_MECH);
	}

	ret = der_put_oid(oidbuf + sizeof(oidbuf) - 1,
			  sizeof(oidbuf),
			  resp.supportedMech,
			  &oidlen);
	if (ret || oidlen != GSS_KRB5_MECH->length ||
	    !isc_safe_memequal(oidbuf + sizeof(oidbuf) - oidlen,
			      GSS_KRB5_MECH->elements, oidlen))
	{
		free_NegTokenResp(&resp);
		return GSS_S_BAD_MECH;
	}

	if (resp.responseToken != NULL) {
		sub_token.length = resp.responseToken->length;
		sub_token.value  = resp.responseToken->data;
	} else {
		sub_token.length = 0;
		sub_token.value  = NULL;
	}

	ret = gss_init_sec_context(minor_status,
				   initiator_cred_handle,
				   context_handle,
				   target_name,
				   GSS_KRB5_MECH,
				   req_flags,
				   time_req,
				   input_chan_bindings,
				   &sub_token,
				   actual_mech_type,
				   output_token,
				   ret_flags,
				   time_rec);
	if (ret) {
		free_NegTokenResp(&resp);
		return (ret);
	}

	/*
	 * XXXSRA I don't think this limited implementation ever needs
	 * to check the MIC -- our preferred mechanism (Kerberos)
	 * authenticates its own messages and is the only mechanism
	 * we'll accept, so if the mechanism negotiation completes
	 * successfully, we don't need the MIC.  See RFC 4178.
	 */

	free_NegTokenResp(&resp);
	return (ret);
}



OM_uint32
gss_init_sec_context_spnego(OM_uint32 *minor_status,
			    const gss_cred_id_t initiator_cred_handle,
			    gss_ctx_id_t *context_handle,
			    const gss_name_t target_name,
			    const gss_OID mech_type,
			    OM_uint32 req_flags,
			    OM_uint32 time_req,
			    const gss_channel_bindings_t input_chan_bindings,
			    const gss_buffer_t input_token,
			    gss_OID *actual_mech_type,
			    gss_buffer_t output_token,
			    OM_uint32 *ret_flags,
			    OM_uint32 *time_rec)
{
	/* Dirty trick to suppress compiler warnings */

	/* Figure out whether we're starting over or processing a reply */

	if (input_token == GSS_C_NO_BUFFER || input_token->length == 0U)
		return (spnego_initial(minor_status,
				       initiator_cred_handle,
				       context_handle,
				       target_name,
				       mech_type,
				       req_flags,
				       time_req,
				       input_chan_bindings,
				       input_token,
				       actual_mech_type,
				       output_token,
				       ret_flags,
				       time_rec));
	else
		return (spnego_reply(minor_status,
				     initiator_cred_handle,
				     context_handle,
				     target_name,
				     mech_type,
				     req_flags,
				     time_req,
				     input_chan_bindings,
				     input_token,
				     actual_mech_type,
				     output_token,
				     ret_flags,
				     time_rec));
}

#endif /* GSSAPI */