summaryrefslogtreecommitdiffstats
path: root/private/newsam2/client/tmachine.c
blob: 32b91a1d2c6827c30ca680b77bea66dad4a4065c (plain) (blame)
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
/*++

Copyright (c) 1990  Microsoft Corporation

Module Name:

    tmachine.c

Abstract:

    This module tests the machine account creation facilities
    of SAM.

Author:

    Jim Kelly    (JimK)  7-Feb-1994

Environment:

    User Mode - Win32

Revision History:


--*/







///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// Includes                                                                  //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <nt.h>
#include <ntsam.h>
#include <ntsamp.h>
#include <ntlsa.h>
#include <ntrpcp.h>     // prototypes for MIDL user functions
#include <seopaque.h>
#include <string.h>



///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// Macros                                                                    //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////


#ifndef SHIFT
#define SHIFT(c,v)      {c--; v++;}
#endif //SHIFT



///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// Routines                                                                  //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////


NTSTATUS
TSampGetLsaDomainInfo(
    IN  PUNICODE_STRING             ServerName,
    OUT PPOLICY_ACCOUNT_DOMAIN_INFO *PolicyAccountDomainInfo
    )

/*++

Routine Description:

    This routine retrieves ACCOUNT domain information from the LSA
    policy database.


Arguments:

    ServerName - name of machine to get account domain information
        from.

    PolicyAccountDomainInfo - Receives a pointer to a
        POLICY_ACCOUNT_DOMAIN_INFO structure containing the account
        domain info.


Return Value:

    STATUS_SUCCESS - Succeeded.

    Other status values that may be returned from:

             LsaOpenPolicy()
             LsaQueryInformationPolicy()
--*/

{
    NTSTATUS
        NtStatus,
        IgnoreStatus;

    LSA_HANDLE
        PolicyHandle;

    OBJECT_ATTRIBUTES
        PolicyObjectAttributes;

    //
    // Open the policy database
    //

    InitializeObjectAttributes( &PolicyObjectAttributes,
                                  NULL,             // Name
                                  0,                // Attributes
                                  NULL,             // Root
                                  NULL );           // Security Descriptor

    NtStatus = LsaOpenPolicy( ServerName,
                              &PolicyObjectAttributes,
                              POLICY_VIEW_LOCAL_INFORMATION,
                              &PolicyHandle );

    if ( NT_SUCCESS(NtStatus) ) {

        //
        // Query the account domain information
        //

        NtStatus = LsaQueryInformationPolicy( PolicyHandle,
                                              PolicyAccountDomainInformation,
                                              (PVOID *)PolicyAccountDomainInfo );


        IgnoreStatus = LsaClose( PolicyHandle );
        ASSERT(NT_SUCCESS(IgnoreStatus));
    }

    return(NtStatus);
}


NTSTATUS
TSampConnectToServer(
    IN  PUNICODE_STRING         ServerName,
    IN  ACCESS_MASK             DomainAccess,
    OUT PHANDLE                 ServerHandle,
    OUT PHANDLE                 DomainHandle,
    OUT PSID                    *DomainSid
    )

/*++

Routine Description:

    Open a handle to the SAM server on the specified server
    and then open the account domain on that same server.

Arguments:

    ServerName - Name of server to connect to.

    DomainAccess - accesses needed to the account domain.

    ServerHandle - Receives a handle to the SAM server on the specified
        system.

    DomainHandle - Receives a handle to the account domain.

    DomainSid - Receives a pointer to the SID of the account domain.


Return Value:




--*/
{
    NTSTATUS
        NtStatus;

    OBJECT_ATTRIBUTES
        ObjectAttributes;

    PPOLICY_ACCOUNT_DOMAIN_INFO
        AccountDomainInfo;

    //
    // get account domain info
    //

    NtStatus = TSampGetLsaDomainInfo( ServerName,
                                      &AccountDomainInfo);

    if (!NT_SUCCESS(NtStatus)) {
        printf("SAM TEST: Failed to get lsa domain info...\n"
               "          Completion status is 0x%lx\n", NtStatus);
        return(NtStatus);
    }
    printf("SAM TEST: Target domain is %wZ\n", &AccountDomainInfo->DomainName);

    (*DomainSid) = AccountDomainInfo->DomainSid;

    InitializeObjectAttributes( &ObjectAttributes, NULL, 0, 0, NULL );


    NtStatus = SamConnect(
                  ServerName,
                  ServerHandle,
                  SAM_SERVER_READ | SAM_SERVER_EXECUTE,
                  &ObjectAttributes
                  );


    if (!NT_SUCCESS(NtStatus)) {
        printf("SAM TEST: Failed to connect...\n"
               "          Completion status is 0x%lx\n", NtStatus);
        return(NtStatus);
    }


    NtStatus = SamOpenDomain(
                   (*ServerHandle),
                   DomainAccess,
                   *DomainSid,
                   DomainHandle
                   );

    if (!NT_SUCCESS(NtStatus)) {
        printf("Failed account domain open\n"
               "        Completion status is 0x%lx\n", NtStatus);
        return(NtStatus);
    }
    
    return(STATUS_SUCCESS);


}


