|
root / base / usr / src / lib / libsmbfs / smb / spnegoparse.c
spnegoparse.c C 1895 lines 61.8 KB
   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
// Copyright 2022 RackTop Systems, Inc.
// Copyright 2012 Nexenta Systems, Inc.  All rights reserved.
// Copyright (C) 2002 Microsoft Corporation
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS"
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
// OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTIBILITY
// AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Date    - 10/08/2002
// Author  - Sanj Surati

/////////////////////////////////////////////////////////////
//
// SPNEGOPARSE.C
//
// SPNEGO Token Handler Source File
//
// Contains implementation of SPNEGO Token parsing functions.
//
/////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include "spnego.h"
#include "derparse.h"
#include "spnegoparse.h"

//
// Defined in DERPARSE.C
//

extern MECH_OID g_stcMechOIDList [];

/**********************************************************************/
/**                                                                  **/
/**                                                                  **/
/**                                                                  **/
/**                                                                  **/
/**                 Local SPNEGO Helper definitions                  **/
/**                                                                  **/
/**                                                                  **/
/**                                                                  **/
/**                                                                  **/
/**********************************************************************/


/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    CalculateMinSpnegoInitTokenSize
//
// Parameters:
//    [in]  nMechTokenLength        -  Length of the MechToken Element
//    [in]  nMechListMICLength      -  Length of the MechListMIC Element
//                                     (or negHints, if no MechToken)
//    [in]  mechOID                 -  OID for MechList
//    [in]  nReqFlagsAvailable      -  Is ContextFlags element available
//    [out] pnTokenSize             -  Filled out with total size of token
//    [out] pnInternalTokenLength   -  Filled out with length minus length
//                                     for initial token.
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Calculates the required length for a SPNEGO NegTokenInit token based
//    on the supplied variable length values and which elements are present.
//    Note that because the lengths can be represented by an arbitrary
//    number of bytes in DER encodings, we actually calculate the lengths
//    backwards, so we always know how many bytes we will potentially be
//    writing out.
//
////////////////////////////////////////////////////////////////////////////

int CalculateMinSpnegoInitTokenSize( long nMechTokenLength,
      long nMechListMICLength, SPNEGO_MECH_OID *mechOidLst, int mechOidCnt,
                                 int nReqFlagsAvailable, long* pnTokenSize,
                                 long* pnInternalTokenLength )
{
   int   nReturn = SPNEGO_E_INVALID_LENGTH;

   // Start at 0.
   long  nTotalLength = 0;
   long  nTempLength= 0L;

   // We will calculate this by walking the token backwards

   // Start with MIC Element (or negHints)
   if ( nMechListMICLength > 0L )
   {
      nTempLength = ASNDerCalcElementLength( nMechListMICLength, NULL );

      // Check for rollover error
      if ( nTempLength < nMechListMICLength )
      {
         goto xEndTokenInitLength;
      }

      nTotalLength += nTempLength;
   }

   // Next is the MechToken
   if ( nMechTokenLength > 0L )
   {
      nTempLength += ASNDerCalcElementLength( nMechTokenLength, NULL );

      // Check for rollover error
      if ( nTempLength < nTotalLength )
      {
         goto xEndTokenInitLength;
      }

      nTotalLength = nTempLength;
   }

   // Next is the ReqFlags
   if ( nReqFlagsAvailable )
   {
      nTempLength += ASNDerCalcElementLength( SPNEGO_NEGINIT_MAXLEN_REQFLAGS, NULL );

      // Check for rollover error
      if ( nTempLength < nTotalLength )
      {
         goto xEndTokenInitLength;
      }

      nTotalLength = nTempLength;
   }

   // Next is the MechList - This is REQUIRED
   nTempLength += ASNDerCalcMechListLength( mechOidLst, mechOidCnt, NULL );

   // Check for rollover error
   if ( nTempLength < nTotalLength )
   {
      goto xEndTokenInitLength;
   }

   nTotalLength = nTempLength;

   // Following four fields are the basic header tokens

   // Sequence Token
   nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );

   // Check for rollover error
   if ( nTempLength < nTotalLength )
   {
      goto xEndTokenInitLength;
   }

   nTotalLength = nTempLength;

   // Neg Token Identifier Token
   nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );

   // Check for rollover error
   if ( nTempLength < nTotalLength )
   {
      goto xEndTokenInitLength;
   }

   nTotalLength = nTempLength;

   // SPNEGO OID Token
   nTempLength += g_stcMechOIDList[spnego_mech_oid_Spnego].iLen;

   // Check for rollover error
   if ( nTempLength < nTotalLength )
   {
      goto xEndTokenInitLength;
   }

   nTotalLength = nTempLength;

   // App Constructed Token
   nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );

   // Check for rollover error
   if ( nTempLength < nTotalLength )
   {
      goto xEndTokenInitLength;
   }

   // The internal length doesn't include the number of bytes
   // for the initial token
   *pnInternalTokenLength = nTotalLength;
   nTotalLength = nTempLength;

   // We're done
   *pnTokenSize = nTotalLength;
   nReturn = SPNEGO_E_SUCCESS;

xEndTokenInitLength:

   return nReturn;

}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    CreateSpnegoInitToken
//
// Parameters:
//    [in]  pMechTypeList           -  OID array
//    [in]  MechTypeCnt             -  OID array length
//    [in]  ucContextFlags          -  ContextFlags value
//    [in]  pbMechToken             -  Mech Token Binary Data
//    [in]  ulMechTokenLen          -  Length of Mech Token
//    [in]  pbMechListMIC           -  MechListMIC Binary Data (or negHints)
//    [in]  ulMechListMICn          -  Length of MechListMIC
//    [out] pbTokenData             -  Buffer to write token into.
//    [in]  nTokenLength            -  Length of pbTokenData buffer
//    [in]  nInternalTokenLength    -  Length of full token without leading
//                                     token bytes.
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Uses DER to fill out pbTokenData with a SPNEGO NegTokenInit Token
//    Note that because the lengths can be represented by an arbitrary
//    number of bytes in DER encodings, we actually calculate the lengths
//    backwards, so we always know how many bytes we will potentially be
//    writing out.
//
//    This function is also used to create an SPNEGO "hint", as described in
//    [MS-SPNG] sec. 2.2.1 negTokenInit2.  The "hint" looks almost identical
//    to a NegTokenInit, but has a "negHints" field inserted before the MIC.
//    A normal SPNEGO negTokenInit2 contains only the mech list and the
//    negHints.  To avoid a giant copy/paste of this function, we pass the
//    negHints as the MIC arg, and pass NULL as the MechToken to indicate
//    that we're creating a Hint rather than an Init, and use the correct
//    type when writing out the MIC (or negHints) element.
//
////////////////////////////////////////////////////////////////////////////

