LsaAddAccountRights不适合我

时间:2010-12-22 16:46:29

标签: delphi winapi

使用:Delphi 2010和JEDI Windows API和JWSCL

我正在尝试使用LsaAddAccountRights函数将Logon As A Service权限分配给用户,但它不起作用即。函数返回后,检查组策略编辑器显示用户仍然没有上述权限。

我在Windows XP上运行该应用程序。

如果有人能指出我的代码中有什么问题,那会很高兴:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, JwaWindows, JwsclSid;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function AddPrivilegeToAccount(AAccountName, APrivilege: String): DWORD;
var
  lStatus: TNTStatus;
  lObjectAttributes: TLsaObjectAttributes;
  lPolicyHandle: TLsaHandle;
  lPrivilege: TLsaUnicodeString;
  lSid: PSID;
  lSidLen: DWORD;
  lTmpDomain: String;
  lTmpDomainLen: DWORD;
  lTmpSidNameUse: TSidNameUse;
  lPrivilegeWStr: String;
begin
  ZeroMemory(@lObjectAttributes, SizeOf(lObjectAttributes));
  lStatus := LsaOpenPolicy(nil, lObjectAttributes, POLICY_LOOKUP_NAMES, lPolicyHandle);

  if lStatus <> STATUS_SUCCESS then begin
    Result := LsaNtStatusToWinError(lStatus);
    Exit;
  end;

  try
    lTmpDomainLen := DNLEN; // In 'clear code' this should be get by LookupAccountName
    SetLength(lTmpDomain, lTmpDomainLen);

    lSidLen := SECURITY_MAX_SID_SIZE;
    GetMem(lSid, lSidLen);
    try
      if LookupAccountName(nil, PChar(AAccountName), lSid, lSidLen, PChar(lTmpDomain),
        lTmpDomainLen, lTmpSidNameUse) then begin
        lPrivilegeWStr := APrivilege;

        lPrivilege.Buffer := PChar(lPrivilegeWStr);
        lPrivilege.Length := Length(lPrivilegeWStr) * SizeOf(Char);
        lPrivilege.MaximumLength := lPrivilege.Length;

        lStatus := LsaAddAccountRights(lPolicyHandle, lSid, @lPrivilege, 1);
        Result := LsaNtStatusToWinError(lStatus);
      end
      else
        Result := GetLastError;
    finally
      FreeMem(lSid);
    end;
  finally
    LsaClose(lPolicyHandle);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  AddPrivilegeToAccount('Sam', 'SeServiceLogonRight');
end;

end.

提前致谢。

1 个答案:

答案 0 :(得分:2)

为了能够使用LsaAddAccountRights,您应该在POLICY_CREATE_ACCOUNT中使用其他POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES标记(LsaOpenPolicy)打开政策句柄,或使用MAXIMUM_ALLOWED而不是两个标记