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
/*
 * PROJECT:     Local Security Authority Server DLL
 * LICENSE:     GPL - See COPYING in the top level directory
 * FILE:        dll/win32/lsasrv/authpackage.c
 * PURPOSE:     Authentication package management routines
 * COPYRIGHT:   Copyright 2013 Eric Kohl
 */

#include "lsasrv.h"

#include <ndk/sefuncs.h>
#include <ndk/umfuncs.h>

typedef enum _LSA_TOKEN_INFORMATION_TYPE
{
    LsaTokenInformationNull,
    LsaTokenInformationV1
} LSA_TOKEN_INFORMATION_TYPE, *PLSA_TOKEN_INFORMATION_TYPE;

typedef struct _LSA_TOKEN_INFORMATION_NULL
{
    LARGE_INTEGER ExpirationTime;
    PTOKEN_GROUPS Groups;
} LSA_TOKEN_INFORMATION_NULL, *PLSA_TOKEN_INFORMATION_NULL;

typedef struct _LSA_TOKEN_INFORMATION_V1
{
    LARGE_INTEGER ExpirationTime;
    TOKEN_USER User;
    PTOKEN_GROUPS Groups;
    TOKEN_PRIMARY_GROUP PrimaryGroup;
    PTOKEN_PRIVILEGES Privileges;
    TOKEN_OWNER Owner;
    TOKEN_DEFAULT_DACL DefaultDacl;
} LSA_TOKEN_INFORMATION_V1, *PLSA_TOKEN_INFORMATION_V1;

typedef PVOID PLSA_CLIENT_REQUEST;

typedef NTSTATUS (NTAPI *PLSA_CREATE_LOGON_SESSION)(PLUID);
typedef NTSTATUS (NTAPI *PLSA_DELETE_LOGON_SESSION)(PLUID);
typedef NTSTATUS (NTAPI *PLSA_ADD_CREDENTIAL)(PLUID, ULONG, PLSA_STRING, PLSA_STRING);
typedef NTSTATUS (NTAPI *PLSA_GET_CREDENTIALS)(PLUID, ULONG, PULONG, BOOLEAN, PLSA_STRING, PULONG, PLSA_STRING);
typedef NTSTATUS (NTAPI *PLSA_DELETE_CREDENTIAL)(PLUID, ULONG, PLSA_STRING);
typedef PVOID (NTAPI *PLSA_ALLOCATE_LSA_HEAP)(ULONG);
typedef VOID (NTAPI *PLSA_FREE_LSA_HEAP)(PVOID);
typedef NTSTATUS (NTAPI *PLSA_ALLOCATE_CLIENT_BUFFER)(PLSA_CLIENT_REQUEST, ULONG, PVOID*);
typedef NTSTATUS (NTAPI *PLSA_FREE_CLIENT_BUFFER)(PLSA_CLIENT_REQUEST, PVOID);
typedef NTSTATUS (NTAPI *PLSA_COPY_TO_CLIENT_BUFFER)(PLSA_CLIENT_REQUEST, ULONG,
 PVOID, PVOID);
typedef NTSTATUS (NTAPI *PLSA_COPY_FROM_CLIENT_BUFFER)(PLSA_CLIENT_REQUEST,
 ULONG, PVOID, PVOID);

typedef struct LSA_DISPATCH_TABLE
{
    PLSA_CREATE_LOGON_SESSION CreateLogonSession;
    PLSA_DELETE_LOGON_SESSION DeleteLogonSession;
    PLSA_ADD_CREDENTIAL AddCredential;
    PLSA_GET_CREDENTIALS GetCredentials;
    PLSA_DELETE_CREDENTIAL DeleteCredential;
    PLSA_ALLOCATE_LSA_HEAP AllocateLsaHeap;
    PLSA_FREE_LSA_HEAP FreeLsaHeap;
    PLSA_ALLOCATE_CLIENT_BUFFER AllocateClientBuffer;
    PLSA_FREE_CLIENT_BUFFER FreeClientBuffer;
    PLSA_COPY_TO_CLIENT_BUFFER CopyToClientBuffer;
    PLSA_COPY_FROM_CLIENT_BUFFER CopyFromClientBuffer;
} LSA_DISPATCH_TABLE, *PLSA_DISPATCH_TABLE;


typedef NTSTATUS (NTAPI *PLSA_AP_INITIALIZE_PACKAGE)(ULONG, PLSA_DISPATCH_TABLE,
 PLSA_STRING, PLSA_STRING, PLSA_STRING *);
typedef NTSTATUS (NTAPI *PLSA_AP_CALL_PACKAGE_INTERNAL)(PLSA_CLIENT_REQUEST, PVOID, PVOID,
 ULONG, PVOID *, PULONG, PNTSTATUS);
typedef NTSTATUS (NTAPI *PLSA_AP_CALL_PACKAGE_PASSTHROUGH)(PLSA_CLIENT_REQUEST,
 PVOID, PVOID, ULONG, PVOID *, PULONG, PNTSTATUS);
typedef NTSTATUS (NTAPI *PLSA_AP_CALL_PACKAGE_UNTRUSTED)(PLSA_CLIENT_REQUEST,
 PVOID, PVOID, ULONG, PVOID *, PULONG, PNTSTATUS);
typedef VOID (NTAPI *PLSA_AP_LOGON_TERMINATED)(PLUID);
typedef NTSTATUS (NTAPI *PLSA_AP_LOGON_USER_EX2)(PLSA_CLIENT_REQUEST,
 SECURITY_LOGON_TYPE, PVOID, PVOID, ULONG, PVOID *, PULONG, PLUID, PNTSTATUS,
 PLSA_TOKEN_INFORMATION_TYPE, PVOID *, PUNICODE_STRING *, PUNICODE_STRING *,
 PUNICODE_STRING *, PVOID /*PSECPKG_PRIMARY_CRED*/, PVOID /*PSECPKG_SUPPLEMENTAL_CRED_ARRAY **/);
typedef NTSTATUS (NTAPI *PLSA_AP_LOGON_USER_EX)(PLSA_CLIENT_REQUEST,
 SECURITY_LOGON_TYPE, PVOID, PVOID, ULONG, PVOID *, PULONG, PLUID, PNTSTATUS,
 PLSA_TOKEN_INFORMATION_TYPE, PVOID *, PUNICODE_STRING *, PUNICODE_STRING *,
 PUNICODE_STRING *);

typedef NTSTATUS (NTAPI *PLSA_AP_LOGON_USER_INTERNAL)(PLSA_CLIENT_REQUEST, SECURITY_LOGON_TYPE,
 PVOID, PVOID, ULONG, PVOID *, PULONG, PLUID, PNTSTATUS, PLSA_TOKEN_INFORMATION_TYPE,
 PVOID *, PUNICODE_STRING *, PUNICODE_STRING *);

typedef struct _AUTH_PACKAGE
{
    LIST_ENTRY Entry;
    PSTRING Name;
    ULONG Id;
    PVOID ModuleHandle;

    PLSA_AP_INITIALIZE_PACKAGE LsaApInitializePackage;
    PLSA_AP_CALL_PACKAGE_INTERNAL LsaApCallPackage;
    PLSA_AP_CALL_PACKAGE_PASSTHROUGH LsaApCallPackagePassthrough;
    PLSA_AP_CALL_PACKAGE_UNTRUSTED LsaApCallPackageUntrusted;
    PLSA_AP_LOGON_TERMINATED LsaApLogonTerminated;
    PLSA_AP_LOGON_USER_EX2 LsaApLogonUserEx2;
    PLSA_AP_LOGON_USER_EX LsaApLogonUserEx;
    PLSA_AP_LOGON_USER_INTERNAL LsaApLogonUser;
} AUTH_PACKAGE, *PAUTH_PACKAGE;

VOID
NTAPI
LsaIFree_LSAPR_PRIVILEGE_SET(IN PLSAPR_PRIVILEGE_SET Ptr);

typedef wchar_t *PSAMPR_SERVER_NAME;
typedef void *SAMPR_HANDLE;

typedef struct _SAMPR_SID_INFORMATION
{
    PRPC_SID SidPointer;
} SAMPR_SID_INFORMATION, *PSAMPR_SID_INFORMATION;

typedef struct _SAMPR_PSID_ARRAY
{
    unsigned long Count;
    PSAMPR_SID_INFORMATION Sids;
} SAMPR_PSID_ARRAY, *PSAMPR_PSID_ARRAY;

NTSTATUS
NTAPI
SamIConnect(
    PSAMPR_SERVER_NAME ServerName,
    SAMPR_HANDLE *ServerHandle,
    ACCESS_MASK DesiredAccess,
    BOOLEAN Trusted);