int CreateSpnegoInitToken( SPNEGO_MECH_OID *pMechTypeList, long MechTypeCnt,
          unsigned char ucContextFlags, unsigned char* pbMechToken,
          unsigned long ulMechTokenLen, unsigned char* pbMechListMIC,
          unsigned long ulMechListMICLen, unsigned char* pbTokenData,
          long nTokenLength, long nInternalTokenLength )
{
   int   nReturn = SPNEGO_E_INVALID_LENGTH;

   // Start at 0.
   long  nTempLength= 0L;
   long  nTotalBytesWritten = 0L;
   long  nInternalLength = 0L;

   unsigned char* pbWriteTokenData = pbTokenData + nTokenLength;

   // Temporary buffer to hold the REQ Flags as BIT String Data
   unsigned char  abTempReqFlags[SPNEGO_NEGINIT_MAXLEN_REQFLAGS];


   // We will write the token out backwards to properly handle the cases
   // where the length bytes become adjustable

   // Start with MIC Element (or negHints)
   if ( ulMechListMICLen > 0L )
   {
      unsigned char ucType;
      nTempLength = ASNDerCalcElementLength( ulMechListMICLen, &nInternalLength );

      // Decrease the pbWriteTokenData, now we know the length and write it out.
      // Note: When MechTokenLen == 0, we're writing a negTokenInit2 and the
      // MIC arg is really negHints, written as a constructed sequence.
      // Otherwise we're writing a negTokenInit, and the MIC is an OCTETSTRING.
      ucType = (ulMechTokenLen == 0) ?
         SPNEGO_CONSTRUCTED_SEQUENCE : OCTETSTRING;

      pbWriteTokenData -= nTempLength;
      nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC,
                              ucType, pbMechListMIC, ulMechListMICLen );

      // Adjust Values and sanity check
      nTotalBytesWritten += nTempLength;
      nInternalTokenLength -= nTempLength;

      if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
      {
         goto xEndWriteNegTokenInit;
      }

   }  // IF MechListMIC is present

   // Next is the MechToken
   if ( ulMechTokenLen > 0L )
   {
      nTempLength = ASNDerCalcElementLength( ulMechTokenLen, &nInternalLength );

      // Decrease the pbWriteTokenData, now we know the length and
      // write it out.
      pbWriteTokenData -= nTempLength;
      nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_MECHTOKEN,
                              OCTETSTRING, pbMechToken, ulMechTokenLen );
      // Adjust Values and sanity check
      nTotalBytesWritten += nTempLength;
      nInternalTokenLength -= nTempLength;

      if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
      {
         goto xEndWriteNegTokenInit;
      }

   }  // IF MechToken Length is present

   // Next is the ReqFlags
   if ( ucContextFlags > 0L )
   {

      nTempLength = ASNDerCalcElementLength( SPNEGO_NEGINIT_MAXLEN_REQFLAGS, &nInternalLength );

      // We need a byte that indicates how many bits difference between the number
      // of bits used in final octet (we only have one) and the max (8)

      abTempReqFlags[0] = SPNEGO_NEGINIT_REQFLAGS_BITDIFF;
      abTempReqFlags[1] = ucContextFlags;

      // Decrease the pbWriteTokenData, now we know the length and
      // write it out.
      pbWriteTokenData -= nTempLength;
      nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_REQFLAGS,
                              BITSTRING, abTempReqFlags, SPNEGO_NEGINIT_MAXLEN_REQFLAGS );

      // Adjust Values and sanity check
      nTotalBytesWritten += nTempLength;
      nInternalTokenLength -= nTempLength;

      if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
      {
         goto xEndWriteNegTokenInit;
      }

   }  // IF ContextFlags

   // Next is the MechList - This is REQUIRED
   nTempLength = ASNDerCalcMechListLength( pMechTypeList, MechTypeCnt, &nInternalLength );

   // Decrease the pbWriteTokenData, now we know the length and
   // write it out.
   pbWriteTokenData -= nTempLength;
   nTempLength = ASNDerWriteMechList( pbWriteTokenData, pMechTypeList, MechTypeCnt );

   // Adjust Values and sanity check
   nTotalBytesWritten += nTempLength;
   nInternalTokenLength -= nTempLength;

   if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
   {
      goto xEndWriteNegTokenInit;
   }

   // The next tokens we're writing out reflect the total number of bytes
   // we have actually written out.

   // Sequence Token
   nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );

   // Decrease the pbWriteTokenData, now we know the length and
   // write it out.
   pbWriteTokenData -= nTempLength;
   nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
                                    NULL, nTotalBytesWritten );

   // Adjust Values and sanity check
   nTotalBytesWritten += nTempLength;
   nInternalTokenLength -= nTempLength;

   if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
   {
      goto xEndWriteNegTokenInit;
   }

   // Neg Init Token Identifier Token
   nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );

   // Decrease the pbWriteTokenData, now we know the length and
   // write it out.
   pbWriteTokenData -= nTempLength;
   nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGINIT_TOKEN_IDENTIFIER,
                                    NULL, nTotalBytesWritten );

   // Adjust Values and sanity check
   nTotalBytesWritten += nTempLength;
   nInternalTokenLength -= nTempLength;

   if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
   {
      goto xEndWriteNegTokenInit;
   }

   // SPNEGO OID Token
   nTempLength = g_stcMechOIDList[spnego_mech_oid_Spnego].iLen;

   // Decrease the pbWriteTokenData, now we know the length and
   // write it out.
   pbWriteTokenData -= nTempLength;
   nTempLength = ASNDerWriteOID( pbWriteTokenData, spnego_mech_oid_Spnego );

   // Adjust Values and sanity check
   nTotalBytesWritten += nTempLength;
   nInternalTokenLength -= nTempLength;

   if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
   {
      goto xEndWriteNegTokenInit;
   }

   // App Constructed Token
   nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );

   // Decrease the pbWriteTokenData, now we know the length and
   // write it out.
   pbWriteTokenData -= nTempLength;
   nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGINIT_APP_CONSTRUCT,
                                    NULL, nTotalBytesWritten );

   // Adjust Values and sanity check
   nTotalBytesWritten += nTempLength;

   // Don't adjust the internal token length here, it doesn't account
   // the initial bytes written out (we really don't need to keep
   // a running count here, but for debugging, it helps to be able
   // to see the total number of bytes written out as well as the
   // number of bytes left to write).

   if ( nTotalBytesWritten == nTokenLength && nInternalTokenLength == 0 &&
         pbWriteTokenData == pbTokenData )
   {
      nReturn = SPNEGO_E_SUCCESS;
   }

xEndWriteNegTokenInit:

   return nReturn;

}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    CalculateMinSpnegoTargTokenSize
//
// Parameters:
//    [in]  MechType                -  Supported MechType
//    [in]  spnegoNegResult         -  Neg Result
//    [in]  nMechTokenLength        -  Length of the MechToken Element
//    [in]  nMechListMICLength      -  Length of the MechListMIC Element
//    [out] pnTokenSize             -  Filled out with total size of token
//    [out] pnInternalTokenLength   -  Filled out with length minus length
//                                     for initial token.
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Calculates the required length for a SPNEGO NegTokenTarg token based
//    on the supplied variable length values and which elements are present.
//    Note that because the lengths can be represented by an arbitrary
//    number of bytes in DER encodings, we actually calculate the lengths
//    backwards, so we always know how many bytes we will potentially be
//    writing out.
//
////////////////////////////////////////////////////////////////////////////