BOOLEAN
TSampEnableMachinePrivilege( VOID )

/*++

Routine Description:

    This function enabled the SeMachineAccountPrivilege privilege.

Arguments:

    None.

Return Value:

    TRUE  if privilege successfully enabled.
    FALSE if not successfully enabled.

--*/
{

    NTSTATUS Status;
    HANDLE Token;
    LUID SecurityPrivilege;
    PTOKEN_PRIVILEGES NewState;
    ULONG ReturnLength;


    //
    // Open our own token
    //

    Status = NtOpenProcessToken(
                 NtCurrentProcess(),
                 TOKEN_ADJUST_PRIVILEGES,
                 &Token
                 );
    if (!NT_SUCCESS(Status)) {
        printf("SAM TEST: Can't open process token to enable Privilege.\n"
               "          Completion status of NtOpenProcessToken() is: 0x%lx\n", Status);
        return(FALSE);
    }


    //
    // Initialize the adjustment structure
    //

    SecurityPrivilege =
        RtlConvertLongToLargeInteger(SE_MACHINE_ACCOUNT_PRIVILEGE);

    ASSERT( (sizeof(TOKEN_PRIVILEGES) + sizeof(LUID_AND_ATTRIBUTES)) < 100);
    NewState = RtlAllocateHeap( RtlProcessHeap(), 0, 100 );

    NewState->PrivilegeCount = 1;
    NewState->Privileges[0].Luid = SecurityPrivilege;
    NewState->Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;


    //
    // Set the state of the privilege to ENABLED.
    //

    Status = NtAdjustPrivilegesToken(
                 Token,                            // TokenHandle
                 FALSE,                            // DisableAllPrivileges
                 NewState,                         // NewState
                 0,                                // BufferLength
                 NULL,                             // PreviousState (OPTIONAL)
                 &ReturnLength                     // ReturnLength
                 );
    // don't use NT_SUCCESS here because STATUS_NOT_ALL_ASSIGNED is a success status
    if (Status != STATUS_SUCCESS) {
        return(FALSE);
    }


    //
    // Clean up some stuff before returning
    //

    RtlFreeHeap( RtlProcessHeap(), 0, NewState );
    Status = NtClose( Token );
    ASSERT(NT_SUCCESS(Status));


    return TRUE;

}


NTSTATUS
TSampCreateMachine(
    IN  SAM_HANDLE              DomainHandle,
    IN  PUNICODE_STRING         AccountName
    )

/*++

Routine Description:

    This routine attempts to create a machine account.

    One of two cases may be tested:

        1) DomainHandle is open for DOMAIN_CREATE_USER,
    or
        2) DomainHandle is open for DOMAIN_LOOKUP and
           the SeMachineAccountPrivilege privilege is
           enabled.

    It is the caller's responsibility to establish the
    correct case criteria before calling.

Arguments:

    DomainHandle - handle to domain to create account in.

    AccountName - Name of the account to create.


Return Value:

--*/

