середа, 4 березня 2015 р.

Login to network share with username (LogonUser)



type
  TImpersonateUser = class
    const
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
      LOGON32_LOGON_NEW_CREDENTIALS = 9;

    const
      SE_CREATE_TOKEN_NAME = 'SeCreateTokenPrivilege';
      SE_ASSIGNPRIMARYTOKEN_NAME = 'SeAssignPrimaryTokenPrivilege';
      SE_LOCK_MEMORY_NAME = 'SeLockMemoryPrivilege';
      SE_INCREASE_QUOTA_NAME = 'SeIncreaseQuotaPrivilege';
      SE_UNSOLICITED_INPUT_NAME = 'SeUnsolicitedInputPrivilege';
      SE_MACHINE_ACCOUNT_NAME = 'SeMachineAccountPrivilege';
      SE_TCB_NAME = 'SeTcbPrivilege';
      SE_SECURITY_NAME = 'SeSecurityPrivilege';
      SE_TAKE_OWNERSHIP_NAME = 'SeTakeOwnershipPrivilege';
      SE_LOAD_DRIVER_NAME = 'SeLoadDriverPrivilege';
      SE_SYSTEM_PROFILE_NAME = 'SeSystemProfilePrivilege';
      SE_SYSTEMTIME_NAME = 'SeSystemtimePrivilege';
      SE_PROF_SINGLE_PROCESS_NAME = 'SeProfileSingleProcessPrivilege';
      SE_INC_BASE_PRIORITY_NAME = 'SeIncreaseBasePriorityPrivilege';
      SE_CREATE_PAGEFILE_NAME = 'SeCreatePagefilePrivilege';
      SE_CREATE_PERMANENT_NAME = 'SeCreatePermanentPrivilege';
      SE_BACKUP_NAME = 'SeBackupPrivilege';
      SE_RESTORE_NAME = 'SeRestorePrivilege';
      SE_SHUTDOWN_NAME = 'SeShutdownPrivilege';
      SE_DEBUG_NAME = 'SeDebugPrivilege';
      SE_AUDIT_NAME = 'SeAuditPrivilege';
      SE_SYSTEM_ENVIRONMENT_NAME = 'SeSystemEnvironmentPrivilege';
      SE_CHANGE_NOTIFY_NAME = 'SeChangeNotifyPrivilege';
      SE_REMOTE_SHUTDOWN_NAME = 'SeRemoteShutdownPrivilege';
      SE_UNDOCK_NAME = 'SeUndockPrivilege';
      SE_SYNC_AGENT_NAME = 'SeSyncAgentPrivilege';
      SE_ENABLE_DELEGATION_NAME = 'SeEnableDelegationPrivilege';
      SE_MANAGE_VOLUME_NAME = 'SeManageVolumePrivilege';
    private
      FInit : boolean;
      FUserToken : THandle;
    public
      constructor create(); overload;
    function Logon(const userName: string; const password: string; const domain: string = '') : boolean;
    procedure Logoff();
      function SetSystemPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
  end;

implementation

constructor TImpersonateUser.create();
begin
  inherited;
  FInit:=false;
  FUserToken:=0;
end;

procedure  TImpersonateUser.Logoff();
begin

 if not FInit then exit;

 RevertToSelf(); // Revert to our user

 if FUserToken>0 then
  begin
    if( not CloseHandle(FUserToken)) then
      raise Exception.Create(SysErrorMessage(GetLastError));
    FUserToken := 0;
  end;

 FInit:= false;
end;

function TImpersonateUser.SetSystemPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
var
  TokenPriv: TOKEN_PRIVILEGES;
  PrevTokenPriv: TOKEN_PRIVILEGES;
  ReturnLength: Cardinal;
begin
 Result := ImpersonateSelf(SecurityImpersonation);
  Result := false;
  if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, FUserToken) then
  begin
    // Get the locally unique identifier (LUID) .
    if LookupPrivilegeValue(nil, PChar(sPrivilege), TokenPriv.Privileges[0].Luid) then
    begin
      TokenPriv.PrivilegeCount := 1; // one privilege to set

      case bEnabled of
        True: TokenPriv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
        False: TokenPriv.Privileges[0].Attributes := 0;
      end;

      ReturnLength := 0; // replaces a var parameter
      PrevTokenPriv := TokenPriv;

      // enable or disable the privilege
      AdjustTokenPrivileges(FUserToken, False, TokenPriv, SizeOf(PrevTokenPriv),
      PrevTokenPriv, ReturnLength);
    end;
  end;
  // test the return value of AdjustTokenPrivileges.
  Result := GetLastError = ERROR_SUCCESS;
  if not Result then
    raise Exception.Create(SysErrorMessage(GetLastError));
end;

function TImpersonateUser.Logon(const userName: string; const password: string; const domain: string = '') : boolean;
var
  bLoggedOn : boolean;
begin
 if FInit then Logoff();

 if (userName.IsEmpty) then // Must at least specify a username
 begin
    raise Exception.Create(SysErrorMessage(ERROR_BAD_ARGUMENTS));
  end;

  // Attempt to log on as that user
 bLoggedOn := FALSE;

 if domain.IsEmpty then // Domain name was specified
    bLoggedOn := LogonUserW(LPWSTR(userName), '.', LPWSTR(password), LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, FUserToken)
  else
  bLoggedOn := LogonUserW(LPWSTR(userName), LPWSTR(domain), LPWSTR(password), LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, FUserToken);

 if not bLoggedOn then
  begin
    raise Exception.Create(SysErrorMessage(GetLastError));
  end;

  // Now impersonate them
 if( not ImpersonateLoggedOnUser(FUserToken)) then
 begin
    raise Exception.Create(SysErrorMessage(GetLastError));
 end;

 FInit := true;
 result := true;
end;



Example: 

ImpersonateUser:=TImpersonateUser.create;
Try
  ImpersonateUser.Logon('username', 'password');
  Try
    copyFile('192.168.1.100\Share\test.png', 'test.png', false);
  finally
    ImpersonateUser.Logoff;
  end;    
finally
  ImpersonateUser.Destroy;
end;
Stand: 
  • windows 8.1 professional 64Bit Rus
  • Delphi XE7
Links: 
  • LogonUser function is The LogonUser function attempts to log a user on to the local computer. The local computer is the computer from which LogonUser was called. You cannot use LogonUser to log on to a remote computer. You specify the user with a user name and domain and authenticate the user with a plaintext password. If the function succeeds, you receive a handle to a token that represents the logged-on user. You can then use this token handle to impersonate the specified user or, in most cases, to create a process that runs in the context of the specified user.

Немає коментарів:

Дописати коментар