int CalculateMinSpnegoTargTokenSize( SPNEGO_MECH_OID MechType,
                                    SPNEGO_NEGRESULT spnegoNegResult, long nMechTokenLen,
                                    long nMechListMICLen, long* pnTokenSize,
                                    long* pnInternalTokenLength )
{
   int   nReturn = SPNEGO_E_INVALID_LENGTH;

   // Start at 0.
   long  nTotalLength = 0;
   long  nTempLength= 0L;

   // We will calculate this by walking the token backwards

   // Start with MIC Element
   if ( nMechListMICLen > 0L )
   {
      nTempLength = ASNDerCalcElementLength( nMechListMICLen, NULL );

      // Check for rollover error
      if ( nTempLength < nMechListMICLen )
      {
         goto xEndTokenTargLength;
      }

      nTotalLength += nTempLength;
   }

   // Next is the MechToken
   if ( nMechTokenLen > 0L )
   {
      nTempLength += ASNDerCalcElementLength( nMechTokenLen, NULL );

      // Check for rollover error
      if ( nTempLength < nTotalLength )
      {
         goto xEndTokenTargLength;
      }

      nTotalLength = nTempLength;
   }

   // Supported MechType
   if ( spnego_mech_oid_NotUsed != MechType )
   {
      // Supported MechOID element - we use the token function since
      // we already know the size of the OID token and value
      nTempLength += ASNDerCalcElementLength( g_stcMechOIDList[MechType].iActualDataLen,
                                             NULL );

      // Check for rollover error
      if ( nTempLength < nTotalLength )
      {
         goto xEndTokenTargLength;
      }

      nTotalLength = nTempLength;

   }  // IF MechType is available

   // NegResult Element
   if ( spnego_negresult_NotUsed != spnegoNegResult )
   {
      nTempLength += ASNDerCalcElementLength( SPNEGO_NEGTARG_MAXLEN_NEGRESULT, NULL );

      // Check for rollover error
      if ( nTempLength < nTotalLength )
      {
         goto xEndTokenTargLength;
      }

      nTotalLength = nTempLength;

   }  // IF negResult is available

   // Following two fields are the basic header tokens

   // Sequence Token
   nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );

   // Check for rollover error
   if ( nTempLength < nTotalLength )
   {
      goto xEndTokenTargLength;
   }

   nTotalLength = nTempLength;

   // Neg Token Identifier Token
   nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );

   // Check for rollover error
   if ( nTempLength < nTotalLength )
   {
      goto xEndTokenTargLength;
   }

   // The internal length doesn't include the number of bytes
   // for the initial token
   *pnInternalTokenLength = nTotalLength;
   nTotalLength = nTempLength;

   // We're done
   *pnTokenSize = nTotalLength;
   nReturn = SPNEGO_E_SUCCESS;

xEndTokenTargLength:

   return nReturn;

}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    CreateSpnegoTargToken
//
// Parameters:
//    [in]  MechType                -  Supported MechType
//    [in]  eNegResult              -  NegResult value
//    [in]  pbMechToken             -  Mech Token Binary Data
//    [in]  ulMechTokenLen          -  Length of Mech Token
//    [in]  pbMechListMIC           -  MechListMIC Binary Data
//    [in]  ulMechListMICn          -  Length of MechListMIC
//    [out] pbTokenData             -  Buffer to write token into.
//    [in]  nTokenLength            -  Length of pbTokenData buffer
//    [in]  nInternalTokenLength    -  Length of full token without leading
//                                     token bytes.
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Uses DER to fill out pbTokenData with a SPNEGO NegTokenTarg Token
//    Note that because the lengths can be represented by an arbitrary
//    number of bytes in DER encodings, we actually calculate the lengths
//    backwards, so we always know how many bytes we will potentially be
//    writing out.
//
////////////////////////////////////////////////////////////////////////////

int CreateSpnegoTargToken( SPNEGO_MECH_OID MechType,
          SPNEGO_NEGRESULT eNegResult, unsigned char* pbMechToken,
          unsigned long ulMechTokenLen, unsigned char* pbMechListMIC,
          unsigned long ulMechListMICLen, unsigned char* pbTokenData,
          long nTokenLength, long nInternalTokenLength )
{
   int   nReturn = SPNEGO_E_INVALID_LENGTH;

   // Start at 0.
   long  nTempLength= 0L;
   long  nTotalBytesWritten = 0L;
   long  nInternalLength = 0L;

   unsigned char  ucTemp = 0;

   // We will write the token out backwards to properly handle the cases
   // where the length bytes become adjustable, so the write location
   // is initialized to point *just* past the end of the buffer.

   unsigned char* pbWriteTokenData = pbTokenData + nTokenLength;


   // Start with MIC Element
   if ( ulMechListMICLen > 0L )
   {
      nTempLength = ASNDerCalcElementLength( ulMechListMICLen, &nInternalLength );

      // Decrease the pbWriteTokenData, now we know the length and
      // write it out.

      pbWriteTokenData -= nTempLength;
      nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC,
                              OCTETSTRING, pbMechListMIC, ulMechListMICLen );

      // Adjust Values and sanity check
      nTotalBytesWritten += nTempLength;
      nInternalTokenLength -= nTempLength;

      if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
      {
         goto xEndWriteNegTokenTarg;
      }

   }  // IF MechListMIC is present

   // Next is the MechToken
   if ( ulMechTokenLen > 0L )
   {
      nTempLength = ASNDerCalcElementLength( ulMechTokenLen, &nInternalLength );

      // Decrease the pbWriteTokenData, now we know the length and
      // write it out.
      pbWriteTokenData -= nTempLength;
      nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN,
                              OCTETSTRING, pbMechToken, ulMechTokenLen );
      // Adjust Values and sanity check
      nTotalBytesWritten += nTempLength;
      nInternalTokenLength -= nTempLength;

      if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
      {
         goto xEndWriteNegTokenTarg;
      }

   }  // IF MechToken Length is present

   // Supported Mech Type
   if ( spnego_mech_oid_NotUsed != MechType )
   {

      nTempLength = ASNDerCalcElementLength( g_stcMechOIDList[MechType].iActualDataLen,
                                             &nInternalLength );

      // Decrease the pbWriteTokenData, now we know the length and
      // write it out.
      pbWriteTokenData -= nTempLength;
      nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH,
                                       g_stcMechOIDList[MechType].ucOid,
                                       g_stcMechOIDList[MechType].iLen );

      // Adjust Values and sanity check
      nTotalBytesWritten += nTempLength;
      nInternalTokenLength -= nTempLength;

      if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
      {
         goto xEndWriteNegTokenTarg;
      }

   }  // IF MechType is present

   // Neg Result
   // NegResult Element
   if ( spnego_negresult_NotUsed != eNegResult )
   {
      ucTemp = (unsigned char) eNegResult;

      nTempLength = ASNDerCalcElementLength( SPNEGO_NEGTARG_MAXLEN_NEGRESULT, &nInternalLength );

      // Decrease the pbWriteTokenData, now we know the length and
      // write it out.
      pbWriteTokenData -= nTempLength;
      nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_NEGRESULT,
                              ENUMERATED, &ucTemp, SPNEGO_NEGTARG_MAXLEN_NEGRESULT );

      // Adjust Values and sanity check
      nTotalBytesWritten += nTempLength;
      nInternalTokenLength -= nTempLength;

      if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
      {
         goto xEndWriteNegTokenTarg;
      }

   }  // If eNegResult is available

   // The next tokens we're writing out reflect the total number of bytes
   // we have actually written out.

   // Sequence Token
   nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );

   // Decrease the pbWriteTokenData, now we know the length and
   // write it out.
   pbWriteTokenData -= nTempLength;
   nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
                                    NULL, nTotalBytesWritten );

   // Adjust Values and sanity check
   nTotalBytesWritten += nTempLength;
   nInternalTokenLength -= nTempLength;

   if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
   {
      goto xEndWriteNegTokenTarg;
   }

   // Neg Targ Token Identifier Token
   nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );

   // Decrease the pbWriteTokenData, now we know the length and
   // write it out.
   pbWriteTokenData -= nTempLength;
   nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGTARG_TOKEN_IDENTIFIER,
                                    NULL, nTotalBytesWritten );

   // Adjust Values and sanity check
   nTotalBytesWritten += nTempLength;

   // Don't adjust the internal token length here, it doesn't account
   // the initial bytes written out (we really don't need to keep
   // a running count here, but for debugging, it helps to be able
   // to see the total number of bytes written out as well as the
   // number of bytes left to write).

   if ( nTotalBytesWritten == nTokenLength && nInternalTokenLength == 0 &&
         pbWriteTokenData == pbTokenData )
   {
      nReturn = SPNEGO_E_SUCCESS;
   }