{
    NTSTATUS
        NtStatus,
        IgnoreStatus;

    SAM_HANDLE
        UserHandle;

    ACCESS_MASK
        GrantedAccess;

    ULONG
        Rid;

    NtStatus = SamCreateUser2InDomain( DomainHandle,
                                       AccountName,
                                       USER_WORKSTATION_TRUST_ACCOUNT,
                                       MAXIMUM_ALLOWED,
                                       &UserHandle,
                                       &GrantedAccess,
                                       &Rid);

    if (NT_SUCCESS(NtStatus)) {
        IgnoreStatus = SamCloseHandle( UserHandle );
        ASSERT(NT_SUCCESS(IgnoreStatus));
        printf("SAM TEST: Machine account created.\n"
               "              GrantedAccess: 0x%lx\n"
               "              Rid:           %d (0x%lx)\n",
               GrantedAccess, Rid, Rid);
    } else {
        printf("SAM TEST: Machine account creation failed.\n"
               "              Status: 0x%lx\n", NtStatus);
    }


    return(NtStatus);


}


NTSTATUS
TSampSetPasswordMachine(
    IN  SAM_HANDLE              DomainHandle,
    IN  PUNICODE_STRING         AccountName,
    IN  PUNICODE_STRING         Password
    )

/*++

Routine Description:

    This routine attempts to set the password of a machine account.


Arguments:

    DomainHandle - handle to domain account is in.

    AccountName - Name of the account to set password.

    Password - New password.

Return Value:

--*/

{
    NTSTATUS
        NtStatus;

    SAM_HANDLE
        UserHandle;

    PULONG
        RelativeIds;

    PSID_NAME_USE
        Use;

    USER_SET_PASSWORD_INFORMATION
        PasswordInfo;


    PasswordInfo.Password = (*Password);
    PasswordInfo.PasswordExpired = FALSE;

    NtStatus = SamLookupNamesInDomain( DomainHandle,
                                       1,
                                       AccountName,
                                       &RelativeIds,
                                       &Use);
    if (!NT_SUCCESS(NtStatus)) {
        printf("SAM TEST: Couldn't find account to set password.\n"
               "              Lookup status: 0x%lx\n", NtStatus);
        return(NtStatus);
    }


    NtStatus = SamOpenUser( DomainHandle,
                            USER_FORCE_PASSWORD_CHANGE,
                            RelativeIds[0],
                            &UserHandle);
                            
    if (!NT_SUCCESS(NtStatus)) {
        printf("SAM TEST: Couldn't open user account for FORCE_PASSWORD_CHANGE.\n"
               "              Lookup status: 0x%lx\n", NtStatus);
        return(NtStatus);
    }

    NtStatus = SamSetInformationUser( UserHandle,
                                      UserSetPasswordInformation,
                                      &PasswordInfo
                                      );
    if (!NT_SUCCESS(NtStatus)) {
        printf("SAM TEST: Couldn't set password on user account.\n"
               "              Set Info status: 0x%lx\n", NtStatus);
        return(NtStatus);
    }


    return(STATUS_SUCCESS);


}


NTSTATUS
TSampDeleteMachine(
    IN  SAM_HANDLE              DomainHandle,
    IN  PUNICODE_STRING         AccountName
    )

/*++

Routine Description:

    This routine attempts to delete a machine account.


Arguments:

    DomainHandle - handle to domain to delete account from.

    AccountName - Name of the account to delete.


Return Value:

--*/

{
    NTSTATUS
        NtStatus;

    SAM_HANDLE
        UserHandle;

    PULONG
        RelativeIds;

    PSID_NAME_USE
        Use;

    NtStatus = SamLookupNamesInDomain( DomainHandle,
                                       1,
                                       AccountName,
                                       &RelativeIds,
                                       &Use);
    if (!NT_SUCCESS(NtStatus)) {
        printf("SAM TEST: Couldn't find account to delete.\n"
               "              Lookup status: 0x%lx\n", NtStatus);
        return(NtStatus);
    }


    NtStatus = SamOpenUser( DomainHandle,
                            DELETE,
                            RelativeIds[0],
                            &UserHandle);
                            
    if (!NT_SUCCESS(NtStatus)) {
        printf("SAM TEST: Couldn't open user account for delete.\n"
               "              Open status: 0x%lx\n", NtStatus);
        return(NtStatus);
    }

    NtStatus = SamDeleteUser( UserHandle );
    if (!NT_SUCCESS(NtStatus)) {
        printf("SAM TEST: Couldn't delete user account.\n"
               "              DeleteUser status: 0x%lx\n", NtStatus);
        return(NtStatus);
    }


    return(STATUS_SUCCESS);


}