VOID
NTAPI
SamIFree_SAMPR_ULONG_ARRAY(
    PSAMPR_ULONG_ARRAY Ptr);

NTSTATUS
__stdcall
SamrCloseHandle(
    SAMPR_HANDLE *SamHandle);

NTSTATUS
__stdcall
SamrOpenDomain(
    SAMPR_HANDLE ServerHandle,
    ACCESS_MASK DesiredAccess,
    PRPC_SID DomainId,
    SAMPR_HANDLE *DomainHandle);

NTSTATUS
__stdcall
SamrGetAliasMembership(
    SAMPR_HANDLE DomainHandle,
    PSAMPR_PSID_ARRAY SidArray,
    PSAMPR_ULONG_ARRAY Membership);


/* GLOBALS *****************************************************************/

static LIST_ENTRY PackageListHead;
static ULONG PackageId;
static LSA_DISPATCH_TABLE DispatchTable;

#define CONST_LUID(x1, x2) {x1, x2}
static const LUID SeChangeNotifyPrivilege = CONST_LUID(SE_CHANGE_NOTIFY_PRIVILEGE, 0);
static const LUID SeCreateGlobalPrivilege = CONST_LUID(SE_CREATE_GLOBAL_PRIVILEGE, 0);
static const LUID SeImpersonatePrivilege = CONST_LUID(SE_IMPERSONATE_PRIVILEGE, 0);


/* FUNCTIONS ***************************************************************/