xEndWriteNegTokenTarg:

   return nReturn;


}


/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    AllocEmptySpnegoToken
//
// Parameters:
//    [in]  ucCopyData        -  Flag to copy data or pointer.
//    [in]  ulFlags           -  Flags for SPNEGO_TOKEN data member.
//    [in]  pbTokenData       -  Binary token data.
//    [in]  ulTokenSize       -  Size of pbTokenData.
//
// Returns:
//    SPNEGO_TOKEN*  Success - Pointer to initialized SPNEGO_TOKEN struct
//                   Failure - NULL
//
// Comments :
//    Allocates a SPNEGO_TOKEN data structure and initializes it.  Based on
//    the value of ucCopyData, if non-zero, we copy the data into a buffer
//    we allocate in this function, otherwise, we copy the data pointer
//    direcly.
//
////////////////////////////////////////////////////////////////////////////

SPNEGO_TOKEN* AllocEmptySpnegoToken( unsigned char ucCopyData, unsigned long ulFlags,
                                    unsigned char * pbTokenData, unsigned long ulTokenSize )
{
   SPNEGO_TOKEN*  pSpnegoToken = (SPNEGO_TOKEN*) calloc( 1, sizeof(SPNEGO_TOKEN) );

   if ( NULL != pSpnegoToken )
   {
      // Set the token size
      pSpnegoToken->nStructSize = SPNEGO_TOKEN_SIZE;

      // Initialize the element array
      InitSpnegoTokenElementArray( pSpnegoToken );

      // Assign the flags value
      pSpnegoToken->ulFlags = ulFlags;

      //
      // IF ucCopyData is TRUE, we will allocate a buffer and copy data into it.
      // Otherwise, we will just copy the pointer and the length.  This is so we
      // can cut out additional allocations for performance reasons
      //

      if ( SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA == ucCopyData )
      {
         // Alloc the internal buffer.  Cleanup on failure.
         pSpnegoToken->pbBinaryData = (unsigned char*) calloc( ulTokenSize, sizeof(unsigned char) );

         if ( NULL != pSpnegoToken->pbBinaryData )
         {
            // We must ALWAYS free this buffer
            pSpnegoToken->ulFlags |= SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA;

            // Copy the data locally
            memcpy( pSpnegoToken->pbBinaryData, pbTokenData, ulTokenSize );
            pSpnegoToken->ulBinaryDataLen = ulTokenSize;
         }
         else
         {
            free( pSpnegoToken );
            pSpnegoToken = NULL;
         }

      }  // IF ucCopyData
      else
      {
         // Copy the pointer and the length directly - ulFlags will control whether or not
         // we are allowed to free the value

         pSpnegoToken->pbBinaryData = pbTokenData;
         pSpnegoToken->ulBinaryDataLen = ulTokenSize;
      }

   }

   return pSpnegoToken;
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    FreeSpnegoToken
//
// Parameters:
//    [in]  pSpnegoToken      -  Points to SPNEGO_TOKEN to free.
//
// Returns:
//    void
//
// Comments :
//    If non-NULL, interprets pSpnegoToken, freeing any internal allocations
//    and finally the actual structure.
//
////////////////////////////////////////////////////////////////////////////

void FreeSpnegoToken( SPNEGO_TOKEN* pSpnegoToken )
{
   if ( NULL != pSpnegoToken )
   {

      // Cleanup internal allocation per the flags
      if ( pSpnegoToken->ulFlags & SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA &&
         NULL != pSpnegoToken->pbBinaryData )
      {
         free( pSpnegoToken->pbBinaryData );
         pSpnegoToken->pbBinaryData = NULL;
      }

      free ( pSpnegoToken );
   }
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    InitSpnegoTokenElementArray
//
// Parameters:
//    [in]  pSpnegoToken      -  Points to SPNEGO_TOKEN structure.
//
// Returns:
//    void
//
// Comments :
//    Initializes the element array data member of a SPNEGO_TOKEN data
//    structure.
//
////////////////////////////////////////////////////////////////////////////

void InitSpnegoTokenElementArray( SPNEGO_TOKEN* pSpnegoToken )
{
   int   nCtr;

   // Set the number of elemnts
   pSpnegoToken->nNumElements = MAX_NUM_TOKEN_ELEMENTS;

   //
   // Initially, all elements are unavailable
   //

   for ( nCtr = 0; nCtr < MAX_NUM_TOKEN_ELEMENTS; nCtr++ )
   {
      // Set the element size as well
      pSpnegoToken->aElementArray[ nCtr ].nStructSize = SPNEGO_ELEMENT_SIZE;
      pSpnegoToken->aElementArray[ nCtr ].iElementPresent = SPNEGO_TOKEN_ELEMENT_UNAVAILABLE;
   }

}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    InitSpnegoTokenType
//
// Parameters:
//    [in]  pSpnegoToken            -  Points to SPNEGO_TOKEN structure.
//    [out] pnTokenLength           -  Filled out with total token length
//    [out] pnRemainingTokenLength  -  Filled out with remaining length
//                                     after header is parsed
//    [out] ppbFirstElement         -  Filled out with pointer to first
//                                     element after header info.
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Walks the underlying binary data for a SPNEGO_TOKEN data structure
//    and determines the type of the underlying token based on token header
//    information.
//
////////////////////////////////////////////////////////////////////////////

int InitSpnegoTokenType( SPNEGO_TOKEN* pSpnegoToken, long* pnTokenLength,
                           long* pnRemainingTokenLength, unsigned char** ppbFirstElement )
{
   int   nReturn = SPNEGO_E_INVALID_TOKEN;
   long  nActualTokenLength = 0L;
   long  nBoundaryLength = pSpnegoToken->ulBinaryDataLen;
   unsigned char* pbTokenData = pSpnegoToken->pbBinaryData;

   //
   // First byte MUST be either an APP_CONSTRUCT or the NEGTARG_TOKEN_TARG
   //

   if ( SPNEGO_NEGINIT_APP_CONSTRUCT == *pbTokenData )
   {
      // Validate the above token - this will tell us the actual length of the token
      // per the encoding (minus the actual token bytes)
      if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGINIT_APP_CONSTRUCT, 0L, nBoundaryLength,
                                          pnTokenLength, &nActualTokenLength ) )
                       == SPNEGO_E_SUCCESS )
      {
         // Initialize the remaining token length value.  This will be used
         // to tell the caller how much token there is left once we've parsed
         // the header (they could calculate it from the other values, but this
         // is a bit friendlier)
         *pnRemainingTokenLength = *pnTokenLength;

         // Make adjustments to next token
         pbTokenData += nActualTokenLength;
         nBoundaryLength -= nActualTokenLength;

         // The next token should be an OID
         if ( ( nReturn = ASNDerCheckOID( pbTokenData, spnego_mech_oid_Spnego, nBoundaryLength,
                                          &nActualTokenLength ) ) == SPNEGO_E_SUCCESS )
         {
            // Make adjustments to next token
            pbTokenData += nActualTokenLength;
            nBoundaryLength -= nActualTokenLength;
            *pnRemainingTokenLength -= nActualTokenLength;

            // The next token should specify the NegTokenInit
            if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGINIT_TOKEN_IDENTIFIER,
                                                *pnRemainingTokenLength, nBoundaryLength, pnTokenLength,
                                                &nActualTokenLength ) )
                             == SPNEGO_E_SUCCESS )
            {
               // Make adjustments to next token
               pbTokenData += nActualTokenLength;
               nBoundaryLength -= nActualTokenLength;
               *pnRemainingTokenLength -= nActualTokenLength;

               // The next token should specify the start of a sequence
               if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
                                                   *pnRemainingTokenLength, nBoundaryLength, pnTokenLength,
                                                   &nActualTokenLength ) )
                                == SPNEGO_E_SUCCESS )
               {
                  // NegTokenInit header is now checked out!

                  // Make adjustments to next token
                  *pnRemainingTokenLength -= nActualTokenLength;

                  // Store pointer to first element
                  *ppbFirstElement = pbTokenData + nActualTokenLength;
                  pSpnegoToken->ucTokenType = SPNEGO_TOKEN_INIT;
               }  // IF Check Sequence Token

            }  // IF Check NegTokenInit token


         }  // IF Check for SPNEGO OID


      }  // IF check app construct token

   }
   else if ( SPNEGO_NEGTARG_TOKEN_IDENTIFIER == *pbTokenData )
   {

      // The next token should specify the NegTokenInit
      if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGTARG_TOKEN_IDENTIFIER,
                                          *pnRemainingTokenLength, nBoundaryLength, pnTokenLength,
                                          &nActualTokenLength ) )
                       == SPNEGO_E_SUCCESS )
      {
         // Initialize the remaining token length value.  This will be used
         // to tell the caller how much token there is left once we've parsed
         // the header (they could calculate it from the other values, but this
         // is a bit friendlier)
         *pnRemainingTokenLength = *pnTokenLength;

         // Make adjustments to next token
         pbTokenData += nActualTokenLength;
         nBoundaryLength -= nActualTokenLength;

         // The next token should specify the start of a sequence
         if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
                                             *pnRemainingTokenLength, nBoundaryLength, pnTokenLength,
                                             &nActualTokenLength ) )
                          == SPNEGO_E_SUCCESS )
         {
            // NegTokenInit header is now checked out!

            // Make adjustments to next token
            *pnRemainingTokenLength -= nActualTokenLength;

            // Store pointer to first element
            *ppbFirstElement = pbTokenData + nActualTokenLength;
            pSpnegoToken->ucTokenType = SPNEGO_TOKEN_TARG;
         }  // IF Check Sequence Token

      }  // IF Check NegTokenInit token

   }  // ELSE IF it's a NegTokenTarg

   return nReturn;
}