VOID
TSampPrintYesOrNo(
    IN BOOLEAN b
    )
{
    if (b) {
        printf("Yes\n");
    } else {
        printf("No\n");
    }
}



VOID
TSampUsage( VOID )
{

    printf("\n\n Command format:\n");
    printf("          tmachine [/c] [/p] [/d] <account-name> <machine> [<password>]\n");
    printf("\n");
    printf(" Switches\n");
    printf("          /c - create account\n");
    printf("          /p - set password on account\n");
    printf("          /d - delete account\n");
    printf("\n");
    printf(" if multiple switches are specified, they are attempted in\n");
    printf(" the order listed above.  An error in any attempt will prevent\n");
    printf(" any further attempts.\n");
    printf("\n");
    return;
}


VOID
main (c,v)
int c;
char **v;

/*++

Routine Description:

    This is the main entry routine for this test.

Arguments:

    Argv[1] - account name to create or delete

    Argv[2] - domain controller machine name

    Argv[3] - 'D' to delete account, otherwise account is created.



Return Value:




--*/
{
    NTSTATUS
        NtStatus,
        IgnoreStatus;

    UNICODE_STRING
        AccountName,
        ControllerName,
        Password;

    WCHAR
        AccountNameBuffer[80],
        ControllerNameBuffer[80],
        PasswordBuffer[80];

    ANSI_STRING
        AnsiString;

    SAM_HANDLE
        ServerHandle,
        ServerHandle2,
        DomainHandle,
        DomainHandle2;

    PSID
        DomainSid;

    BOOLEAN
        Create = FALSE,
        SetPassword = FALSE,
        Delete = FALSE;

    ULONG
        ArgNum = 0;

    PCHAR
        p;

    CHAR
        ch;

    AccountName.Length = 0;
    ControllerName.Length = 0;
    Password.Length = 0;



    //
    // Command format:
    //
    //          tmachine [/c] [/p] [/d] <account-name> <machine> [<password>]
    //
    // Switches
    //          /c - create account
    //          /p - set password on account
    //          /d - delete account
    //
    // if multiple switches are specified, they are attempted in
    // the order listed above.  An error in any attempt will prevent
    // any further attempts.
    //

    SHIFT (c,v);
    while ((c > 0) && ((ch = *v[0]))) {
        p = *v;
        if (ch == '/') {
            while (*++p != '\0') {
                if ((*p == 'c') || (*p == 'C')) {
                    Create = TRUE;
//                    printf("Create\n");
                } else if ((*p == 'p') || (*p == 'P')) {
                    SetPassword = TRUE;
//                    printf("SetPassword\n");
                } else if ((*p == 'd') || (*p == 'D')) {
                    Delete = TRUE;
//                    printf("Delete\n");
                } else {
                    TSampUsage();
                    return;
                }
            }
        } else {

            switch (ArgNum) {
                case 0:

                    //
                    // collecting account name
                    //

                    AccountName.Buffer = AccountNameBuffer;
                    AccountName.MaximumLength = sizeof(AccountNameBuffer);
                    RtlInitAnsiString(&AnsiString, (*v));
                    RtlAnsiStringToUnicodeString(&AccountName, &AnsiString, FALSE);

//                    printf("account: %wZ\n", &AccountName);
                    break;

                case 1:

                    //
                    // collecting machine name
                    //

                    ControllerName.Buffer = ControllerNameBuffer;
                    ControllerName.MaximumLength = sizeof(ControllerNameBuffer);
                    RtlInitAnsiString(&AnsiString, (*v));
                    RtlAnsiStringToUnicodeString(&ControllerName, &AnsiString, FALSE);

//                    printf("machine: %wZ\n", &ControllerName);
                    break;


                case 2:

                    //
                    // collecting password name
                    //

                    Password.Buffer = PasswordBuffer;
                    Password.MaximumLength = sizeof(PasswordBuffer);
                    RtlInitAnsiString(&AnsiString, (*v));
                    RtlAnsiStringToUnicodeString(&Password, &AnsiString, FALSE);

//                    printf("password: %wZ\n", &Password);
                    break;

                default:

                    //
                    // collecting garbage.
                    //

                    break;
            }

            ArgNum++;
        }
    SHIFT(c,v);
    }



    printf("parameters:\n");
    printf("    Create Account:  "); TSampPrintYesOrNo( Create );
    printf("    Set Password  :  "); TSampPrintYesOrNo( SetPassword );
    printf("    Delete Account:  "); TSampPrintYesOrNo( Delete );
    printf("    Account       :  *%wZ*\n", &AccountName);
    printf("    Machine       :  *%wZ*\n", &ControllerName);
    printf("    Password      :  *%wZ*\n", &Password);


    //
    // Make sure we don't have conflicting parameters
    //
    // Rules:
    //
    //      1) account name is always required.
    //      2) password and machine are required if /P was specified.
    //      3) machine is optional if /P not specified.
    //
    //

    if ( (AccountName.Length == 0)                          ||
         ( SetPassword && (ControllerName.Length == 0) )    ||
         ( SetPassword && (Password.Length == 0) ) ) {
        TSampUsage();
        return;
    }


    //
    // Open the server and the account domain
    //

    NtStatus = TSampConnectToServer(&ControllerName,
                                    DOMAIN_LOOKUP | DOMAIN_READ_PASSWORD_PARAMETERS,
                                    &ServerHandle,
                                    &DomainHandle,
                                    &DomainSid);


    if (Create) {
        //
        // try to create the machine account with privilege.
        //


        printf("SAM TEST: Creating machine account with privilege.\n");
        TSampEnableMachinePrivilege();
        NtStatus = TSampCreateMachine( DomainHandle, &AccountName );
        if (NT_SUCCESS(NtStatus)) {
            printf("          Status: successful\n");
        } else {

            if (NtStatus == STATUS_ACCESS_DENIED) {
                //
                // We didn't have the privilege, and didn't have
                // the domain open so that it would work without
                // the privilege.
                //

                printf("      Couldn't create account with privilege (0x%lx)\n"
                       "      Attempting normal creation (without privilege)\n"
                       , NtStatus);
                NtStatus = TSampConnectToServer(&ControllerName,
                                                DOMAIN_LOOKUP |
                                                DOMAIN_READ_PASSWORD_PARAMETERS |
                                                DOMAIN_CREATE_USER,
                                                &ServerHandle2,
                                                &DomainHandle2,
                                                &DomainSid);
                if (!NT_SUCCESS(NtStatus)) {
                    printf("      Can't open domain for CREATE_USER access (0x%lx)\n", NtStatus);
                } else {
                    NtStatus = TSampCreateMachine( DomainHandle2,
                                                   &AccountName );
                    if (NT_SUCCESS(NtStatus)) {
                        printf("          Status: successful\n");
                    } else {
                        printf("          Failed: 0x%lx\n", NtStatus);
                    }

                    IgnoreStatus = SamCloseHandle( DomainHandle2 );

                }
            }
            if (!NT_SUCCESS(NtStatus)) {
                printf("          Status: 0x%lx", NtStatus);
                return;
            }
        }
    }


    if (SetPassword) {

        //
        // Try to set the password on the account
        //

        printf("SAM TEST: Setting password of account ...\n");
        NtStatus = TSampSetPasswordMachine( DomainHandle, &AccountName, &Password );
        if (NT_SUCCESS(NtStatus)) {
            printf("          Status: successful\n");
        } else {
            printf("          Status: 0x%lx", NtStatus);
            return;
        }
    }


    if (Delete) {

        printf("SAM TEST: Deleting account ...\n");
        NtStatus = TSampDeleteMachine( DomainHandle, &AccountName );
        if (NT_SUCCESS(NtStatus)) {
            printf("          Status: successful\n");
        } else {
            printf("          Status: 0x%lx", NtStatus);
            return;
        }
    }


    return;
}