static
NTSTATUS
NTAPI
LsapAddAuthPackage(IN PWSTR ValueName,
                   IN ULONG ValueType,
                   IN PVOID ValueData,
                   IN ULONG ValueLength,
                   IN PVOID Context,
                   IN PVOID EntryContext)
{
    PAUTH_PACKAGE Package = NULL;
    UNICODE_STRING PackageName;
    STRING ProcName;
    PULONG Id;
    NTSTATUS Status = STATUS_SUCCESS;

    TRACE("LsapAddAuthPackage()\n");

    PackageName.Length = (USHORT)ValueLength - sizeof(WCHAR);
    PackageName.MaximumLength = (USHORT)ValueLength;
    PackageName.Buffer = ValueData;

    Id = (PULONG)Context;

    Package = RtlAllocateHeap(RtlGetProcessHeap(),
                                  HEAP_ZERO_MEMORY,
                                  sizeof(AUTH_PACKAGE));
    if (Package == NULL)
        return STATUS_INSUFFICIENT_RESOURCES;

    Status = LdrLoadDll(NULL,
                        NULL,
                        &PackageName,
                        &Package->ModuleHandle);
    if (!NT_SUCCESS(Status))
    {
        TRACE("LdrLoadDll failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    RtlInitAnsiString(&ProcName, "LsaApInitializePackage");
    Status = LdrGetProcedureAddress(Package->ModuleHandle,
                                    &ProcName,
                                    0,
                                    (PVOID *)&Package->LsaApInitializePackage);
    if (!NT_SUCCESS(Status))
    {
        TRACE("LdrGetProcedureAddress() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    RtlInitAnsiString(&ProcName, "LsaApCallPackage");
    Status = LdrGetProcedureAddress(Package->ModuleHandle,
                                    &ProcName,
                                    0,
                                    (PVOID *)&Package->LsaApCallPackage);
    if (!NT_SUCCESS(Status))
    {
        TRACE("LdrGetProcedureAddress() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    RtlInitAnsiString(&ProcName, "LsaApCallPackagePassthrough");
    Status = LdrGetProcedureAddress(Package->ModuleHandle,
                                    &ProcName,
                                    0,
                                    (PVOID *)&Package->LsaApCallPackagePassthrough);
    if (!NT_SUCCESS(Status))
    {
        TRACE("LdrGetProcedureAddress() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    RtlInitAnsiString(&ProcName, "LsaApCallPackageUntrusted");
    Status = LdrGetProcedureAddress(Package->ModuleHandle,
                                    &ProcName,
                                    0,
                                    (PVOID *)&Package->LsaApCallPackageUntrusted);
    if (!NT_SUCCESS(Status))
    {
        TRACE("LdrGetProcedureAddress() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    RtlInitAnsiString(&ProcName, "LsaApLogonTerminated");
    Status = LdrGetProcedureAddress(Package->ModuleHandle,
                                    &ProcName,
                                    0,
                                    (PVOID *)&Package->LsaApLogonTerminated);
    if (!NT_SUCCESS(Status))
    {
        TRACE("LdrGetProcedureAddress() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    RtlInitAnsiString(&ProcName, "LsaApLogonUserEx2");
    Status = LdrGetProcedureAddress(Package->ModuleHandle,
                                    &ProcName,
                                    0,
                                    (PVOID *)&Package->LsaApLogonUserEx2);
    if (!NT_SUCCESS(Status))
    {
        RtlInitAnsiString(&ProcName, "LsaApLogonUserEx");
        Status = LdrGetProcedureAddress(Package->ModuleHandle,
                                        &ProcName,
                                        0,
                                        (PVOID *)&Package->LsaApLogonUserEx);
        if (!NT_SUCCESS(Status))
        {
            RtlInitAnsiString(&ProcName, "LsaApLogonUser");
            Status = LdrGetProcedureAddress(Package->ModuleHandle,
                                            &ProcName,
                                            0,
                                            (PVOID *)&Package->LsaApLogonUser);
            if (!NT_SUCCESS(Status))
            {
                TRACE("LdrGetProcedureAddress() failed (Status 0x%08lx)\n", Status);
                goto done;
            }
        }
    }

    /* Initialize the current package */
    Status = Package->LsaApInitializePackage(*Id,
                                             &DispatchTable,
                                             NULL,
                                             NULL,
                                             &Package->Name);
    if (!NT_SUCCESS(Status))
    {
        TRACE("Package->LsaApInitializePackage() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    TRACE("Package Name: %s\n", Package->Name->Buffer);

    Package->Id = *Id;
    (*Id)++;

    InsertTailList(&PackageListHead, &Package->Entry);

done:
    if (!NT_SUCCESS(Status))
    {
        if (Package != NULL)
        {
            if (Package->ModuleHandle != NULL)
                LdrUnloadDll(Package->ModuleHandle);

            if (Package->Name != NULL)
            {
                if (Package->Name->Buffer != NULL)
                    RtlFreeHeap(RtlGetProcessHeap(), 0, Package->Name->Buffer);

                RtlFreeHeap(RtlGetProcessHeap(), 0, Package->Name);
            }

            RtlFreeHeap(RtlGetProcessHeap(), 0, Package);
        }
    }

    return Status;
}


static
PAUTH_PACKAGE
LsapGetAuthenticationPackage(IN ULONG PackageId)
{
    PLIST_ENTRY ListEntry;
    PAUTH_PACKAGE Package;

    ListEntry = PackageListHead.Flink;
    while (ListEntry != &PackageListHead)
    {
        Package = CONTAINING_RECORD(ListEntry, AUTH_PACKAGE, Entry);

        if (Package->Id == PackageId)
        {
            return Package;
        }

        ListEntry = ListEntry->Flink;
    }

    return NULL;
}


PVOID
NTAPI
LsapAllocateHeap(IN ULONG Length)
{
    return RtlAllocateHeap(RtlGetProcessHeap(), 0, Length);
}


PVOID
NTAPI
LsapAllocateHeapZero(IN ULONG Length)
{
    return RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Length);
}


VOID
NTAPI
LsapFreeHeap(IN PVOID Base)
{
    RtlFreeHeap(RtlGetProcessHeap(), 0, Base);
}


static
NTSTATUS
NTAPI
LsapAllocateClientBuffer(IN PLSA_CLIENT_REQUEST ClientRequest,
                         IN ULONG LengthRequired,
                         OUT PVOID *ClientBaseAddress)
{
    PLSAP_LOGON_CONTEXT LogonContext;
    SIZE_T Length;

    *ClientBaseAddress = NULL;

    LogonContext = (PLSAP_LOGON_CONTEXT)ClientRequest;

    Length = LengthRequired;
    return NtAllocateVirtualMemory(LogonContext->ClientProcessHandle,
                                   ClientBaseAddress,
                                   0,
                                   &Length,
                                   MEM_COMMIT,
                                   PAGE_READWRITE);
}


static
NTSTATUS
NTAPI
LsapFreeClientBuffer(IN PLSA_CLIENT_REQUEST ClientRequest,
                     IN PVOID ClientBaseAddress)
{
    PLSAP_LOGON_CONTEXT LogonContext;
    SIZE_T Length;

    if (ClientBaseAddress == NULL)
        return STATUS_SUCCESS;

    LogonContext = (PLSAP_LOGON_CONTEXT)ClientRequest;

    Length = 0;
    return NtFreeVirtualMemory(LogonContext->ClientProcessHandle,
                               &ClientBaseAddress,
                               &Length,
                               MEM_RELEASE);
}


static
NTSTATUS
NTAPI
LsapCopyToClientBuffer(IN PLSA_CLIENT_REQUEST ClientRequest,
                       IN ULONG Length,
                       IN PVOID ClientBaseAddress,
                       IN PVOID BufferToCopy)
{
    PLSAP_LOGON_CONTEXT LogonContext;

    LogonContext = (PLSAP_LOGON_CONTEXT)ClientRequest;

    return NtWriteVirtualMemory(LogonContext->ClientProcessHandle,
                                ClientBaseAddress,
                                BufferToCopy,
                                Length,
                                NULL);
}


static
NTSTATUS
NTAPI
LsapCopyFromClientBuffer(IN PLSA_CLIENT_REQUEST ClientRequest,
                         IN ULONG Length,
                         IN PVOID BufferToCopy,
                         IN PVOID ClientBaseAddress)
{
    PLSAP_LOGON_CONTEXT LogonContext;

    LogonContext = (PLSAP_LOGON_CONTEXT)ClientRequest;

    return NtReadVirtualMemory(LogonContext->ClientProcessHandle,
                               ClientBaseAddress,
                               BufferToCopy,
                               Length,
                               NULL);
}


NTSTATUS
LsapInitAuthPackages(VOID)
{
    RTL_QUERY_REGISTRY_TABLE AuthPackageTable[] = {
    {LsapAddAuthPackage, 0, L"Authentication Packages", NULL, REG_NONE, NULL, 0},
    {NULL, 0, NULL, NULL, REG_NONE, NULL, 0}};

    NTSTATUS Status;

    InitializeListHead(&PackageListHead);
    PackageId = 0;

    /* Initialize the dispatch table */
    DispatchTable.CreateLogonSession = &LsapCreateLogonSession;
    DispatchTable.DeleteLogonSession = &LsapDeleteLogonSession;
    DispatchTable.AddCredential = &LsapAddCredential;
    DispatchTable.GetCredentials = &LsapGetCredentials;
    DispatchTable.DeleteCredential = &LsapDeleteCredential;
    DispatchTable.AllocateLsaHeap = &LsapAllocateHeapZero;
    DispatchTable.FreeLsaHeap = &LsapFreeHeap;
    DispatchTable.AllocateClientBuffer = &LsapAllocateClientBuffer;
    DispatchTable.FreeClientBuffer = &LsapFreeClientBuffer;
    DispatchTable.CopyToClientBuffer = &LsapCopyToClientBuffer;
    DispatchTable.CopyFromClientBuffer = &LsapCopyFromClientBuffer;

    /* Add registered authentication packages */
    Status = RtlQueryRegistryValues(RTL_REGISTRY_CONTROL,
                                    L"Lsa",
                                    AuthPackageTable,
                                    &PackageId,
                                    NULL);

    return Status;
}


NTSTATUS
LsapLookupAuthenticationPackage(PLSA_API_MSG RequestMsg,
                                PLSAP_LOGON_CONTEXT LogonContext)
{
    PLIST_ENTRY ListEntry;
    PAUTH_PACKAGE Package;
    ULONG PackageNameLength;
    PCHAR PackageName;

    TRACE("(%p %p)\n", RequestMsg, LogonContext);

    PackageNameLength = RequestMsg->LookupAuthenticationPackage.Request.PackageNameLength;
    PackageName = RequestMsg->LookupAuthenticationPackage.Request.PackageName;

    TRACE("PackageName: %s\n", PackageName);

    ListEntry = PackageListHead.Flink;
    while (ListEntry != &PackageListHead)
    {
        Package = CONTAINING_RECORD(ListEntry, AUTH_PACKAGE, Entry);

        if ((PackageNameLength == Package->Name->Length) &&
            (_strnicmp(PackageName, Package->Name->Buffer, Package->Name->Length) == 0))
        {
            RequestMsg->LookupAuthenticationPackage.Reply.Package = Package->Id;
            return STATUS_SUCCESS;
        }

        ListEntry = ListEntry->Flink;
    }

    return STATUS_NO_SUCH_PACKAGE;
}


NTSTATUS
LsapCallAuthenticationPackage(PLSA_API_MSG RequestMsg,
                              PLSAP_LOGON_CONTEXT LogonContext)
{
    PAUTH_PACKAGE Package;
    PVOID LocalBuffer = NULL;
    ULONG PackageId;
    NTSTATUS Status;

    TRACE("(%p %p)\n", RequestMsg, LogonContext);

    PackageId = RequestMsg->CallAuthenticationPackage.Request.AuthenticationPackage;

    /* Get the right authentication package */
    Package = LsapGetAuthenticationPackage(PackageId);
    if (Package == NULL)
    {
        TRACE("LsapGetAuthenticationPackage() failed to find a package\n");
        return STATUS_NO_SUCH_PACKAGE;
    }

    if (RequestMsg->CallAuthenticationPackage.Request.SubmitBufferLength > 0)
    {
        LocalBuffer = RtlAllocateHeap(RtlGetProcessHeap(),
                                      HEAP_ZERO_MEMORY,
                                      RequestMsg->CallAuthenticationPackage.Request.SubmitBufferLength);
        if (LocalBuffer == NULL)
        {
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        Status = NtReadVirtualMemory(LogonContext->ClientProcessHandle,
                                     RequestMsg->CallAuthenticationPackage.Request.ProtocolSubmitBuffer,
                                     LocalBuffer,
                                     RequestMsg->CallAuthenticationPackage.Request.SubmitBufferLength,
                                     NULL);
        if (!NT_SUCCESS(Status))
        {
            TRACE("NtReadVirtualMemory() failed (Status 0x%08lx)\n", Status);
            RtlFreeHeap(RtlGetProcessHeap(), 0, LocalBuffer);
            return Status;
        }
    }

    if (LogonContext->Untrusted)
        Status = Package->LsaApCallPackageUntrusted((PLSA_CLIENT_REQUEST)LogonContext,
                                                    LocalBuffer,
                                                    RequestMsg->CallAuthenticationPackage.Request.ProtocolSubmitBuffer,
                                                    RequestMsg->CallAuthenticationPackage.Request.SubmitBufferLength,
                                                    &RequestMsg->CallAuthenticationPackage.Reply.ProtocolReturnBuffer,
                                                    &RequestMsg->CallAuthenticationPackage.Reply.ReturnBufferLength,
                                                    &RequestMsg->CallAuthenticationPackage.Reply.ProtocolStatus);
    else
        Status = Package->LsaApCallPackage((PLSA_CLIENT_REQUEST)LogonContext,
                                           LocalBuffer,
                                           RequestMsg->CallAuthenticationPackage.Request.ProtocolSubmitBuffer,
                                           RequestMsg->CallAuthenticationPackage.Request.SubmitBufferLength,
                                           &RequestMsg->CallAuthenticationPackage.Reply.ProtocolReturnBuffer,
                                           &RequestMsg->CallAuthenticationPackage.Reply.ReturnBufferLength,
                                           &RequestMsg->CallAuthenticationPackage.Reply.ProtocolStatus);
    if (!NT_SUCCESS(Status))
    {
        TRACE("Package->LsaApCallPackage() failed (Status 0x%08lx)\n", Status);
    }

    if (LocalBuffer != NULL)
        RtlFreeHeap(RtlGetProcessHeap(), 0, LocalBuffer);

    return Status;
}


static
NTSTATUS
LsapCopyLocalGroups(
    IN PLSAP_LOGON_CONTEXT LogonContext,
    IN PTOKEN_GROUPS ClientGroups,
    IN ULONG ClientGroupsCount,
    OUT PTOKEN_GROUPS *TokenGroups)
{
    ULONG LocalGroupsLength = 0;
    PTOKEN_GROUPS LocalGroups = NULL;
    ULONG SidHeaderLength = 0;
    PSID SidHeader = NULL;
    PSID SrcSid, DstSid;
    ULONG SidLength;
    ULONG AllocatedSids = 0;
    ULONG i;
    NTSTATUS Status;

    LocalGroupsLength = sizeof(TOKEN_GROUPS) +
                        (ClientGroupsCount - ANYSIZE_ARRAY) * sizeof(SID_AND_ATTRIBUTES);
    LocalGroups = RtlAllocateHeap(RtlGetProcessHeap(),
                                  HEAP_ZERO_MEMORY,
                                  LocalGroupsLength);
    if (LocalGroups == NULL)
    {
        TRACE("RtlAllocateHeap() failed\n");
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    Status = NtReadVirtualMemory(LogonContext->ClientProcessHandle,
                                 ClientGroups,
                                 LocalGroups,
                                 LocalGroupsLength,
                                 NULL);
    if (!NT_SUCCESS(Status))
        goto done;


    SidHeaderLength  = RtlLengthRequiredSid(0);
    SidHeader = RtlAllocateHeap(RtlGetProcessHeap(),
                                HEAP_ZERO_MEMORY,
                                SidHeaderLength);
    if (SidHeader == NULL)
    {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto done;
    }

    for (i = 0; i < ClientGroupsCount; i++)
    {
        SrcSid = LocalGroups->Groups[i].Sid;

        Status = NtReadVirtualMemory(LogonContext->ClientProcessHandle,
                                     SrcSid,
                                     SidHeader,
                                     SidHeaderLength,
                                     NULL);
        if (!NT_SUCCESS(Status))
            goto done;

        SidLength = RtlLengthSid(SidHeader);
        TRACE("Sid %lu: Length %lu\n", i, SidLength);

        DstSid = RtlAllocateHeap(RtlGetProcessHeap(),
                                 HEAP_ZERO_MEMORY,
                                 SidLength);
        if (DstSid == NULL)
        {
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto done;
        }

        Status = NtReadVirtualMemory(LogonContext->ClientProcessHandle,
                                     SrcSid,
                                     DstSid,
                                     SidLength,
                                     NULL);
        if (!NT_SUCCESS(Status))
        {
            RtlFreeHeap(RtlGetProcessHeap(), 0, DstSid);
            goto done;
        }

        LocalGroups->Groups[i].Sid = DstSid;
        AllocatedSids++;
    }

    *TokenGroups = LocalGroups;

done:
    if (SidHeader != NULL)
        RtlFreeHeap(RtlGetProcessHeap(), 0, SidHeader);

    if (!NT_SUCCESS(Status))
    {
        if (LocalGroups != NULL)
        {
            for (i = 0; i < AllocatedSids; i++)
                RtlFreeHeap(RtlGetProcessHeap(), 0, LocalGroups->Groups[i].Sid);

            RtlFreeHeap(RtlGetProcessHeap(), 0, LocalGroups);
        }
    }

    return Status;
}


static
NTSTATUS
LsapAddLocalGroups(
    IN PVOID TokenInformation,
    IN LSA_TOKEN_INFORMATION_TYPE TokenInformationType,
    IN PTOKEN_GROUPS LocalGroups)
{
    PLSA_TOKEN_INFORMATION_V1 TokenInfo1;
    PTOKEN_GROUPS Groups;
    ULONG Length;
    ULONG i;
    ULONG j;

    if (LocalGroups == NULL || LocalGroups->GroupCount == 0)
        return STATUS_SUCCESS;

    if (TokenInformationType == LsaTokenInformationV1)
    {
        TokenInfo1 = (PLSA_TOKEN_INFORMATION_V1)TokenInformation;

        if (TokenInfo1->Groups != NULL)
        {
            Length = sizeof(TOKEN_GROUPS) +
                     (LocalGroups->GroupCount + TokenInfo1->Groups->GroupCount - ANYSIZE_ARRAY) * sizeof(SID_AND_ATTRIBUTES);

            Groups = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Length);
            if (Groups == NULL)
            {
                ERR("Group buffer allocation failed!\n");
                return STATUS_INSUFFICIENT_RESOURCES;
            }

            Groups->GroupCount = LocalGroups->GroupCount + TokenInfo1->Groups->GroupCount;

            for (i = 0; i < TokenInfo1->Groups->GroupCount; i++)
            {
                Groups->Groups[i].Sid = TokenInfo1->Groups->Groups[i].Sid;
                Groups->Groups[i].Attributes = TokenInfo1->Groups->Groups[i].Attributes;
            }

            for (j = 0; j < LocalGroups->GroupCount; i++, j++)
            {
                Groups->Groups[i].Sid = LocalGroups->Groups[j].Sid;
                Groups->Groups[i].Attributes = LocalGroups->Groups[j].Attributes;
                LocalGroups->Groups[j].Sid = NULL;
            }

            RtlFreeHeap(RtlGetProcessHeap(), 0, TokenInfo1->Groups);

            TokenInfo1->Groups = Groups;
        }
        else
        {
            Length = sizeof(TOKEN_GROUPS) +
                     (LocalGroups->GroupCount - ANYSIZE_ARRAY) * sizeof(SID_AND_ATTRIBUTES);

            Groups = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Length);
            if (Groups == NULL)
            {
                ERR("Group buffer allocation failed!\n");
                return STATUS_INSUFFICIENT_RESOURCES;
            }

            Groups->GroupCount = LocalGroups->GroupCount;

            for (i = 0; i < LocalGroups->GroupCount; i++)
            {
                Groups->Groups[i].Sid = LocalGroups->Groups[i].Sid;
                Groups->Groups[i].Attributes = LocalGroups->Groups[i].Attributes;
            }

            TokenInfo1->Groups = Groups;
        }
    }
    else
    {
        FIXME("TokenInformationType %d is not supported!\n", TokenInformationType);
        return STATUS_NOT_IMPLEMENTED;
    }

    return STATUS_SUCCESS;
}

static
NTSTATUS
LsapAddDefaultGroups(
    IN PVOID TokenInformation,
    IN LSA_TOKEN_INFORMATION_TYPE TokenInformationType,
    IN SECURITY_LOGON_TYPE LogonType)
{
    PLSA_TOKEN_INFORMATION_V1 TokenInfo1;
    PTOKEN_GROUPS Groups;
    ULONG i, Length;
    PSID SrcSid;

    if (TokenInformationType == LsaTokenInformationV1)
    {
        TokenInfo1 = (PLSA_TOKEN_INFORMATION_V1)TokenInformation;

        if (TokenInfo1->Groups != NULL)
        {
            Length = sizeof(TOKEN_GROUPS) +
                     (TokenInfo1->Groups->GroupCount + 2 - ANYSIZE_ARRAY) * sizeof(SID_AND_ATTRIBUTES);

            Groups = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Length);
            if (Groups == NULL)
            {
                ERR("Group buffer allocation failed!\n");
                return STATUS_INSUFFICIENT_RESOURCES;
            }

            Groups->GroupCount = TokenInfo1->Groups->GroupCount;

            for (i = 0; i < TokenInfo1->Groups->GroupCount; i++)
            {
                Groups->Groups[i].Sid = TokenInfo1->Groups->Groups[i].Sid;
                Groups->Groups[i].Attributes = TokenInfo1->Groups->Groups[i].Attributes;
            }

            RtlFreeHeap(RtlGetProcessHeap(), 0, TokenInfo1->Groups);

            TokenInfo1->Groups = Groups;

        }
        else
        {
            Length = sizeof(TOKEN_GROUPS) +
                     (2 - ANYSIZE_ARRAY) * sizeof(SID_AND_ATTRIBUTES);

            Groups = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Length);
            if (Groups == NULL)
            {
                ERR("Group buffer allocation failed!\n");
                return STATUS_INSUFFICIENT_RESOURCES;
            }

            TokenInfo1->Groups = Groups;
        }

        /* Append the World SID (aka Everyone) */
        Length = RtlLengthSid(LsapWorldSid);
        Groups->Groups[Groups->GroupCount].Sid = RtlAllocateHeap(RtlGetProcessHeap(),
                                                                 HEAP_ZERO_MEMORY,
                                                                 Length);
        if (Groups->Groups[Groups->GroupCount].Sid == NULL)
            return STATUS_INSUFFICIENT_RESOURCES;

        RtlCopyMemory(Groups->Groups[Groups->GroupCount].Sid,
                      LsapWorldSid,
                      Length);

        Groups->Groups[Groups->GroupCount].Attributes =
            SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_MANDATORY;

        Groups->GroupCount++;

        /* Append the logon type SID */
        switch (LogonType)
        {
            case Interactive:
                SrcSid = LsapInteractiveSid;
                break;

            case Network:
                SrcSid = LsapNetworkSid;
                break;

            case Batch:
                SrcSid = LsapBatchSid;
                break;

            case Service:
                SrcSid = LsapServiceSid;
                break;

            default:
                FIXME("LogonType %d is not supported!\n", LogonType);
                return STATUS_NOT_IMPLEMENTED;
        }

        Length = RtlLengthSid(SrcSid);
        Groups->Groups[Groups->GroupCount].Sid = RtlAllocateHeap(RtlGetProcessHeap(),
                                                                 HEAP_ZERO_MEMORY,
                                                                 Length);
        if (Groups->Groups[Groups->GroupCount].Sid == NULL)
            return STATUS_INSUFFICIENT_RESOURCES;

        RtlCopyMemory(Groups->Groups[Groups->GroupCount].Sid,
                      SrcSid,
                      Length);

        Groups->Groups[Groups->GroupCount].Attributes =
            SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_MANDATORY;

        Groups->GroupCount++;
    }
    else
    {
        FIXME("TokenInformationType %d is not supported!\n", TokenInformationType);
        return STATUS_NOT_IMPLEMENTED;
    }

    return STATUS_SUCCESS;
}


static
NTSTATUS
LsapAppendSidToGroups(
    IN PTOKEN_GROUPS *TokenGroups,
    IN PSID DomainSid,
    IN ULONG RelativeId)
{
    PTOKEN_GROUPS Groups;
    PSID Sid;
    ULONG Length;
    ULONG i;

    Sid = LsapAppendRidToSid(DomainSid, RelativeId);
    if (Sid == NULL)
    {
        ERR("Group SID creation failed!\n");
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    if (*TokenGroups == NULL)
    {
        Length = sizeof(TOKEN_GROUPS) +
                 (1 - ANYSIZE_ARRAY) * sizeof(SID_AND_ATTRIBUTES);

        Groups = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Length);
        if (Groups == NULL)
        {
            ERR("Group buffer allocation failed!\n");
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        Groups->GroupCount = 1;

        Groups->Groups[0].Sid = Sid;
        Groups->Groups[0].Attributes =
            SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_MANDATORY;

        *TokenGroups = Groups;
    }
    else
    {
        for (i = 0; i < (*TokenGroups)->GroupCount; i++)
        {
            if (RtlEqualSid((*TokenGroups)->Groups[i].Sid, Sid))
            {
                RtlFreeHeap(RtlGetProcessHeap(), 0, Sid);
                return STATUS_SUCCESS;
            }
        }

        Length = sizeof(TOKEN_GROUPS) +
                 ((*TokenGroups)->GroupCount + 1 - ANYSIZE_ARRAY) * sizeof(SID_AND_ATTRIBUTES);

        Groups = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Length);
        if (Groups == NULL)
        {
            ERR("Group buffer allocation failed!\n");
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        Groups->GroupCount = (*TokenGroups)->GroupCount;

        for (i = 0; i < (*TokenGroups)->GroupCount; i++)
        {
            Groups->Groups[i].Sid = (*TokenGroups)->Groups[i].Sid;
            Groups->Groups[i].Attributes = (*TokenGroups)->Groups[i].Attributes;
        }

        Groups->Groups[Groups->GroupCount].Sid = Sid;
        Groups->Groups[Groups->GroupCount].Attributes =
            SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_MANDATORY;

        Groups->GroupCount++;

        RtlFreeHeap(RtlGetProcessHeap(), 0, *TokenGroups);

        *TokenGroups = Groups;
    }

    return STATUS_SUCCESS;
}


static
NTSTATUS
LsapAddSamGroups(
    IN PVOID TokenInformation,
    IN LSA_TOKEN_INFORMATION_TYPE TokenInformationType)
{
    PLSA_TOKEN_INFORMATION_V1 TokenInfo1;
    SAMPR_HANDLE ServerHandle = NULL;
    SAMPR_HANDLE BuiltinDomainHandle = NULL;
    SAMPR_HANDLE AccountDomainHandle = NULL;
    SAMPR_PSID_ARRAY SidArray;
    SAMPR_ULONG_ARRAY BuiltinMembership;
    SAMPR_ULONG_ARRAY AccountMembership;
    ULONG i;
    NTSTATUS Status = STATUS_SUCCESS;

    if (TokenInformationType != LsaTokenInformationV1)
        return STATUS_SUCCESS;

    TokenInfo1 = (PLSA_TOKEN_INFORMATION_V1)TokenInformation;

    SidArray.Count = TokenInfo1->Groups->GroupCount + 1;
    SidArray.Sids = RtlAllocateHeap(RtlGetProcessHeap(),
                                    HEAP_ZERO_MEMORY,
                                    (TokenInfo1->Groups->GroupCount + 1) * sizeof(PRPC_SID));
    if (SidArray.Sids == NULL)
        return STATUS_INSUFFICIENT_RESOURCES;

    SidArray.Sids[0].SidPointer = TokenInfo1->User.User.Sid;
    for (i = 0; i < TokenInfo1->Groups->GroupCount; i++)
        SidArray.Sids[i + 1].SidPointer = TokenInfo1->Groups->Groups[i].Sid;

    BuiltinMembership.Element = NULL;
    AccountMembership.Element = NULL;

    Status = SamIConnect(NULL,
                         &ServerHandle,
                         SAM_SERVER_CONNECT | SAM_SERVER_LOOKUP_DOMAIN,
                         FALSE);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamIConnect failed (Status %08lx)\n", Status);
        goto done;
    }

    Status = SamrOpenDomain(ServerHandle,
                            DOMAIN_GET_ALIAS_MEMBERSHIP,
                            BuiltinDomainSid,
                            &BuiltinDomainHandle);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrOpenDomain failed (Status %08lx)\n", Status);
        goto done;
    }

    Status = SamrOpenDomain(ServerHandle,
                            DOMAIN_GET_ALIAS_MEMBERSHIP,
                            AccountDomainSid,
                            &AccountDomainHandle);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrOpenDomain failed (Status %08lx)\n", Status);
        goto done;
    }

    Status = SamrGetAliasMembership(BuiltinDomainHandle,
                                    &SidArray,
                                    &BuiltinMembership);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrGetAliasMembership failed (Status %08lx)\n", Status);
        goto done;
    }

    Status = SamrGetAliasMembership(AccountDomainHandle,
                                    &SidArray,
                                    &AccountMembership);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrGetAliasMembership failed (Status %08lx)\n", Status);
        goto done;
    }

    TRACE("Builtin Memberships: %lu\n", BuiltinMembership.Count);
    for (i = 0; i < BuiltinMembership.Count; i++)
    {
        TRACE("RID %lu: %lu (0x%lx)\n", i, BuiltinMembership.Element[i], BuiltinMembership.Element[i]);
        Status = LsapAppendSidToGroups(&TokenInfo1->Groups,
                                       BuiltinDomainSid,
                                       BuiltinMembership.Element[i]);
        if (!NT_SUCCESS(Status))
        {
            TRACE("LsapAppendSidToGroups failed (Status %08lx)\n", Status);
            goto done;
        }
    }

    TRACE("Account Memberships: %lu\n", AccountMembership.Count);
    for (i = 0; i < AccountMembership.Count; i++)
    {
        TRACE("RID %lu: %lu (0x%lx)\n", i, AccountMembership.Element[i], AccountMembership.Element[i]);
        Status = LsapAppendSidToGroups(&TokenInfo1->Groups,
                                       AccountDomainSid,
                                       AccountMembership.Element[i]);
        if (!NT_SUCCESS(Status))
        {
            TRACE("LsapAppendSidToGroups failed (Status %08lx)\n", Status);
            goto done;
        }
    }

done:
    RtlFreeHeap(RtlGetProcessHeap(), 0, SidArray.Sids);

    if (AccountMembership.Element != NULL)
        SamIFree_SAMPR_ULONG_ARRAY(&AccountMembership);

    if (BuiltinMembership.Element != NULL)
        SamIFree_SAMPR_ULONG_ARRAY(&BuiltinMembership);

    if (AccountDomainHandle != NULL)
        SamrCloseHandle(&AccountDomainHandle);

    if (BuiltinDomainHandle != NULL)
        SamrCloseHandle(&BuiltinDomainHandle);

    if (ServerHandle != NULL)
        SamrCloseHandle(&ServerHandle);

//    return Status;

    return STATUS_SUCCESS;
}


static
NTSTATUS
LsapSetTokenOwner(
    IN PVOID TokenInformation,
    IN LSA_TOKEN_INFORMATION_TYPE TokenInformationType)
{
    PLSA_TOKEN_INFORMATION_V1 TokenInfo1;
    PSID_AND_ATTRIBUTES OwnerSid = NULL;
    ULONG i, Length;

    if (TokenInformationType == LsaTokenInformationV1)
    {
        TokenInfo1 = (PLSA_TOKEN_INFORMATION_V1)TokenInformation;

        if (TokenInfo1->Owner.Owner != NULL)
            return STATUS_SUCCESS;

        OwnerSid = &TokenInfo1->User.User;
        for (i = 0; i < TokenInfo1->Groups->GroupCount; i++)
        {
            if (EqualSid(TokenInfo1->Groups->Groups[i].Sid, LsapAdministratorsSid))
            {
                OwnerSid = &TokenInfo1->Groups->Groups[i];
                break;
            }
        }

        Length = RtlLengthSid(OwnerSid->Sid);
        TokenInfo1->Owner.Owner = DispatchTable.AllocateLsaHeap(Length);
        if (TokenInfo1->Owner.Owner == NULL)
            return STATUS_INSUFFICIENT_RESOURCES;

        RtlCopyMemory(TokenInfo1->Owner.Owner,
                      OwnerSid->Sid,
                      Length);
        OwnerSid->Attributes |= SE_GROUP_OWNER;
    }

    return STATUS_SUCCESS;
}


static
NTSTATUS
LsapAddTokenDefaultDacl(
    IN PVOID TokenInformation,
    IN LSA_TOKEN_INFORMATION_TYPE TokenInformationType)
{
    PLSA_TOKEN_INFORMATION_V1 TokenInfo1;
    PACL Dacl = NULL;
    ULONG Length;

    if (TokenInformationType == LsaTokenInformationV1)
    {
        TokenInfo1 = (PLSA_TOKEN_INFORMATION_V1)TokenInformation;

        if (TokenInfo1->DefaultDacl.DefaultDacl != NULL)
            return STATUS_SUCCESS;

        Length = sizeof(ACL) +
                 (2 * sizeof(ACCESS_ALLOWED_ACE)) +
                 RtlLengthSid(TokenInfo1->Owner.Owner) +
                 RtlLengthSid(LsapLocalSystemSid);

        Dacl = DispatchTable.AllocateLsaHeap(Length);
        if (Dacl == NULL)
            return STATUS_INSUFFICIENT_RESOURCES;

        RtlCreateAcl(Dacl, Length, ACL_REVISION);

        RtlAddAccessAllowedAce(Dacl,
                               ACL_REVISION,
                               GENERIC_ALL,
                               TokenInfo1->Owner.Owner);

        /* SID: S-1-5-18 */
        RtlAddAccessAllowedAce(Dacl,
                               ACL_REVISION,
                               GENERIC_ALL,
                               LsapLocalSystemSid);

        TokenInfo1->DefaultDacl.DefaultDacl = Dacl;
    }

    return STATUS_SUCCESS;
}


static
NTSTATUS
LsapAddPrivilegeToTokenPrivileges(PTOKEN_PRIVILEGES *TokenPrivileges,
                                  PLSAPR_LUID_AND_ATTRIBUTES Privilege)
{
    PTOKEN_PRIVILEGES LocalPrivileges;
    ULONG Length, TokenPrivilegeCount, i;
    NTSTATUS Status = STATUS_SUCCESS;

    if (*TokenPrivileges == NULL)
    {
        Length = sizeof(TOKEN_PRIVILEGES) +
                 (1 - ANYSIZE_ARRAY) * sizeof(LUID_AND_ATTRIBUTES);
        LocalPrivileges = RtlAllocateHeap(RtlGetProcessHeap(),
                                          0,
                                          Length);
        if (LocalPrivileges == NULL)
            return STATUS_INSUFFICIENT_RESOURCES;

        LocalPrivileges->PrivilegeCount = 1;
        LocalPrivileges->Privileges[0].Luid = Privilege->Luid;
        LocalPrivileges->Privileges[0].Attributes = Privilege->Attributes;
    }
    else
    {
        TokenPrivilegeCount = (*TokenPrivileges)->PrivilegeCount;

        for (i = 0; i < TokenPrivilegeCount; i++)
        {
            if (RtlEqualLuid(&(*TokenPrivileges)->Privileges[i].Luid, &Privilege->Luid))
                return STATUS_SUCCESS;
        }

        Length = sizeof(TOKEN_PRIVILEGES) +
                 (TokenPrivilegeCount + 1 - ANYSIZE_ARRAY) * sizeof(LUID_AND_ATTRIBUTES);
        LocalPrivileges = RtlAllocateHeap(RtlGetProcessHeap(),
                                          0,
                                          Length);
        if (LocalPrivileges == NULL)
            return STATUS_INSUFFICIENT_RESOURCES;

        LocalPrivileges->PrivilegeCount = TokenPrivilegeCount + 1;
        for (i = 0; i < TokenPrivilegeCount; i++)
        {
            LocalPrivileges->Privileges[i].Luid = (*TokenPrivileges)->Privileges[i].Luid;
            LocalPrivileges->Privileges[i].Attributes = (*TokenPrivileges)->Privileges[i].Attributes;
        }

        LocalPrivileges->Privileges[TokenPrivilegeCount].Luid = Privilege->Luid;
        LocalPrivileges->Privileges[TokenPrivilegeCount].Attributes = Privilege->Attributes;

        RtlFreeHeap(RtlGetProcessHeap(), 0, *TokenPrivileges);
    }

    *TokenPrivileges = LocalPrivileges;

    return Status;
}

static
NTSTATUS
LsapSetPrivileges(
    IN PVOID TokenInformation,
    IN LSA_TOKEN_INFORMATION_TYPE TokenInformationType)
{
    PLSA_TOKEN_INFORMATION_V1 TokenInfo1;
    LSAPR_HANDLE PolicyHandle = NULL;
    LSAPR_HANDLE AccountHandle = NULL;
    PLSAPR_PRIVILEGE_SET Privileges = NULL;
    ULONG i, j;
    NTSTATUS Status;

    if (TokenInformationType == LsaTokenInformationV1)
    {
        TokenInfo1 = (PLSA_TOKEN_INFORMATION_V1)TokenInformation;

        Status = LsarOpenPolicy(NULL,
                                NULL,
                                0,
                                &PolicyHandle);
        if (!NT_SUCCESS(Status))
            return Status;

        for (i = 0; i < TokenInfo1->Groups->GroupCount; i++)
        {
            Status = LsarOpenAccount(PolicyHandle,
                                     TokenInfo1->Groups->Groups[i].Sid,
                                     ACCOUNT_VIEW,
                                     &AccountHandle);
            if (!NT_SUCCESS(Status))
                continue;

            Status = LsarEnumeratePrivilegesAccount(AccountHandle,
                                                    &Privileges);
            if (NT_SUCCESS(Status))
            {
                for (j = 0; j < Privileges->PrivilegeCount; j++)
                {
                    Status = LsapAddPrivilegeToTokenPrivileges(&TokenInfo1->Privileges,
                                                               &(Privileges->Privilege[j]));
                    if (!NT_SUCCESS(Status))
                    {
                        /* We failed, clean everything and return */
                        LsaIFree_LSAPR_PRIVILEGE_SET(Privileges);
                        LsarClose(&AccountHandle);
                        LsarClose(&PolicyHandle);

                        return Status;
                    }
                }

                LsaIFree_LSAPR_PRIVILEGE_SET(Privileges);
                Privileges = NULL;
            }

            LsarClose(&AccountHandle);
        }

        LsarClose(&PolicyHandle);

        if (TokenInfo1->Privileges != NULL)
        {
            for (i = 0; i < TokenInfo1->Privileges->PrivilegeCount; i++)
            {
                if (RtlEqualLuid(&TokenInfo1->Privileges->Privileges[i].Luid, &SeChangeNotifyPrivilege) ||
                    RtlEqualLuid(&TokenInfo1->Privileges->Privileges[i].Luid, &SeCreateGlobalPrivilege) ||
                    RtlEqualLuid(&TokenInfo1->Privileges->Privileges[i].Luid, &SeImpersonatePrivilege))
                {
                    TokenInfo1->Privileges->Privileges[i].Attributes |= SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_ENABLED_BY_DEFAULT;
                }
            }
        }
    }

    return STATUS_SUCCESS;
}


NTSTATUS
LsapLogonUser(PLSA_API_MSG RequestMsg,
              PLSAP_LOGON_CONTEXT LogonContext)
{
    PAUTH_PACKAGE Package;
    OBJECT_ATTRIBUTES ObjectAttributes;
    SECURITY_QUALITY_OF_SERVICE Qos;
    LSA_TOKEN_INFORMATION_TYPE TokenInformationType;
    PVOID TokenInformation = NULL;
    PLSA_TOKEN_INFORMATION_NULL TokenInfo0 = NULL;
    PLSA_TOKEN_INFORMATION_V1 TokenInfo1 = NULL;
    PUNICODE_STRING AccountName = NULL;
    PUNICODE_STRING AuthenticatingAuthority = NULL;
    PUNICODE_STRING MachineName = NULL;
    PVOID LocalAuthInfo = NULL;
    PTOKEN_GROUPS LocalGroups = NULL;
    HANDLE TokenHandle = NULL;
    ULONG i;
    ULONG PackageId;
    SECURITY_LOGON_TYPE LogonType;
    NTSTATUS Status;

    PUNICODE_STRING UserName = NULL;
    PUNICODE_STRING LogonDomainName = NULL;
//    UNICODE_STRING LogonServer;


    TRACE("LsapLogonUser(%p %p)\n", RequestMsg, LogonContext);

    PackageId = RequestMsg->LogonUser.Request.AuthenticationPackage;
    LogonType = RequestMsg->LogonUser.Request.LogonType;

    /* Get the right authentication package */
    Package = LsapGetAuthenticationPackage(PackageId);
    if (Package == NULL)
    {
        ERR("LsapGetAuthenticationPackage() failed to find a package\n");
        return STATUS_NO_SUCH_PACKAGE;
    }

    if (RequestMsg->LogonUser.Request.AuthenticationInformationLength > 0)
    {
        /* Allocate the local authentication info buffer */
        LocalAuthInfo = RtlAllocateHeap(RtlGetProcessHeap(),
                                        HEAP_ZERO_MEMORY,
                                        RequestMsg->LogonUser.Request.AuthenticationInformationLength);
        if (LocalAuthInfo == NULL)
        {
            ERR("RtlAllocateHeap() failed\n");
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        /* Read the authentication info from the callers address space */
        Status = NtReadVirtualMemory(LogonContext->ClientProcessHandle,
                                     RequestMsg->LogonUser.Request.AuthenticationInformation,
                                     LocalAuthInfo,
                                     RequestMsg->LogonUser.Request.AuthenticationInformationLength,
                                     NULL);
        if (!NT_SUCCESS(Status))
        {
            ERR("NtReadVirtualMemory() failed (Status 0x%08lx)\n", Status);
            RtlFreeHeap(RtlGetProcessHeap(), 0, LocalAuthInfo);
            return Status;
        }
    }

    if (RequestMsg->LogonUser.Request.LocalGroupsCount > 0)
    {
        Status = LsapCopyLocalGroups(LogonContext,
                                     RequestMsg->LogonUser.Request.LocalGroups,
                                     RequestMsg->LogonUser.Request.LocalGroupsCount,
                                     &LocalGroups);
        if (!NT_SUCCESS(Status))
        {
            ERR("LsapCopyLocalGroups failed (Status 0x%08lx)\n", Status);
            goto done;
        }

        TRACE("GroupCount: %lu\n", LocalGroups->GroupCount);
    }

    if (Package->LsaApLogonUserEx2 != NULL)
    {
        Status = Package->LsaApLogonUserEx2((PLSA_CLIENT_REQUEST)LogonContext,
                                            RequestMsg->LogonUser.Request.LogonType,
                                            LocalAuthInfo,
                                            RequestMsg->LogonUser.Request.AuthenticationInformation,
                                            RequestMsg->LogonUser.Request.AuthenticationInformationLength,
                                            &RequestMsg->LogonUser.Reply.ProfileBuffer,
                                            &RequestMsg->LogonUser.Reply.ProfileBufferLength,
                                            &RequestMsg->LogonUser.Reply.LogonId,
                                            &RequestMsg->LogonUser.Reply.SubStatus,
                                            &TokenInformationType,
                                            &TokenInformation,
                                            &AccountName,
                                            &AuthenticatingAuthority,
                                            &MachineName,
                                            NULL,  /* FIXME: PSECPKG_PRIMARY_CRED PrimaryCredentials */
                                            NULL); /* FIXME: PSECPKG_SUPPLEMENTAL_CRED_ARRAY *SupplementalCredentials */
    }
    else if (Package->LsaApLogonUserEx != NULL)
    {
        Status = Package->LsaApLogonUserEx((PLSA_CLIENT_REQUEST)LogonContext,
                                           RequestMsg->LogonUser.Request.LogonType,
                                           LocalAuthInfo,
                                           RequestMsg->LogonUser.Request.AuthenticationInformation,
                                           RequestMsg->LogonUser.Request.AuthenticationInformationLength,
                                           &RequestMsg->LogonUser.Reply.ProfileBuffer,
                                           &RequestMsg->LogonUser.Reply.ProfileBufferLength,
                                           &RequestMsg->LogonUser.Reply.LogonId,
                                           &RequestMsg->LogonUser.Reply.SubStatus,
                                           &TokenInformationType,
                                           &TokenInformation,
                                           &AccountName,
                                           &AuthenticatingAuthority,
                                           &MachineName);
    }
    else
    {
        Status = Package->LsaApLogonUser((PLSA_CLIENT_REQUEST)LogonContext,
                                         RequestMsg->LogonUser.Request.LogonType,
                                         LocalAuthInfo,
                                         RequestMsg->LogonUser.Request.AuthenticationInformation,
                                         RequestMsg->LogonUser.Request.AuthenticationInformationLength,
                                         &RequestMsg->LogonUser.Reply.ProfileBuffer,
                                         &RequestMsg->LogonUser.Reply.ProfileBufferLength,
                                         &RequestMsg->LogonUser.Reply.LogonId,
                                         &RequestMsg->LogonUser.Reply.SubStatus,
                                         &TokenInformationType,
                                         &TokenInformation,
                                         &AccountName,
                                         &AuthenticatingAuthority);
    }

    if (!NT_SUCCESS(Status))
    {
        ERR("LsaApLogonUser/Ex/2 failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    if (LocalGroups->GroupCount > 0)
    {
        /* Add local groups to the token information */
        Status = LsapAddLocalGroups(TokenInformation,
                                    TokenInformationType,
                                    LocalGroups);
        if (!NT_SUCCESS(Status))
        {
            ERR("LsapAddLocalGroupsToTokenInfo() failed (Status 0x%08lx)\n", Status);
            goto done;
        }
    }

    Status = LsapAddDefaultGroups(TokenInformation,
                                  TokenInformationType,
                                  LogonType);
    if (!NT_SUCCESS(Status))
    {
        ERR("LsapAddDefaultGroups() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    Status = LsapAddSamGroups(TokenInformation,
                              TokenInformationType);
    if (!NT_SUCCESS(Status))
    {
        ERR("LsapAddSamGroups() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    Status = LsapSetTokenOwner(TokenInformation,
                               TokenInformationType);
    if (!NT_SUCCESS(Status))
    {
        ERR("LsapSetTokenOwner() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    Status = LsapAddTokenDefaultDacl(TokenInformation,
                                     TokenInformationType);
    if (!NT_SUCCESS(Status))
    {
        ERR("LsapAddTokenDefaultDacl() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    Status = LsapSetPrivileges(TokenInformation,
                               TokenInformationType);
    if (!NT_SUCCESS(Status))
    {
        ERR("LsapSetPrivileges() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    if (TokenInformationType == LsaTokenInformationNull)
    {
        TOKEN_USER TokenUser;
        TOKEN_PRIMARY_GROUP TokenPrimaryGroup;
        TOKEN_GROUPS NoGroups = {0};
        TOKEN_PRIVILEGES NoPrivileges = {0};

        TokenInfo0 = (PLSA_TOKEN_INFORMATION_NULL)TokenInformation;

        TokenUser.User.Sid = LsapWorldSid;
        TokenUser.User.Attributes = 0;
        TokenPrimaryGroup.PrimaryGroup = LsapWorldSid;

        Qos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
        Qos.ImpersonationLevel = SecurityImpersonation;
        Qos.ContextTrackingMode = SECURITY_STATIC_TRACKING;
        Qos.EffectiveOnly = TRUE;

        ObjectAttributes.Length = sizeof(OBJECT_ATTRIBUTES);
        ObjectAttributes.RootDirectory = NULL;
        ObjectAttributes.ObjectName = NULL;
        ObjectAttributes.Attributes = 0;
        ObjectAttributes.SecurityDescriptor = NULL;
        ObjectAttributes.SecurityQualityOfService = &Qos;

        /* Create the logon token */
        Status = NtCreateToken(&TokenHandle,<--- Status is assigned
                               TOKEN_ALL_ACCESS,
                               &ObjectAttributes,
                               TokenImpersonation,
                               &RequestMsg->LogonUser.Reply.LogonId,
                               &TokenInfo0->ExpirationTime,
                               &TokenUser,
                               &NoGroups,
                               &NoPrivileges,
                               NULL,
                               &TokenPrimaryGroup,
                               NULL,
                               &RequestMsg->LogonUser.Request.SourceContext);
    }
    else if (TokenInformationType == LsaTokenInformationV1)
    {
        TOKEN_PRIVILEGES NoPrivileges = {0};

        TokenInfo1 = (PLSA_TOKEN_INFORMATION_V1)TokenInformation;

        Qos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
        Qos.ImpersonationLevel = SecurityImpersonation;
        Qos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
        Qos.EffectiveOnly = FALSE;

        ObjectAttributes.Length = sizeof(OBJECT_ATTRIBUTES);
        ObjectAttributes.RootDirectory = NULL;
        ObjectAttributes.ObjectName = NULL;
        ObjectAttributes.Attributes = 0;
        ObjectAttributes.SecurityDescriptor = NULL;
        ObjectAttributes.SecurityQualityOfService = &Qos;

        /* Create the logon token */
        Status = NtCreateToken(&TokenHandle,
                               TOKEN_ALL_ACCESS,
                               &ObjectAttributes,
                               (RequestMsg->LogonUser.Request.LogonType == Network) ? TokenImpersonation : TokenPrimary,
                               &RequestMsg->LogonUser.Reply.LogonId,
                               &TokenInfo1->ExpirationTime,
                               &TokenInfo1->User,
                               TokenInfo1->Groups,
                               TokenInfo1->Privileges ? TokenInfo1->Privileges : &NoPrivileges,
                               &TokenInfo1->Owner,
                               &TokenInfo1->PrimaryGroup,
                               &TokenInfo1->DefaultDacl,
                               &RequestMsg->LogonUser.Request.SourceContext);
        if (!NT_SUCCESS(Status))
        {
            ERR("NtCreateToken failed (Status 0x%08lx)\n", Status);
            goto done;
        }
    }
    else
    {
        FIXME("TokenInformationType %d is not supported!\n", TokenInformationType);
        Status = STATUS_NOT_IMPLEMENTED;
        goto done;
    }

    if (LogonType == Interactive ||
        LogonType == Batch ||
        LogonType == Service)
    {
        UserName = &((PMSV1_0_INTERACTIVE_LOGON)LocalAuthInfo)->UserName;
        LogonDomainName = &((PMSV1_0_INTERACTIVE_LOGON)LocalAuthInfo)->LogonDomainName;
    }
    else
    {
        FIXME("LogonType %lu is not supported yet!\n", LogonType);
    }

    Status = LsapSetLogonSessionData(&RequestMsg->LogonUser.Reply.LogonId,<--- Status is overwritten
                                     LogonType,
                                     UserName,
                                     LogonDomainName,
                                     TokenInfo1->User.User.Sid);
    if (!NT_SUCCESS(Status))
    {
        ERR("LsapSetLogonSessionData failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    /*
     * Duplicate the token handle into the client process.
     * This must be the last step because we cannot
     * close the duplicated token handle in case something fails.
     */
    Status = NtDuplicateObject(NtCurrentProcess(),
                               TokenHandle,
                               LogonContext->ClientProcessHandle,
                               &RequestMsg->LogonUser.Reply.Token,
                               0,
                               0,
                               DUPLICATE_SAME_ACCESS | DUPLICATE_SAME_ATTRIBUTES | DUPLICATE_CLOSE_SOURCE);
    if (!NT_SUCCESS(Status))
    {
        ERR("NtDuplicateObject failed (Status 0x%08lx)\n", Status);
        goto done;
    }

done:
    if (!NT_SUCCESS(Status))
    {
        /* Notify the authentification package of the failure */
        Package->LsaApLogonTerminated(&RequestMsg->LogonUser.Reply.LogonId);

        /* Delete the logon session */
        LsapDeleteLogonSession(&RequestMsg->LogonUser.Reply.LogonId);

        /* Release the profile buffer */
        LsapFreeClientBuffer((PLSA_CLIENT_REQUEST)LogonContext,
                             RequestMsg->LogonUser.Reply.ProfileBuffer);
        RequestMsg->LogonUser.Reply.ProfileBuffer = NULL;
    }

    if (TokenHandle != NULL)
        NtClose(TokenHandle);

    /* Free the local groups */
    if (LocalGroups != NULL)
    {
        for (i = 0; i < LocalGroups->GroupCount; i++)
        {
            if (LocalGroups->Groups[i].Sid != NULL)
                RtlFreeHeap(RtlGetProcessHeap(), 0, LocalGroups->Groups[i].Sid);
        }

        RtlFreeHeap(RtlGetProcessHeap(), 0, LocalGroups);
    }

    /* Free the local authentication info buffer */
    if (LocalAuthInfo != NULL)
        RtlFreeHeap(RtlGetProcessHeap(), 0, LocalAuthInfo);

    /* Free the token information */
    if (TokenInformation != NULL)<--- Assuming that condition 'TokenInformation!=NULL' is not redundant<--- Assuming that condition 'TokenInformation!=NULL' is not redundant
    {
        if (TokenInformationType == LsaTokenInformationNull)
        {
            TokenInfo0 = (PLSA_TOKEN_INFORMATION_NULL)TokenInformation;<--- Assignment 'TokenInfo0=(struct _LSA_TOKEN_INFORMATION_NULL*)TokenInformation', assigned value is 0

            if (TokenInfo0 != NULL)<--- Condition 'TokenInfo0!=NULL' is always true
            {
                if (TokenInfo0->Groups != NULL)
                {
                    for (i = 0; i < TokenInfo0->Groups->GroupCount; i++)
                    {
                        if (TokenInfo0->Groups->Groups[i].Sid != NULL)
                            LsapFreeHeap(TokenInfo0->Groups->Groups[i].Sid);
                    }

                    LsapFreeHeap(TokenInfo0->Groups);
                }

                LsapFreeHeap(TokenInfo0);
            }
        }
        else if (TokenInformationType == LsaTokenInformationV1)
        {
            TokenInfo1 = (PLSA_TOKEN_INFORMATION_V1)TokenInformation;<--- Assignment 'TokenInfo1=(struct _LSA_TOKEN_INFORMATION_V1*)TokenInformation', assigned value is 0

            if (TokenInfo1 != NULL)<--- Condition 'TokenInfo1!=NULL' is always true
            {
                if (TokenInfo1->User.User.Sid != NULL)
                    LsapFreeHeap(TokenInfo1->User.User.Sid);

                if (TokenInfo1->Groups != NULL)
                {
                    for (i = 0; i < TokenInfo1->Groups->GroupCount; i++)
                    {
                        if (TokenInfo1->Groups->Groups[i].Sid != NULL)
                            LsapFreeHeap(TokenInfo1->Groups->Groups[i].Sid);
                    }

                    LsapFreeHeap(TokenInfo1->Groups);
                }

                if (TokenInfo1->PrimaryGroup.PrimaryGroup != NULL)
                    LsapFreeHeap(TokenInfo1->PrimaryGroup.PrimaryGroup);

                if (TokenInfo1->Privileges != NULL)
                    LsapFreeHeap(TokenInfo1->Privileges);

                if (TokenInfo1->Owner.Owner != NULL)
                    LsapFreeHeap(TokenInfo1->Owner.Owner);

                if (TokenInfo1->DefaultDacl.DefaultDacl != NULL)
                    LsapFreeHeap(TokenInfo1->DefaultDacl.DefaultDacl);

                LsapFreeHeap(TokenInfo1);
            }
        }
        else
        {
            FIXME("TokenInformationType %d is not supported!\n", TokenInformationType);
        }
    }

    /* Free the account name */
    if (AccountName != NULL)
    {
        if (AccountName->Buffer != NULL)
            LsapFreeHeap(AccountName->Buffer);

        LsapFreeHeap(AccountName);
    }

    /* Free the authentication authority */
    if (AuthenticatingAuthority != NULL)<--- outer condition: AuthenticatingAuthority!=NULL
    {
        if (AuthenticatingAuthority != NULL)<--- identical inner condition: AuthenticatingAuthority!=NULL
            LsapFreeHeap(AuthenticatingAuthority->Buffer);

        LsapFreeHeap(AuthenticatingAuthority);
    }

    /* Free the machine name */
    if (MachineName != NULL)
    {
        if (MachineName->Buffer != NULL)
            LsapFreeHeap(MachineName->Buffer);

        LsapFreeHeap(MachineName);
    }

    TRACE("LsapLogonUser done (Status 0x%08lx)\n", Status);

    return Status;
}

/* EOF */