/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    GetSpnegoInitTokenMechList
//
// Parameters:
//    [in]  pbTokenData             -  Points to binary MechList element
//                                     in NegTokenInit.
//    [in]  nMechListLength         -  Length of the MechList
//    [out] pSpnegoElement          -  Filled out with MechList Element
//                                     data.
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Checks that pbTokenData is pointing at something that at least
//    *looks* like a MechList and then fills out the supplied
//    SPNEGO_ELEMENT structure.
//
////////////////////////////////////////////////////////////////////////////

int GetSpnegoInitTokenMechList( unsigned char* pbTokenData, int nMechListLength,
                                 SPNEGO_ELEMENT* pSpnegoElement )
{
   int   nReturn = SPNEGO_E_INVALID_TOKEN;
   long  nLength = 0L;
   long  nActualTokenLength = 0L;

   // Actual MechList is prepended by a Constructed Sequence Token
   if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
                                       nMechListLength, nMechListLength,
                                       &nLength, &nActualTokenLength ) )
                             == SPNEGO_E_SUCCESS )
   {
      // Adjust for this token
      nMechListLength -= nActualTokenLength;
      pbTokenData += nActualTokenLength;

      // Perform simple validation of the actual MechList (i.e. ensure that
      // the OIDs in the MechList are reasonable).

      if ( ( nReturn = ValidateMechList( pbTokenData, nLength ) ) == SPNEGO_E_SUCCESS )
      {
         // Initialize the element now
         pSpnegoElement->eElementType = spnego_init_mechtypes;
         pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE;
         pSpnegoElement->type = SPNEGO_MECHLIST_TYPE;
         pSpnegoElement->nDatalength = nLength;
         pSpnegoElement->pbData = pbTokenData;
      }

   }  // IF Check Token

   return nReturn;
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    InitSpnegoTokenElementFromBasicType
//
// Parameters:
//    [in]  pbTokenData             -  Points to binary element data in
//                                     a SPNEGO token.
//    [in]  nElementLength          -  Length of the element
//    [in]  ucExpectedType          -  Expected DER type.
//    [in]  spnegoElementType       -  Which element is this?
//    [out] pSpnegoElement          -  Filled out with element data.
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Checks that pbTokenData is pointing at the specified DER type.  If so,
//    then we verify that lengths are proper and then fill out the
//    SPNEGO_ELEMENT data structure.
//
////////////////////////////////////////////////////////////////////////////

int InitSpnegoTokenElementFromBasicType( unsigned char* pbTokenData, int nElementLength,
                                          unsigned char ucExpectedType,
                                          SPNEGO_ELEMENT_TYPE spnegoElementType,
                                          SPNEGO_ELEMENT* pSpnegoElement )
{
   int   nReturn = SPNEGO_E_UNEXPECTED_TYPE;
   long  nLength = 0L;
   long  nActualTokenLength = 0L;

   // The type BYTE must match our token data or something is badly wrong
   if ( *pbTokenData == ucExpectedType )
   {

      // Check that we are pointing at the specified type
      if ( ( nReturn = ASNDerCheckToken( pbTokenData, ucExpectedType,
                                          nElementLength, nElementLength,
                                          &nLength, &nActualTokenLength ) )
                                == SPNEGO_E_SUCCESS )
      {
         // Adjust for this token
         nElementLength -= nActualTokenLength;
         pbTokenData += nActualTokenLength;

         // Initialize the element now
         pSpnegoElement->eElementType = spnegoElementType;
         pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE;
         pSpnegoElement->type = ucExpectedType;
         pSpnegoElement->nDatalength = nLength;
         pSpnegoElement->pbData = pbTokenData;
      }

   }  // IF type makes sense

   return nReturn;
}


/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    InitSpnegoTokenElementFromOID
//
// Parameters:
//    [in]  pbTokenData             -  Points to binary element data in
//                                     a SPNEGO token.
//    [in]  nElementLength          -  Length of the element
//    [in]  spnegoElementType       -  Which element is this?
//    [out] pSpnegoElement          -  Filled out with element data.
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Initializes a SpnegoElement from an OID - normally, this would have
//    used the Basic Type function above, but since we do binary compares
//    on the OIDs against the DER information as well as the OID, we need
//    to account for that.
//
////////////////////////////////////////////////////////////////////////////

int InitSpnegoTokenElementFromOID( unsigned char* pbTokenData, int nElementLength,
                                   SPNEGO_ELEMENT_TYPE spnegoElementType,
                                   SPNEGO_ELEMENT* pSpnegoElement )
{
   int   nReturn = SPNEGO_E_UNEXPECTED_TYPE;
   long  nLength = 0L;
   long  nActualTokenLength = 0L;

   // The type BYTE must match our token data or something is badly wrong
   if ( *pbTokenData == OID )
   {

      // Check that we are pointing at an OID type
      if ( ( nReturn = ASNDerCheckToken( pbTokenData, OID,
                                          nElementLength, nElementLength,
                                          &nLength, &nActualTokenLength ) )
                                == SPNEGO_E_SUCCESS )
      {
         // Don't adjust any values for this function

         // Initialize the element now
         pSpnegoElement->eElementType = spnegoElementType;
         pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE;
         pSpnegoElement->type = OID;
         pSpnegoElement->nDatalength = nElementLength;
         pSpnegoElement->pbData = pbTokenData;
      }

   }  // IF type makes sense

   return nReturn;
}


/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    InitSpnegoTokenElements
//
// Parameters:
//    [in]  pSpnegoToken            -  Points to SPNEGO_TOKEN struct
//    [in]  pbTokenData             -  Points to initial binary element
//                                     data in a SPNEGO token.
//    [in]  nRemainingTokenLength   -  Length remaining past header
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Interprets the data at pbTokenData based on the TokenType in
//    pSpnegoToken.  Since some elements are optional (technically all are
//    but the token becomes quite useless if this is so), we check if
//    an element exists before filling out the element in the array.
//
////////////////////////////////////////////////////////////////////////////

int InitSpnegoTokenElements( SPNEGO_TOKEN* pSpnegoToken, unsigned char* pbTokenData,
                           long nRemainingTokenLength  )
{
   //
   // The following arrays contain the token identifiers for the elements
   // comprising the actual token.  All values are optional, and there are
   // no defaults.
   //

   static unsigned char abNegTokenInitElements[] =
      { SPNEGO_NEGINIT_ELEMENT_MECHTYPES, SPNEGO_NEGINIT_ELEMENT_REQFLAGS,
         SPNEGO_NEGINIT_ELEMENT_MECHTOKEN, SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC };

   static unsigned char abNegTokenTargElements[] =
      { SPNEGO_NEGTARG_ELEMENT_NEGRESULT, SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH,
         SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN, SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC };

   int   nReturn = SPNEGO_E_SUCCESS;
   int   nCtr = 0L;
   long  nElementLength = 0L;
   long  nActualTokenLength = 0L;
   unsigned char* pbElements = NULL;

   // Point to the correct array
   switch( pSpnegoToken->ucTokenType )
   {
      case SPNEGO_TOKEN_INIT:
      {
         pbElements = abNegTokenInitElements;
      }
      break;

      case SPNEGO_TOKEN_TARG:
      {
         pbElements = abNegTokenTargElements;
      }
      break;

   }  // SWITCH tokentype

   //
   // Enumerate the element arrays and look for the tokens at our current location
   //

   for ( nCtr = 0L;
         SPNEGO_E_SUCCESS == nReturn &&
         nCtr < MAX_NUM_TOKEN_ELEMENTS &&
         nRemainingTokenLength > 0L;
         nCtr++ )
   {

      // Check if the token exists
      if ( ( nReturn = ASNDerCheckToken( pbTokenData, pbElements[nCtr],
                                          0L, nRemainingTokenLength,
                                          &nElementLength, &nActualTokenLength ) )
                                == SPNEGO_E_SUCCESS )
      {

         // Token data should skip over the sequence token and then
         // call the appropriate function to initialize the element
         pbTokenData += nActualTokenLength;

         // Lengths in the elements should NOT go beyond the element
         // length

         // Different tokens mean different elements
         if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
         {

            // Handle each element as appropriate
            switch( pbElements[nCtr] )
            {

               case SPNEGO_NEGINIT_ELEMENT_MECHTYPES:
               {
                  //
                  // This is a Mech List that specifies which OIDs the
                  // originator of the Init Token supports.
                  //

                  nReturn = GetSpnegoInitTokenMechList( pbTokenData, nElementLength,
                                                         &pSpnegoToken->aElementArray[nCtr] );

               }
               break;

               case SPNEGO_NEGINIT_ELEMENT_REQFLAGS:
               {
                  //
                  // This is a BITSTRING which specifies the flags that the receiver
                  // pass to the gss_accept_sec_context() function.
                  //

                  nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
                                                                  BITSTRING, spnego_init_reqFlags,
                                                                  &pSpnegoToken->aElementArray[nCtr] );
               }
               break;

               case SPNEGO_NEGINIT_ELEMENT_MECHTOKEN:
               {
                  //
                  // This is an OCTETSTRING which contains a GSSAPI token corresponding
                  // to the first OID in the MechList.
                  //

                  nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
                                                                  OCTETSTRING, spnego_init_mechToken,
                                                                  &pSpnegoToken->aElementArray[nCtr] );
               }
               break;

               case SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC:  // xA3
               {
                  //
                  // Don't yet know if this is a negTokenInit, or negTokenInit2.
                  // Unfortunately, both have the same type: SPNEGO_TOKEN_INIT
                  // If it's negTokenInit, this element should be an OCTETSTRING
                  // containing the MIC.  If it's a negTokenInit2, this element
                  // should be an SPNEGO_CONSTRUCTED_SEQUENCE containing the
                  // negHints (GENERALSTR, ignored)
                  //

                  nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
                                                                 OCTETSTRING, spnego_init_mechListMIC,
                                                                 &pSpnegoToken->aElementArray[nCtr] );

                  if (nReturn == SPNEGO_E_UNEXPECTED_TYPE) {
                     // This is really a negHints element.  Check the type and length,
                     // but otherwise just ignore it.
                     long  elen, tlen;
                     nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
                                          nElementLength, nElementLength,
                                          &elen, &tlen );
                  }
               }
               break;

            }  // SWITCH Element
         }
         else
         {
            /* pSpnegoToken->ucTokenType == SPNEGO_TOKEN_TARG */

            switch( pbElements[nCtr] )
            {

               case SPNEGO_NEGTARG_ELEMENT_NEGRESULT:
               {
                  //
                  // This is an ENUMERATION which specifies result of the last GSS
                  // token negotiation call.
                  //

                  nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
                                                                  ENUMERATED, spnego_targ_negResult,
                                                                  &pSpnegoToken->aElementArray[nCtr] );
               }
               break;

               case SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH:
               {
                  //
                  // This is an OID which specifies a supported mechanism.
                  //

                  nReturn = InitSpnegoTokenElementFromOID( pbTokenData, nElementLength,
                                                           spnego_targ_mechListMIC,
                                                           &pSpnegoToken->aElementArray[nCtr] );
               }
               break;

               case SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN:
               {
                  //
                  // This is an OCTETSTRING which specifies results of the last GSS
                  // token negotiation call.
                  //

                  nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
                                                                  OCTETSTRING, spnego_targ_responseToken,
                                                                  &pSpnegoToken->aElementArray[nCtr] );
               }
               break;

               case SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC:
               {
                  //
                  // This is an OCTETSTRING, typically 16 bytes,
                  // which contains a message integrity BLOB.
                  //

                  nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
                                                                 OCTETSTRING, spnego_targ_mechListMIC,
                                                                 &pSpnegoToken->aElementArray[nCtr] );
               }
               break;

            }  // SWITCH Element

         }  // ELSE !NegTokenInit

         // Account for the entire token and following data
         nRemainingTokenLength -= ( nActualTokenLength + nElementLength );

         // Token data should skip past the element length now
         pbTokenData += nElementLength;

      }  // IF Token found
      else if ( SPNEGO_E_TOKEN_NOT_FOUND == nReturn )
      {
         // For now, this is a benign error (remember, all elements are optional, so
         // if we don't find one, it's okay).

         nReturn = SPNEGO_E_SUCCESS;
      }

   }  // FOR enum elements

   //
   // We should always run down to 0 remaining bytes in the token.  If not, we've got
   // a bad token.
   //

   if ( SPNEGO_E_SUCCESS == nReturn && nRemainingTokenLength != 0L )
   {
      nReturn = SPNEGO_E_INVALID_TOKEN;
   }

   return nReturn;
}


/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    FindMechOIDInMechList
//
// Parameters:
//    [in]  pSpnegoElement          -  SPNEGO_ELEMENT for MechList
//    [in]  MechOID                 -  OID we're looking for.
//    [out] piMechTypeIndex         -  Index in the list where OID was
//                                     found
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Walks the MechList for MechOID.  When it is found, the index in the
//    list is written to piMechTypeIndex.
//
////////////////////////////////////////////////////////////////////////////

int FindMechOIDInMechList( SPNEGO_ELEMENT* pSpnegoElement, SPNEGO_MECH_OID MechOID,
                          int * piMechTypeIndex )
{
   int   nReturn = SPNEGO_E_NOT_FOUND;
   int   nCtr = 0;
   long  nLength = 0L;
   long  nBoundaryLength = pSpnegoElement->nDatalength;
   unsigned char* pbMechListData = pSpnegoElement->pbData;

   while( SPNEGO_E_SUCCESS != nReturn && nBoundaryLength > 0L )
   {

      // Use the helper function to check the OID
      if ( ( nReturn = ASNDerCheckOID( pbMechListData, MechOID, nBoundaryLength, &nLength ) )
                     == SPNEGO_E_SUCCESS )
      {
         *piMechTypeIndex = nCtr;
      }

      // Adjust for the current OID
      pbMechListData += nLength;
      nBoundaryLength -= nLength;
      nCtr++;

   }  // WHILE enuming OIDs

   return nReturn;

}


/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    ValidateMechList
//
// Parameters:
//    [in]  pbMechListData          -  Pointer to binary MechList data
//    [in]  nBoundaryLength         -  Length we must not exceed
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Checks the data at pbMechListData to see if it looks like a MechList.
//    As part of this, we walk the list and ensure that none of the OIDs
//    have a length that takes us outside of nBoundaryLength.
//
////////////////////////////////////////////////////////////////////////////

int ValidateMechList( unsigned char* pbMechListData, long nBoundaryLength )
{
   int   nReturn = SPNEGO_E_SUCCESS;
   long  nLength = 0L;
   long  nTokenLength = 0L;

   while( SPNEGO_E_SUCCESS == nReturn && nBoundaryLength > 0L )
   {
      // Verify that we have something that at least *looks* like an OID - in other
      // words it has an OID identifier and specifies a length that doesn't go beyond
      // the size of the list.
      nReturn = ASNDerCheckToken( pbMechListData, OID, 0L, nBoundaryLength,
                                  &nLength, &nTokenLength );

      // Adjust for the current OID
      pbMechListData += ( nLength + nTokenLength );
      nBoundaryLength -= ( nLength + nTokenLength );

   }  // WHILE enuming OIDs

   return nReturn;

}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    IsValidMechOid
//
// Parameters:
//    [in]  mechOid  -  mechOID id enumeration
//
// Returns:
//    int   Success - 1
//          Failure - 0
//
// Comments :
//    Checks for a valid mechOid value.
//
////////////////////////////////////////////////////////////////////////////

int IsValidMechOid( SPNEGO_MECH_OID mechOid )
{
   return ( mechOid >= spnego_mech_oid_Kerberos_V5_Legacy &&
            mechOid <= spnego_mech_oid_NTLMSSP );
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    IsValidContextFlags
//
// Parameters:
//    [in]  ucContextFlags -  ContextFlags value
//
// Returns:
//    int   Success - 1
//          Failure - 0
//
// Comments :
//    Checks for a valid ContextFlags value.
//
////////////////////////////////////////////////////////////////////////////

int IsValidContextFlags( unsigned char ucContextFlags )
{
   // Mask out our valid bits.  If there is anything leftover, this
   // is not a valid value for Context Flags
   return ( ( ucContextFlags & ~SPNEGO_NEGINIT_CONTEXT_MASK ) == 0 );
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    IsValidNegResult
//
// Parameters:
//    [in]  negResult   -  NegResult value
//
// Returns:
//    int   Success - 1
//          Failure - 0
//
// Comments :
//    Checks for a valid NegResult value.
//
////////////////////////////////////////////////////////////////////////////

int IsValidNegResult( SPNEGO_NEGRESULT negResult )
{
   return ( negResult >= spnego_negresult_success &&
            negResult <= spnego_negresult_request_mic );
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    IsValidSpnegoToken
//
// Parameters:
//    [in]  pSpnegoToken   -  Points to SPNEGO_TOKEN data structure
//
// Returns:
//    int   Success - 1
//          Failure - 0
//
// Comments :
//    Performs simple heuristic on location pointed to by pSpnegoToken.
//
////////////////////////////////////////////////////////////////////////////

int IsValidSpnegoToken( SPNEGO_TOKEN* pSpnegoToken )
{
   int   nReturn = 0;

   // Parameter should be non-NULL
   if ( NULL != pSpnegoToken )
   {
      // Length should be at least the size defined in the header
      if ( pSpnegoToken->nStructSize >= SPNEGO_TOKEN_SIZE )
      {
         // Number of elements should be >= our maximum - if it's greater, that's
         // okay, since we'll only be accessing the elements up to MAX_NUM_TOKEN_ELEMENTS
         if ( pSpnegoToken->nNumElements >= MAX_NUM_TOKEN_ELEMENTS )
         {
            // Check for proper token type
            if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ||
               SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType )
            {
               nReturn = 1;
            }
         }

      }  // IF struct size makes sense

   }  // IF non-NULL spnego Token

   return nReturn;
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    IsValidSpnegoElement
//
// Parameters:
//    [in]  pSpnegoToken   -  Points to SPNEGO_TOKEN data structure
//    [in]  spnegoElement  -  spnegoElement Type from enumeration
//
// Returns:
//    int   Success - 1
//          Failure - 0
//
// Comments :
//    Checks that spnegoElement has a valid value and is appropriate for
//    the SPNEGO token encapsulated by pSpnegoToken.
//
////////////////////////////////////////////////////////////////////////////

int IsValidSpnegoElement( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement )
{
   int   nReturn = 0;

   // Check boundaries
   if ( spnegoElement > spnego_element_min &&
      spnegoElement < spnego_element_max )
   {

      // Check for appropriateness to token type
      if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
      {
         nReturn = ( spnegoElement >= spnego_init_mechtypes &&
                     spnegoElement <= spnego_init_mechListMIC );
      }
      else
      {
         nReturn = ( spnegoElement >= spnego_targ_negResult &&
                     spnegoElement <= spnego_targ_mechListMIC );
      }

   }  // IF boundary conditions are met

   return nReturn;
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    CalculateElementArrayIndex
//
// Parameters:
//    [in]  pSpnegoToken   -  Points to SPNEGO_TOKEN data structure
//    [in]  spnegoElement  -  spnegoElement Type from enumeration
//
// Returns:
//    int   index in the SPNEGO_TOKEN element array that the element can
//          can be found
//
// Comments :
//    Based on the Token Type, calculates the index in the element array
//    at which the specified element can be found.
//
////////////////////////////////////////////////////////////////////////////

int CalculateElementArrayIndex( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement )
{
   int   nReturn = 0;

   // Offset is difference between value and initial element identifier
   // (these differ based on ucTokenType)

   if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
   {
      nReturn = spnegoElement - spnego_init_mechtypes;
   }
   else
   {
      nReturn = spnegoElement - spnego_targ_negResult;
   }

   return nReturn;
}

/////////////////////////////////////////////////////////////////////////////
//
// Function:
//    InitTokenFromBinary
//
// Parameters:
//    [in]  ucCopyData     -  Flag indicating if data should be copied
//    [in]  ulFlags        -  Flags value for structure
//    [in]  pnTokenData    -  Binary Token Data
//    [in]  ulLength       -  Length of the data
//    [out] ppSpnegoToken  -  Pointer to call allocated SPNEGO Token
//                            data structure
//
// Returns:
//    int   Success - SPNEGO_E_SUCCESS
//          Failure - SPNEGO API Error code
//
// Comments :
//    Allocates a SPNEGO_TOKEN data structure and fills it out as
//    appropriate based in the flags passed into the function.
//
////////////////////////////////////////////////////////////////////////////


// Initializes SPNEGO_TOKEN structure from DER encoded binary data
int InitTokenFromBinary( unsigned char ucCopyData, unsigned long ulFlags,
                        unsigned char* pbTokenData, unsigned long ulLength,
                        SPNEGO_TOKEN** ppSpnegoToken )
{
   int            nReturn = SPNEGO_E_INVALID_PARAMETER;
   SPNEGO_TOKEN*  pSpnegoToken = NULL;
   unsigned char* pbFirstElement = NULL;
   long           nTokenLength = 0L;
   long           nRemainingTokenLength = 0L;

   // Basic Parameter Validation

   if (  NULL != pbTokenData &&
         NULL != ppSpnegoToken &&
         0L != ulLength )
   {

      //
      // Allocate the empty token, then initialize the data structure.
      //

      pSpnegoToken = AllocEmptySpnegoToken( ucCopyData, ulFlags, pbTokenData, ulLength );

      if ( NULL != pSpnegoToken )
      {

         // Copy the binary data locally


         // Initialize the token type
         if ( ( nReturn = InitSpnegoTokenType( pSpnegoToken, &nTokenLength,
                                                &nRemainingTokenLength, &pbFirstElement ) )
                        == SPNEGO_E_SUCCESS )
         {

            // Initialize the element array
            if ( ( nReturn = InitSpnegoTokenElements( pSpnegoToken, pbFirstElement,
                                                      nRemainingTokenLength ) )
                           == SPNEGO_E_SUCCESS )
            {
               *ppSpnegoToken = pSpnegoToken;
            }

         }  // IF Init Token Type

         // Cleanup on error condition
         if ( SPNEGO_E_SUCCESS != nReturn )
         {
            spnegoFreeData( pSpnegoToken );
         }

      }
      else
      {
         nReturn = SPNEGO_E_OUT_OF_MEMORY;
      }

   }  // IF Valid parameters


   return nReturn;
}