Exemple #1
2
int main(void)
{
  // GetCurrentProcess cannot fail
  HANDLE hProcess = GetCurrentProcess();

  if (OpenProcessToken(hProcess, TOKEN_READ, &hProcess))
  {
    LUID seCreateSymbolicLinkPrivilege;

    if (LookupPrivilegeValue(NULL, SE_CREATE_SYMBOLIC_LINK_NAME, &seCreateSymbolicLinkPrivilege))
    {
      DWORD length;

      printf("SeCreateSymbolicLinkPrivilege = %ld, %ld\n", seCreateSymbolicLinkPrivilege.HighPart, seCreateSymbolicLinkPrivilege.LowPart);

      if (!GetTokenInformation(hProcess, TokenPrivileges, NULL, 0, &length))
      {
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
          TOKEN_PRIVILEGES* privileges = (TOKEN_PRIVILEGES*)malloc(length);
          if (GetTokenInformation(hProcess, TokenPrivileges, privileges, length, &length))
          {
            BOOL found = FALSE;
            DWORD count = privileges->PrivilegeCount;

            printf("User has %ld privileges\n", count);

            if (count > 0)
            {
              LUID_AND_ATTRIBUTES* privs = privileges->Privileges;
              while (count-- > 0 && !luid_eq(privs->Luid, seCreateSymbolicLinkPrivilege))
                privs++;
              found = (count > 0);
            }

            printf("User does%s have the SeCreateSymbolicLinkPrivilege\n", (found ? "" : "n't"));
          }
          else
          {
            fprintf(stderr, "Second GetTokenInformation failed\n");
          }

          free(privileges);
        }
        else
        {
          fprintf(stderr, "First GetTokenInformation failed\n");
        }
      }
      else
      {
        fprintf(stderr, "Impossible output from GetTokenInformation\n");
      }
    }
    else
    {
      fprintf(stderr, "LookupPrivilegeValue failed\n");
    }

    CloseHandle(hProcess);
  }
  else
  {
    fprintf(stderr, "OpenProcessToken failed\n");
  }

  LSA_HANDLE hPolicy;
  NTSTATUS r;
  LSA_OBJECT_ATTRIBUTES attributes = {0, NULL, NULL, 0, NULL, NULL};
  attributes.Length = sizeof(attributes);

  LUID seCreateSymbolicLinkPrivilege;

  if (LookupPrivilegeValue(NULL, SE_CREATE_SYMBOLIC_LINK_NAME, &seCreateSymbolicLinkPrivilege))
  {
    // POLICY_LOOKUP_NAMES: LsaLookupNames2, LsaEnumerateAccountRights, LsaLookupSids, LsaAddAccountRights
    // POLICY_VIEW_LOCAL_INFORMATION: LsaEnumerateAccountsWithUserRight
    // Elevation: LsaEnumerateAccountRights, LsaEnumerateAccountsWithUserRight, LsaRemoveAccountRights, LsaAddAccountRights
    if (NT_SUCCESS(r = LsaOpenPolicy(NULL, &attributes, POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION, &hPolicy)))
    {
      LSA_REFERENCED_DOMAIN_LIST* referencedDomains;
      LSA_TRANSLATED_SID2* sids;
      LSA_UNICODE_STRING name;
      name.Buffer = L"Users";
      name.Length = wcslen(name.Buffer) * sizeof(WCHAR);
      name.MaximumLength = name.Length + sizeof(WCHAR);
  
      if (NT_SUCCESS(r = LsaLookupNames2(hPolicy, LSA_LOOKUP_ISOLATED_AS_LOCAL, 1, &name, &referencedDomains, &sids)))
      {
        LSA_UNICODE_STRING* rights;
        ULONG count;
        LsaFreeMemory(referencedDomains);

        if (NT_SUCCESS(r = LsaEnumerateAccountRights(hPolicy, sids->Sid, &rights, &count)))
        {
          LSA_UNICODE_STRING* right = rights;
          printf("%ld right%s found\n", count, PLURAL(count));
          while (count-- > 0)
          {
            printf("  %.*S\n", right->Length / 2, right->Buffer);
            right++;
          }

          LsaFreeMemory(rights);

          LSA_ENUMERATION_INFORMATION* allSidsRaw;
          LSA_UNICODE_STRING lsaCreateSymbolicLinkPrivilege;
          lsaCreateSymbolicLinkPrivilege.Buffer = SE_CREATE_SYMBOLIC_LINK_NAME;
          lsaCreateSymbolicLinkPrivilege.Length = wcslen(lsaCreateSymbolicLinkPrivilege.Buffer) * sizeof(WCHAR);
          lsaCreateSymbolicLinkPrivilege.MaximumLength = lsaCreateSymbolicLinkPrivilege.Length + sizeof(WCHAR);
          if (NT_SUCCESS(r = LsaEnumerateAccountsWithUserRight(hPolicy, &lsaCreateSymbolicLinkPrivilege, (void**)&allSidsRaw, &count)))
          {
            LSA_ENUMERATION_INFORMATION* sid = allSidsRaw;
            PSID* allSids;
            PSID* p;
            PLSA_TRANSLATED_NAME names;
            ULONG i = count;

            printf("%ld SID%s found\n", count, PLURAL(count));
            p = allSids = (PSID*)malloc(count * sizeof(PSID));

            while (i-- > 0)
              *p++ = (sid++)->Sid;

            if (NT_SUCCESS(r = LsaLookupSids(hPolicy, count, allSids, &referencedDomains, &names)))
            {
              PLSA_TRANSLATED_NAME name = names;
              BOOL usersAssigned = FALSE;

              LsaFreeMemory(referencedDomains);

              while (count-- > 0)
              {
                LPTSTR sidString;
                USHORT len = name->Name.Length / 2;
                ConvertSidToStringSid(*allSids++, &sidString);
                printf("  %.*S (%S)\n", len, name->Name.Buffer, sidString);
                usersAssigned |= (len > 4 && !wcsncmp(L"Users", name->Name.Buffer, len));
                name++;
                LocalFree(sidString);
              }

              printf("Users had%s got SeCreateSymbolicLinkPrivilege\n", (usersAssigned ? "" : "n't"));
              if (usersAssigned)
              {
                if (!NT_SUCCESS(r = LsaRemoveAccountRights(hPolicy, sids->Sid, FALSE, &lsaCreateSymbolicLinkPrivilege, 1)))
                {
                  fprintf(stderr, "Lsa failed with code %x\n", r);
                }
              }
              else
              {
                if (!NT_SUCCESS(r = LsaAddAccountRights(hPolicy, sids->Sid, &lsaCreateSymbolicLinkPrivilege, 1)))
                {
                  fprintf(stderr, "LsaAddAccountRights failed with code %x\n", r);
                }
              }

              LsaFreeMemory(names);
            }
            else
            {
              fprintf(stderr, "LsaLookupSids2 failed with code %x\n", r);
            }
              
            LsaFreeMemory(allSidsRaw);
            free(allSids);
          }
          else
          {
            fprintf(stderr, "LsaEnumerateAccountsWithUserRight failed with code %x\n", r);
          }
        }
        else
        {
          fprintf(stderr, "LsaEnumerateAccountRights failed with code %x\n", r);
        }

        LsaFreeMemory(sids);
      }
      else
      {
        fprintf(stderr, "LsaLookupNames2 failed with code %x\n", r);
      }
  
      LsaClose(hPolicy);
    }
    else
    {
      fprintf(stderr, "LsaOpenPolicy failed with code %x\n", r);
    }
  }
  else
  {
    fprintf(stderr, "LookupPrivilegeValue failed\n");
  }
}
Exemple #2
0
static
VOID
InstallBuiltinAccounts(VOID)
{
    LPWSTR BuiltinAccounts[] = {
        L"S-1-1-0",         /* Everyone */
        L"S-1-5-4",         /* Interactive */
        L"S-1-5-6",         /* Service */
        L"S-1-5-19",        /* Local Service */
        L"S-1-5-20",        /* Network Service */
        L"S-1-5-32-544",    /* Administrators */
        L"S-1-5-32-545",    /* Users */
        L"S-1-5-32-547",    /* Power Users */
        L"S-1-5-32-551",    /* Backup Operators */
        L"S-1-5-32-555"};   /* Remote Desktop Users */
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    NTSTATUS Status;
    LSA_HANDLE PolicyHandle = NULL;
    LSA_HANDLE AccountHandle = NULL;
    PSID AccountSid;
    ULONG i;

    DPRINT("InstallBuiltinAccounts()\n");

    memset(&ObjectAttributes, 0, sizeof(LSA_OBJECT_ATTRIBUTES));

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_CREATE_ACCOUNT,
                           &PolicyHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("LsaOpenPolicy failed (Status %08lx)\n", Status);
        return;
    }

    for (i = 0; i < 10; i++)
    {
        if (!ConvertStringSidToSid(BuiltinAccounts[i], &AccountSid))
        {
            DPRINT1("ConvertStringSidToSid(%S) failed: %lu\n", BuiltinAccounts[i], GetLastError());
            continue;
        }

        Status = LsaCreateAccount(PolicyHandle,
                                  AccountSid,
                                  0,
                                  &AccountHandle);
        if (NT_SUCCESS(Status))
        {
            LsaClose(AccountHandle);
        }

        LocalFree(AccountSid);
    }

    LsaClose(PolicyHandle);
}
Exemple #3
0
NTSTATUS InstallNetWare( LPWSTR lpNcpSecretKey )
{
    NTSTATUS          ntstatus;
    OBJECT_ATTRIBUTES ObjAttributes;
    LSA_HANDLE        PolicyHandle;
    LSA_HANDLE        SecretHandle;
    UNICODE_STRING    SecretNameString;
    UNICODE_STRING    unicodeCurrentValue;
    UNICODE_STRING    unicodeOldValue;

    InitializeObjectAttributes( &ObjAttributes,
                                NULL,
                                0L,
                                NULL,
                                NULL);

    ntstatus = LsaOpenPolicy( NULL,
                              &ObjAttributes,
                              POLICY_CREATE_SECRET,
                              &PolicyHandle );

    if ( !NT_SUCCESS( ntstatus ))
    {
        return( ntstatus );
    }

    RtlInitUnicodeString( &SecretNameString, NCP_LSA_SECRET_KEY );

    ntstatus = LsaCreateSecret( PolicyHandle,
                                &SecretNameString,
                                SECRET_SET_VALUE | DELETE,
                                &SecretHandle );

    if ( ntstatus == STATUS_OBJECT_NAME_COLLISION )
    {
        ntstatus = LsaOpenSecret( PolicyHandle,
                                  &SecretNameString,
                                  SECRET_SET_VALUE,
                                  &SecretHandle );
    }

    if ( NT_SUCCESS( ntstatus ))
    {
        RtlInitUnicodeString( &unicodeOldValue, NULL );
        RtlInitUnicodeString( &unicodeCurrentValue, lpNcpSecretKey );

        ntstatus = LsaSetSecret( SecretHandle,
                                 &unicodeCurrentValue,
                                 &unicodeOldValue );

        LsaClose( SecretHandle );
    }

    LsaClose( PolicyHandle );

    return( ntstatus );
}
Exemple #4
0
static VOID
AddImpersonatePrivilege(VOID)
{
    /* S-1-5-6 -- "Service" group */
    static SID ServiceSid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_SERVICE_RID } };

    NTSTATUS Status;
    LSA_HANDLE PolicyHandle;
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    LSA_UNICODE_STRING RightString;

    ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes));
    Status = LsaOpenPolicy(NULL, &ObjectAttributes,
                           POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES,
                           &PolicyHandle);
    if (!NT_SUCCESS(Status))
    {
        ERR("LsaOpenPolicy() failed with Status 0x%08lx\n", Status);
        return;
    }

    RtlInitUnicodeString(&RightString, L"SeImpersonatePrivilege");
    Status = LsaAddAccountRights(PolicyHandle, &ServiceSid, &RightString, 1);
    if (!NT_SUCCESS(Status))
    {
        ERR("LsaAddAccountRights(\"S-1-5-6\", \"%wZ\") failed with Status 0x%08lx\n", Status, &RightString);
    }

    LsaClose(PolicyHandle);
}
Exemple #5
0
NTSTATUS
AddPrivilegeToAcccount(LPTSTR name, LPWSTR PrivilegeName) {
	LSA_HANDLE PolicyHandle;
	TCHAR AccountName[256];		/* static account name buffer */
	PSID pSid;
	NTSTATUS Status;
	unsigned long err;

	/*
	 * Open the policy on the target machine.
	 */
	if ((Status = OpenPolicy(NULL, POLICY_ALL_ACCESS, &PolicyHandle))
		!= STATUS_SUCCESS)
		return (RTN_ERROR);

	/*
	 * Let's see if the account exists. Return if not
	 */
	wsprintf(AccountName, TEXT("%hS"), name);
	if (!GetAccountSid(NULL, AccountName, &pSid))
		return (RTN_NOACCOUNT);

	err = LsaNtStatusToWinError(SetPrivilegeOnAccount(PolicyHandle,
		pSid, PrivilegeName, TRUE));

	LsaClose(PolicyHandle);
	if (err == ERROR_SUCCESS)
		return (RTN_OK);
	else
		return (err);
}
BOOL
GrantUserRight(
    PSID    psidAccountSid,
    LPWSTR  pszUserRight,
    BOOL    bEnable
    )
{
    LSA_HANDLE  PolicyHandle = NULL;
    NTSTATUS    Status;

    //
    // Open the policy on the local host.
    //
    Status = OpenPolicy(
                _T(""),
                POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES,
                &PolicyHandle
                );


    if(Status != STATUS_SUCCESS) {
        return FALSE;
    }


    //
    // Grant the requested user right represented by psidAccountSid.
    //
    Status = SetPrivilegeOnAccount(
                PolicyHandle,                   // policy handle
                psidAccountSid,                 // SID to grant privilege
                pszUserRight,                   // Unicode privilege
                bEnable                         // enable the privilege
                );

    if(Status != STATUS_SUCCESS)
    {
        LsaClose(PolicyHandle);
        return FALSE;
    }

    //
    // Cleanup any handles and memory allocated during the custom action
    //
    LsaClose(PolicyHandle);
    return TRUE;
}
Exemple #7
0
/**
 * @brief
 * 		add_privilege - add_privilege: returns 0 if privname has been added for account
 * 		referenced by sid; otherwise, 1.
 *
 * @param[in]	sid	-	The security identifier (SID) structure is a variable-length structure
 * 						 used to uniquely identify users or groups.
 * @param[in]	privname	-	privilege name
 *
 * @return	int
 * @retval	1	: if privname has not been added for account referenced by sid
 * @retval	0	: if privname has been added for account referenced by sid
 */
int
add_privilege(SID *sid, char *privname)
{
	LSA_UNICODE_STRING rights;
	LSA_HANDLE h_policy = INVALID_HANDLE_VALUE;
	LSA_OBJECT_ATTRIBUTES  obj_attrs;
	NTSTATUS lsa_stat;
	BOOL	rval = 1;
	WCHAR	*privnameW = NULL;
	int	priv_len = 0;

	if (privname == NULL) {
		fprintf(stderr, "add_privilege: NULL privname\n");
		return (1);
	}

	if (!IsValidSid(sid)) {
		fprintf(stderr, "add_privilege: Not a valid sid\n");
		return (1);
	}

	priv_len = strlen(privname) + 1;
	privnameW = (WCHAR *)malloc(priv_len * sizeof(WCHAR));

	if (privnameW == NULL) {
		fprintf(stderr, "add_privilege: malloc failed\n");
		return (1);
	}

	mbstowcs(privnameW, privname, priv_len);
	init_lsa_string(&rights, privnameW);

	ZeroMemory(&obj_attrs, sizeof(obj_attrs));
	if( LsaOpenPolicy(NULL, &obj_attrs, POLICY_ALL_ACCESS, &h_policy) \
							!= ERROR_SUCCESS ) {
		fprintf(stderr, "add_privilege: Unable to open policy!\n");
		goto add_privilege_end;
	}

	if( (lsa_stat=LsaAddAccountRights( h_policy, sid, &rights, 1 )) != \
							ERROR_SUCCESS ) {
		fprintf(stderr,
			"add_privilege: adding privilege %s failed! - err %d\n",
			privname, LsaNtStatusToWinError(lsa_stat));
		goto add_privilege_end;
	}

	printf("\tadded %s\n", privname);
	rval = 0;

add_privilege_end:
	if (h_policy != INVALID_HANDLE_VALUE)
		LsaClose(h_policy);

	if (privnameW != NULL)
		(void)free(privnameW);

	return (rval);
}
void RevokePrivilege(PSID sid, LPCWSTR userRight)
{
    LSA_HANDLE hPolicy = OpenPolicy(POLICY_LOOKUP_NAMES);

    try
    {
        LSA_UNICODE_STRING lsaUserRight;
        InitLsaString(&lsaUserRight, (LPWSTR)userRight);
        CheckRetVal(LsaRemoveAccountRights(hPolicy, sid, FALSE, &lsaUserRight, 1));
        LsaClose(hPolicy);
    }
    catch (const std::exception&)
    {
        LsaClose(hPolicy);
        throw;
    }
}
Exemple #9
0
int isDomainMember(wchar_t *wszDomain)
{
     PPOLICY_PRIMARY_DOMAIN_INFO ppdiDomainInfo=NULL;
     PPOLICY_DNS_DOMAIN_INFO pddiDomainInfo=NULL;
     LSA_HANDLE PolicyHandle;
     NTSTATUS status;
     BOOL retval = FALSE;

	 *wszDomain = '\0';

     // open the policy object for the local system
     status = OpenPolicy(
             NULL
             , GENERIC_READ | POLICY_VIEW_LOCAL_INFORMATION
             , &PolicyHandle
     );
    // You have a handle to the policy object. Now, get the
    // domain information using LsaQueryInformationPolicy.
    if ( !status )
    {
		/* Based on patch by Valdas Sevelis.  Call PolicyDnsDomainInformation first
		   as Win2K Advanced server is broken w/PolicyPrimaryDomainInformation */
        status = LsaQueryInformationPolicy(
                PolicyHandle,
                PolicyDnsDomainInformation,
                (void**)&pddiDomainInfo);
		if(!status)
		{
			retval = pddiDomainInfo->Sid != 0;
			if(wszDomain && retval)
			{
					wcsncpy(wszDomain,pddiDomainInfo->Name.Buffer,pddiDomainInfo->Name.Length/sizeof(wchar_t));
					wszDomain[pddiDomainInfo->Name.Length/sizeof(wchar_t)]='\0';
			}
		    LsaFreeMemory( (LPVOID)pddiDomainInfo );
		}
		else
		{
             status = LsaQueryInformationPolicy(
                     PolicyHandle,
                     PolicyPrimaryDomainInformation,
                     (void**)&ppdiDomainInfo);
			if(!status)
			{
				retval = ppdiDomainInfo->Sid != 0;
				if(wszDomain && retval)
				{
					wcsncpy(wszDomain,ppdiDomainInfo->Name.Buffer,ppdiDomainInfo->Name.Length/sizeof(wchar_t));
					wszDomain[ppdiDomainInfo->Name.Length/sizeof(wchar_t)]='\0';
				}
			    LsaFreeMemory( (LPVOID)ppdiDomainInfo );
			}
		}
    }
    // Clean up all the memory buffers created by the LSA calls
	LsaClose(PolicyHandle);
    return retval;
}
void GrantPrivilege(PSID sid, LPCWSTR userRight)
{
    LSA_HANDLE hPolicy = OpenPolicy(POLICY_LOOKUP_NAMES | POLICY_CREATE_ACCOUNT);

    try
    {
        LSA_UNICODE_STRING lsaUserRight;
        InitLsaString(&lsaUserRight, (LPWSTR)userRight);
        CheckRetVal(LsaAddAccountRights(hPolicy, sid, &lsaUserRight, 1));

        LsaClose(hPolicy);
    }
    catch (const std::exception&)
    {
        LsaClose(hPolicy);
        throw;
    }
}
std::vector<std::wstring> GetPrivileges(PSID sid)
{
    LSA_HANDLE hPolicy = OpenPolicy(POLICY_LOOKUP_NAMES);
    PLSA_UNICODE_STRING userRights = NULL;

    try
    {
        ULONG rightsCount = 0;

        CheckRetVal(LsaEnumerateAccountRights(hPolicy, sid, &userRights, &rightsCount), ERROR_FILE_NOT_FOUND);

        std::vector<std::wstring> v;
        for (int i = 0; i < rightsCount; i++)
        {
            std::wstring s(userRights[i].Buffer, userRights[i].Length / sizeof(WCHAR));
            v.push_back(s);
        }

        LsaFreeMemory(userRights);
        userRights = NULL;
        LsaClose(hPolicy);
        hPolicy = NULL;

        return v;
    }
    catch (const std::exception&)
    {
        if (userRights)
        {
            LsaFreeMemory(userRights);
        }

        if (hPolicy)
        {
            LsaClose(hPolicy);
        }

        throw;
    }
}
Exemple #12
0
DWORD
ScmSetServicePassword(
    IN PCWSTR pszServiceName,
    IN PCWSTR pszPassword)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    LSA_HANDLE PolicyHandle = NULL;
    UNICODE_STRING ServiceName = {0, 0, NULL};
    UNICODE_STRING Password;
    NTSTATUS Status;
    DWORD dwError = ERROR_SUCCESS;

    RtlZeroMemory(&ObjectAttributes, sizeof(OBJECT_ATTRIBUTES));

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_CREATE_SECRET,
                           &PolicyHandle);
    if (!NT_SUCCESS(Status))
        return RtlNtStatusToDosError(Status);

    ServiceName.Length = (wcslen(pszServiceName) + 4) * sizeof(WCHAR);
    ServiceName.MaximumLength = ServiceName.Length + sizeof(WCHAR);
    ServiceName.Buffer = HeapAlloc(GetProcessHeap(),
                                   HEAP_ZERO_MEMORY,
                                   ServiceName.MaximumLength);
    if (ServiceName.Buffer == NULL)
        return ERROR_NOT_ENOUGH_MEMORY;

    wcscpy(ServiceName.Buffer, L"_SC_");
    wcscat(ServiceName.Buffer, pszServiceName);

    RtlInitUnicodeString(&Password, pszPassword);

    Status = LsaStorePrivateData(PolicyHandle,
                                 &ServiceName,
                                 pszPassword ? &Password : NULL);
    if (!NT_SUCCESS(Status))
    {
        dwError = RtlNtStatusToDosError(Status);
        goto done;
    }

done:
    if (ServiceName.Buffer != NULL)
        HeapFree(GetProcessHeap(), 0, ServiceName.Buffer);

    if (PolicyHandle != NULL)
        LsaClose(PolicyHandle);

    return dwError;
}
Exemple #13
0
BOOL kull_m_net_getCurrentDomainInfo(PPOLICY_DNS_DOMAIN_INFO * pDomainInfo)
{
	BOOL status = FALSE;
	LSA_HANDLE hLSA;
	LSA_OBJECT_ATTRIBUTES oaLsa = {0};

	if(NT_SUCCESS(LsaOpenPolicy(NULL, &oaLsa, POLICY_VIEW_LOCAL_INFORMATION, &hLSA)))
	{
		status = NT_SUCCESS(LsaQueryInformationPolicy(hLSA, PolicyDnsDomainInformation, (PVOID *) pDomainInfo));
		LsaClose(hLSA);
	}
	return status;
}
Exemple #14
0
PLSA_UNICODE_STRING CDialupass::GetLsaData(LPSTR KeyName)
{
	LSA_OBJECT_ATTRIBUTES LsaObjectAttribs;
	LSA_HANDLE LsaHandle;
	LSA_UNICODE_STRING LsaKeyName;
	NTSTATUS nts;
	PLSA_UNICODE_STRING OutData;

	ZeroMemory(&LsaObjectAttribs,sizeof(LsaObjectAttribs));
	nts=LsaOpenPolicy(NULL,&LsaObjectAttribs,POLICY_GET_PRIVATE_INFORMATION,&LsaHandle);
	if(nts!=0)return NULL;
	AnsiStringToLsaStr(KeyName, &LsaKeyName);
	nts=LsaRetrievePrivateData(LsaHandle, &LsaKeyName,&OutData);
	if(nts!=0)return NULL;
	nts=LsaClose(LsaHandle);
	if(nts!=0)return NULL;
	return OutData;
}
Exemple #15
0
bool DeleteRightUsers(UserManager *panel,bool selection)
{
  bool res=false;
  CFarPanelSelection sp((HANDLE)panel,selection);
  if(sp.Number())
  {
    TCHAR warning[TINY_BUFFER];
    if(sp.Number()==1)
    {
      TCHAR Truncated[MAX_PATH];
      _tcscpy(Truncated,sp[0].FileName);
      FSF.TruncPathStr(Truncated,50);
      FSF.sprintf(warning,GetMsg(mDelOne),Truncated);
    }
    else
      FSF.sprintf(warning,GetMsg(mDelUserN+NumberType(sp.Number())),sp.Number());
    const TCHAR *MsgItems[]={GetMsg(mButtonDelete),warning,GetMsg(mButtonDelete),GetMsg(mButtonCancel)};
    if(!Info.Message(&MainGuid,&DelUserMessageGuid,0,NULL,MsgItems,sizeof(MsgItems)/sizeof(MsgItems[0]),2))
    {
      res=true;
      LSA_HANDLE PolicyHandle;
      PolicyHandle=GetPolicyHandle(panel->computer);
      if(PolicyHandle)
      {
        for(int i=0;i<sp.Number();i++)
        {
          if(sp[i].UserData.FreeData)
          {
            LSA_UNICODE_STRING RightName;
            RightName.Buffer=panel->nonfixed;
            RightName.Length=wcslen(RightName.Buffer)*sizeof(wchar_t);
            RightName.MaximumLength=RightName.Length+sizeof(wchar_t);
            LsaRemoveAccountRights(PolicyHandle,GetSidFromUserData(sp[i].UserData.Data),FALSE,&RightName,1);
          }
        }
        LsaClose(PolicyHandle);
      }
    }
  }
  return res;
}
Exemple #16
0
static VOID PhpAddAccountsToComboBox(
    _In_ HWND ComboBoxHandle
    )
{
    LSA_HANDLE policyHandle;
    LSA_ENUMERATION_HANDLE enumerationContext = 0;
    PLSA_ENUMERATION_INFORMATION buffer;
    ULONG count;
    ULONG i;
    PPH_STRING name;
    SID_NAME_USE nameUse;

    if (NT_SUCCESS(PhOpenLsaPolicy(&policyHandle, POLICY_VIEW_LOCAL_INFORMATION, NULL)))
    {
        while (NT_SUCCESS(LsaEnumerateAccounts(
            policyHandle,
            &enumerationContext,
            &buffer,
            0x100,
            &count
            )))
        {
            for (i = 0; i < count; i++)
            {
                name = PhGetSidFullName(buffer[i].Sid, TRUE, &nameUse);

                if (name)
                {
                    if (nameUse == SidTypeUser)
                        ComboBox_AddString(ComboBoxHandle, name->Buffer);

                    PhDereferenceObject(name);
                }
            }

            LsaFreeMemory(buffer);
        }

        LsaClose(policyHandle);
    }
}
Exemple #17
0
static BOOL ObtainLockPagesPrivilege() {
    HANDLE token;
    PTOKEN_USER user = NULL;

    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) == TRUE) {
        DWORD size = 0;

        GetTokenInformation(token, TokenUser, NULL, 0, &size);
        if (size) {
            user = (PTOKEN_USER) LocalAlloc(LPTR, size);
        }

        GetTokenInformation(token, TokenUser, user, size, &size);
        CloseHandle(token);
    }

    if (!user) {
        return FALSE;
    }

    LSA_HANDLE handle;
    LSA_OBJECT_ATTRIBUTES attributes;
    ZeroMemory(&attributes, sizeof(attributes));

    BOOL result = FALSE;
    if (LsaOpenPolicy(NULL, &attributes, POLICY_ALL_ACCESS, &handle) == 0) {
        LSA_UNICODE_STRING str = StringToLsaUnicodeString(_T(SE_LOCK_MEMORY_NAME));

        if (LsaAddAccountRights(handle, user->User.Sid, &str, 1) == 0) {
            LOG_NOTICE("Huge pages support was successfully enabled, but reboot required to use it");
            result = TRUE;
        }

        LsaClose(handle);
    }

    LocalFree(user);
    return result;
}
Exemple #18
0
static int ondata_no_sid(struct lm_sam_s *This, PUNICODE_STRING uname, HASH hash, NTSTATUS *result){
    LSA_HANDLE                      h_policy;
    LSA_OBJECT_ATTRIBUTES           objattr;
    POLICY_ACCOUNT_DOMAIN_INFO      *pdomain_info;
    NTSTATUS                        status;
    char                            dname[64];

    memset(&objattr, 0, sizeof(objattr));
    objattr.Length = sizeof(objattr);

    if((status = LsaOpenPolicy(NULL, &objattr, POLICY_VIEW_LOCAL_INFORMATION, &h_policy)) != STATUS_SUCCESS){
        DOUTST2("LsaOpenPolicy", status);
        *result = status;
        return 0;
    }

    if((status = LsaQueryInformationPolicy(h_policy, PolicyAccountDomainInformation, &pdomain_info)) != STATUS_SUCCESS){
        DOUTST2("LsaQueryInformationPolicy", status);
        LsaClose(h_policy);
        *result = status;
        return 0;
    }

    if(unicode2ansi(pdomain_info->DomainName.Buffer, pdomain_info->DomainName.Length, dname, sizeof(dname)) == 0){
        strcpy(dname, "<unknown>");
    }

    dout(va("Current domain is %s.\n", dname));

    This->lsa_policy_info_buffer = pdomain_info;
    This->domain_sid = pdomain_info->DomainSid;

    // delegate processing to no_sam state
    This->state = &state_no_sam;
    return This->state->data(This, uname, hash, result);
}
Exemple #19
0
USHORT SERVICES_grant_privilege(const TEXT* account, pfnSvcError err_handler, const WCHAR* privilege)
{
/***************************************************
 *
 * S E R V I C E _ g r a n t _ l o g o n _ r i g h t
 *
 ***************************************************
 *
 * Functional description
 *  Grants the "Log on as a service" right to account.
 *  This is a Windows NT, 2000, XP, 2003 security thing.
 *  To run a service under an account other than LocalSystem, the account
 *  must have this right. To succeed granting the right, the current user
 *  must be an Administrator.
 *  Returns FB_SUCCESS when actually granted the right.
 *  Returns FB_LOGON_SRVC_RIGHT_ALREADY_DEFINED if right was already granted
 *  to the user.
 *  Returns FB_FAILURE on any error.
 *
 *  OM - AUG 2003 - Initial implementation
 *  OM - SEP 2003 - Control flow revision, no functional change
 *
 ***************************************************/

	LSA_OBJECT_ATTRIBUTES ObjectAttributes;
	LSA_HANDLE PolicyHandle;

	// Open the policy on the local machine.
	ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes));
	NTSTATUS lsaErr = LsaOpenPolicy(NULL, &ObjectAttributes,
		POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, &PolicyHandle);
	if (lsaErr != (NTSTATUS) 0)
		return (*err_handler)(LsaNtStatusToWinError(lsaErr), "LsaOpenPolicy", NULL);

	// Obtain the SID of the user/group.
	// First, dummy call to LookupAccountName to get the required buffer sizes.
	DWORD cbSid;
	DWORD cchDomain;
	cbSid = cchDomain = 0;
	SID_NAME_USE peUse;
	LookupAccountName(NULL, account, NULL, &cbSid, NULL, &cchDomain, &peUse);
	PSID pSid = (PSID) LocalAlloc(LMEM_ZEROINIT, cbSid);
	if (pSid == 0)
	{
		DWORD err = GetLastError();
		LsaClose(PolicyHandle);
		return (*err_handler)(err, "LocalAlloc(Sid)", NULL);
	}
	TEXT* pDomain = (LPTSTR) LocalAlloc(LMEM_ZEROINIT, cchDomain);
	if (pDomain == 0)
	{
		DWORD err = GetLastError();
		LsaClose(PolicyHandle);
		LocalFree(pSid);
		return (*err_handler)(err, "LocalAlloc(Domain)", NULL);
	}
	// Now, really obtain the SID of the user/group.
	if (LookupAccountName(NULL, account, pSid, &cbSid, pDomain, &cchDomain, &peUse) == 0)
	{
		DWORD err = GetLastError();
		LsaClose(PolicyHandle);
		LocalFree(pSid);
		LocalFree(pDomain);
		return (*err_handler)(err, "LookupAccountName", NULL);
	}

	PLSA_UNICODE_STRING UserRights;
	ULONG CountOfRights = 0;
	NTSTATUS ntStatus = LsaEnumerateAccountRights(PolicyHandle, pSid, &UserRights, &CountOfRights);
	if (ntStatus == (NTSTATUS) 0xC0000034L) //STATUS_OBJECT_NAME_NOT_FOUND
		CountOfRights = 0;
	// Check if the seServiceLogonRight is already granted
	ULONG i;
	for (i = 0; i < CountOfRights; i++)
	{
		if (wcscmp(UserRights[i].Buffer, privilege) == 0)
			break;
	}
	LsaFreeMemory(UserRights); // Don't leak
	LSA_UNICODE_STRING PrivilegeString;
	if (CountOfRights == 0 || i == CountOfRights)
	{
		// Grant the SeServiceLogonRight to users represented by pSid.
		const int string_buff_size = 100;
		WCHAR tempStr[string_buff_size];
		wcsncpy(tempStr, privilege, string_buff_size - 1);
		tempStr[string_buff_size - 1] = 0;

		PrivilegeString.Buffer = tempStr;
		PrivilegeString.Length = wcslen(tempStr) * sizeof(WCHAR);
		PrivilegeString.MaximumLength = sizeof(tempStr);
		if ((lsaErr = LsaAddAccountRights(PolicyHandle, pSid, &PrivilegeString, 1)) != (NTSTATUS) 0)
		{
			LsaClose(PolicyHandle);
			LocalFree(pSid);
			LocalFree(pDomain);
			return (*err_handler)(LsaNtStatusToWinError(lsaErr), "LsaAddAccountRights", NULL);
		}
	}
	else
	{
		LsaClose(PolicyHandle);
		LocalFree(pSid);
		LocalFree(pDomain);
		return FB_PRIVILEGE_ALREADY_GRANTED;
	}

	LsaClose(PolicyHandle);
	LocalFree(pSid);
	LocalFree(pDomain);

	return FB_SUCCESS;
}
Exemple #20
0
NTSTATUS
SetAdministratorPassword(LPCWSTR Password)
{
    PPOLICY_ACCOUNT_DOMAIN_INFO OrigInfo = NULL;
    PUSER_ACCOUNT_NAME_INFORMATION AccountNameInfo = NULL;
    USER_SET_PASSWORD_INFORMATION PasswordInfo;
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    LSA_HANDLE PolicyHandle = NULL;
    SAM_HANDLE ServerHandle = NULL;
    SAM_HANDLE DomainHandle = NULL;
    SAM_HANDLE UserHandle = NULL;
    NTSTATUS Status;

    DPRINT1("SYSSETUP: SetAdministratorPassword(%S)\n", Password);

    memset(&ObjectAttributes, 0, sizeof(LSA_OBJECT_ATTRIBUTES));
    ObjectAttributes.Length = sizeof(LSA_OBJECT_ATTRIBUTES);

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_VIEW_LOCAL_INFORMATION | POLICY_TRUST_ADMIN,
                           &PolicyHandle);
    if (Status != STATUS_SUCCESS)
    {
        DPRINT1("LsaOpenPolicy() failed (Status: 0x%08lx)\n", Status);
        return Status;
    }

    Status = LsaQueryInformationPolicy(PolicyHandle,
                                       PolicyAccountDomainInformation,
                                       (PVOID *)&OrigInfo);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("LsaQueryInformationPolicy() failed (Status: 0x%08lx)\n", Status);
        goto done;
    }

    Status = SamConnect(NULL,
                        &ServerHandle,
                        SAM_SERVER_CONNECT | SAM_SERVER_LOOKUP_DOMAIN,
                        NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamConnect() failed (Status: 0x%08lx)\n", Status);
        goto done;
    }

    Status = SamOpenDomain(ServerHandle,
                           DOMAIN_LOOKUP,
                           OrigInfo->DomainSid,
                           &DomainHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamOpenDomain() failed (Status: 0x%08lx)\n", Status);
        goto done;
    }

    Status = SamOpenUser(DomainHandle,
                         USER_FORCE_PASSWORD_CHANGE | USER_READ_GENERAL,
                         DOMAIN_USER_RID_ADMIN,
                         &UserHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamOpenUser() failed (Status %08lx)\n", Status);
        goto done;
    }

    RtlInitUnicodeString(&PasswordInfo.Password, Password);
    PasswordInfo.PasswordExpired = FALSE;

    Status = SamSetInformationUser(UserHandle,
                                   UserSetPasswordInformation,
                                   (PVOID)&PasswordInfo);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamSetInformationUser() failed (Status %08lx)\n", Status);
        goto done;
    }

    Status = SamQueryInformationUser(UserHandle,
                                     UserAccountNameInformation,
                                     (PVOID*)&AccountNameInfo);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamSetInformationUser() failed (Status %08lx)\n", Status);
        goto done;
    }

    AdminInfo.Name = RtlAllocateHeap(RtlGetProcessHeap(),
                                     HEAP_ZERO_MEMORY,
                                     AccountNameInfo->UserName.Length + sizeof(WCHAR));
    if (AdminInfo.Name != NULL)
        RtlCopyMemory(AdminInfo.Name,
                      AccountNameInfo->UserName.Buffer,
                      AccountNameInfo->UserName.Length);

    AdminInfo.Domain = RtlAllocateHeap(RtlGetProcessHeap(),
                                       HEAP_ZERO_MEMORY,
                                       OrigInfo->DomainName.Length + sizeof(WCHAR));
    if (AdminInfo.Domain != NULL)
        RtlCopyMemory(AdminInfo.Domain,
                      OrigInfo->DomainName.Buffer,
                      OrigInfo->DomainName.Length);

    AdminInfo.Password = RtlAllocateHeap(RtlGetProcessHeap(),
                                         0,
                                         (wcslen(Password) + 1) * sizeof(WCHAR));
    if (AdminInfo.Password != NULL)
        wcscpy(AdminInfo.Password, Password);

    DPRINT("Administrator Name: %S\n", AdminInfo.Name);
    DPRINT("Administrator Domain: %S\n", AdminInfo.Domain);
    DPRINT("Administrator Password: %S\n", AdminInfo.Password);

done:
    if (AccountNameInfo != NULL)
        SamFreeMemory(AccountNameInfo);

    if (OrigInfo != NULL)
        LsaFreeMemory(OrigInfo);

    if (PolicyHandle != NULL)
        LsaClose(PolicyHandle);

    if (UserHandle != NULL)
        SamCloseHandle(UserHandle);

    if (DomainHandle != NULL)
        SamCloseHandle(DomainHandle);

    if (ServerHandle != NULL)
        SamCloseHandle(ServerHandle);

    DPRINT1("SYSSETUP: SetAdministratorPassword() done (Status %08lx)\n", Status);

    return Status;
}
Exemple #21
0
NTSTATUS
SetAccountDomain(LPCWSTR DomainName,
                 PSID DomainSid)
{
    PPOLICY_ACCOUNT_DOMAIN_INFO OrigInfo = NULL;
    POLICY_ACCOUNT_DOMAIN_INFO Info;
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    LSA_HANDLE PolicyHandle;

    SAM_HANDLE ServerHandle = NULL;
    SAM_HANDLE DomainHandle = NULL;
    DOMAIN_NAME_INFORMATION DomainNameInfo;

    NTSTATUS Status;

    DPRINT1("SYSSETUP: SetAccountDomain\n");

    memset(&ObjectAttributes, 0, sizeof(LSA_OBJECT_ATTRIBUTES));
    ObjectAttributes.Length = sizeof(LSA_OBJECT_ATTRIBUTES);

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_VIEW_LOCAL_INFORMATION | POLICY_TRUST_ADMIN,
                           &PolicyHandle);
    if (Status != STATUS_SUCCESS)
    {
        DPRINT("LsaOpenPolicy failed (Status: 0x%08lx)\n", Status);
        return Status;
    }

    Status = LsaQueryInformationPolicy(PolicyHandle,
                                       PolicyAccountDomainInformation,
                                       (PVOID *)&OrigInfo);
    if (Status == STATUS_SUCCESS && OrigInfo != NULL)
    {
        if (DomainName == NULL)
        {
            Info.DomainName.Buffer = OrigInfo->DomainName.Buffer;
            Info.DomainName.Length = OrigInfo->DomainName.Length;
            Info.DomainName.MaximumLength = OrigInfo->DomainName.MaximumLength;
        }
        else
        {
            Info.DomainName.Buffer = (LPWSTR)DomainName;
            Info.DomainName.Length = wcslen(DomainName) * sizeof(WCHAR);
            Info.DomainName.MaximumLength = Info.DomainName.Length + sizeof(WCHAR);
        }

        if (DomainSid == NULL)
            Info.DomainSid = OrigInfo->DomainSid;
        else
            Info.DomainSid = DomainSid;
    }
    else
    {
        Info.DomainName.Buffer = (LPWSTR)DomainName;
        Info.DomainName.Length = wcslen(DomainName) * sizeof(WCHAR);
        Info.DomainName.MaximumLength = Info.DomainName.Length + sizeof(WCHAR);
        Info.DomainSid = DomainSid;
    }

    Status = LsaSetInformationPolicy(PolicyHandle,
                                     PolicyAccountDomainInformation,
                                     (PVOID)&Info);
    if (Status != STATUS_SUCCESS)
    {
        DPRINT("LsaSetInformationPolicy failed (Status: 0x%08lx)\n", Status);
    }

    if (OrigInfo != NULL)
        LsaFreeMemory(OrigInfo);

    LsaClose(PolicyHandle);

    DomainNameInfo.DomainName.Length = wcslen(DomainName) * sizeof(WCHAR);
    DomainNameInfo.DomainName.MaximumLength = (wcslen(DomainName) + 1) * sizeof(WCHAR);
    DomainNameInfo.DomainName.Buffer = (LPWSTR)DomainName;

    Status = SamConnect(NULL,
                        &ServerHandle,
                        SAM_SERVER_CONNECT | SAM_SERVER_LOOKUP_DOMAIN,
                        NULL);
    if (NT_SUCCESS(Status))
    {
        Status = SamOpenDomain(ServerHandle,
                               DOMAIN_WRITE_OTHER_PARAMETERS,
                               Info.DomainSid,
                               &DomainHandle);
        if (NT_SUCCESS(Status))
        {
            Status = SamSetInformationDomain(DomainHandle,
                                             DomainNameInformation,
                                             (PVOID)&DomainNameInfo);
            if (!NT_SUCCESS(Status))
            {
                DPRINT1("SamSetInformationDomain failed (Status: 0x%08lx)\n", Status);
            }

            SamCloseHandle(DomainHandle);
        }
        else
        {
            DPRINT1("SamOpenDomain failed (Status: 0x%08lx)\n", Status);
        }

        SamCloseHandle(ServerHandle);
    }

    return Status;
}
Exemple #22
0
static
VOID
InstallPrivileges(VOID)
{
    HINF hSecurityInf = INVALID_HANDLE_VALUE;
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    WCHAR szPrivilegeString[256];
    WCHAR szSidString[256];
    INFCONTEXT InfContext;
    DWORD i;
    PRIVILEGE_SET PrivilegeSet;
    PSID AccountSid;
    NTSTATUS Status;
    LSA_HANDLE PolicyHandle = NULL;
    LSA_HANDLE AccountHandle;

    DPRINT("InstallPrivileges()\n");

    hSecurityInf = SetupOpenInfFileW(L"defltws.inf", //szNameBuffer,
                                     NULL,
                                     INF_STYLE_WIN4,
                                     NULL);
    if (hSecurityInf == INVALID_HANDLE_VALUE)
    {
        DPRINT1("SetupOpenInfFileW failed\n");
        return;
    }

    memset(&ObjectAttributes, 0, sizeof(LSA_OBJECT_ATTRIBUTES));

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_CREATE_ACCOUNT,
                           &PolicyHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("LsaOpenPolicy failed (Status %08lx)\n", Status);
        goto done;
    }

    if (!SetupFindFirstLineW(hSecurityInf,
                             L"Privilege Rights",
                             NULL,
                             &InfContext))
    {
        DPRINT1("SetupFindfirstLineW failed\n");
        goto done;
    }

    PrivilegeSet.PrivilegeCount = 1;
    PrivilegeSet.Control = 0;

    do
    {
        /* Retrieve the privilege name */
        if (!SetupGetStringFieldW(&InfContext,
                                  0,
                                  szPrivilegeString,
                                  256,
                                  NULL))
        {
            DPRINT1("SetupGetStringFieldW() failed\n");
            goto done;
        }
        DPRINT("Privilege: %S\n", szPrivilegeString);

        if (!LookupPrivilegeValueW(NULL,
                                   szPrivilegeString,
                                   &(PrivilegeSet.Privilege[0].Luid)))
        {
            DPRINT1("LookupPrivilegeNameW() failed\n");
            goto done;
        }

        PrivilegeSet.Privilege[0].Attributes = 0;

        for (i = 0; i < SetupGetFieldCount(&InfContext); i++)
        {
            if (!SetupGetStringFieldW(&InfContext,
                                      i + 1,
                                      szSidString,
                                      256,
                                      NULL))
            {
                DPRINT1("SetupGetStringFieldW() failed\n");
                goto done;
            }
            DPRINT("SID: %S\n", szSidString);

            ConvertStringSidToSid(szSidString, &AccountSid);

            Status = LsaOpenAccount(PolicyHandle,
                                    AccountSid,
                                    ACCOUNT_VIEW | ACCOUNT_ADJUST_PRIVILEGES,
                                    &AccountHandle);
            if (NT_SUCCESS(Status))
            {
                Status = LsaAddPrivilegesToAccount(AccountHandle,
                                                   &PrivilegeSet);
                if (!NT_SUCCESS(Status))
                {
                    DPRINT1("LsaAddPrivilegesToAccount() failed (Status %08lx)\n", Status);
                }

                LsaClose(AccountHandle);
            }

            LocalFree(AccountSid);
        }

    }
    while (SetupFindNextLine(&InfContext, &InfContext));

done:
    if (PolicyHandle != NULL)
        LsaClose(PolicyHandle);

    if (hSecurityInf != INVALID_HANDLE_VALUE)
        SetupCloseInfFile(hSecurityInf);
}
Exemple #23
0
/************************************************************
 *  DsRoleGetPrimaryDomainInformation  (NETAPI32.@)
 *
 * PARAMS
 *  lpServer  [I] Pointer to UNICODE string with ComputerName
 *  InfoLevel [I] Type of data to retrieve	
 *  Buffer    [O] Pointer to to the requested data
 *
 * RETURNS
 *
 * NOTES
 *  When lpServer is NULL, use the local computer
 */
DWORD WINAPI DsRoleGetPrimaryDomainInformation(
    LPCWSTR lpServer, DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
    PBYTE* Buffer)
{
    DWORD ret;

    FIXME("(%p, %d, %p) stub\n", lpServer, InfoLevel, Buffer);

    /* Check some input parameters */

    if (!Buffer) return ERROR_INVALID_PARAMETER;
    if ((InfoLevel < DsRolePrimaryDomainInfoBasic) || (InfoLevel > DsRoleOperationState)) return ERROR_INVALID_PARAMETER;

    *Buffer = NULL;
    switch (InfoLevel)
    {
        case DsRolePrimaryDomainInfoBasic:
        {
            LSA_OBJECT_ATTRIBUTES ObjectAttributes;
            LSA_HANDLE PolicyHandle;
            PPOLICY_ACCOUNT_DOMAIN_INFO DomainInfo;
            NTSTATUS NtStatus;
            int logon_domain_sz;
            DWORD size;
            PDSROLE_PRIMARY_DOMAIN_INFO_BASIC basic;

            ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes));
            NtStatus = LsaOpenPolicy(NULL, &ObjectAttributes,
             POLICY_VIEW_LOCAL_INFORMATION, &PolicyHandle);
            if (NtStatus != STATUS_SUCCESS)
            {
                TRACE("LsaOpenPolicyFailed with NT status %x\n",
                    LsaNtStatusToWinError(NtStatus));
                return ERROR_OUTOFMEMORY;
            }
            LsaQueryInformationPolicy(PolicyHandle,
             PolicyAccountDomainInformation, (PVOID*)&DomainInfo);
            logon_domain_sz = lstrlenW(DomainInfo->DomainName.Buffer) + 1;
            LsaClose(PolicyHandle);

            size = sizeof(DSROLE_PRIMARY_DOMAIN_INFO_BASIC) +
             logon_domain_sz * sizeof(WCHAR);
            basic = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
            if (basic)
            {
                basic->MachineRole = DsRole_RoleStandaloneWorkstation;
                basic->DomainNameFlat = (LPWSTR)((LPBYTE)basic +
                 sizeof(DSROLE_PRIMARY_DOMAIN_INFO_BASIC));
                lstrcpyW(basic->DomainNameFlat, DomainInfo->DomainName.Buffer);
                ret = ERROR_SUCCESS;
            }
            else
                ret = ERROR_OUTOFMEMORY;
            *Buffer = (PBYTE)basic;
            LsaFreeMemory(DomainInfo);
        }
        break;
    default:
        ret = ERROR_CALL_NOT_IMPLEMENTED;
    }
    return ret;
}
Exemple #24
0
/* Hack */
static
NTSTATUS
SetPrimaryDomain(LPCWSTR DomainName,
                 PSID DomainSid)
{
    PPOLICY_PRIMARY_DOMAIN_INFO OrigInfo = NULL;
    POLICY_PRIMARY_DOMAIN_INFO Info;
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    LSA_HANDLE PolicyHandle;
    NTSTATUS Status;

    DPRINT1("SYSSETUP: SetPrimaryDomain()\n");

    memset(&ObjectAttributes, 0, sizeof(LSA_OBJECT_ATTRIBUTES));
    ObjectAttributes.Length = sizeof(LSA_OBJECT_ATTRIBUTES);

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_VIEW_LOCAL_INFORMATION | POLICY_TRUST_ADMIN,
                           &PolicyHandle);
    if (Status != STATUS_SUCCESS)
    {
        DPRINT("LsaOpenPolicy failed (Status: 0x%08lx)\n", Status);
        return Status;
    }

    Status = LsaQueryInformationPolicy(PolicyHandle,
                                       PolicyPrimaryDomainInformation,
                                       (PVOID *)&OrigInfo);
    if (Status == STATUS_SUCCESS && OrigInfo != NULL)
    {
        if (DomainName == NULL)
        {
            Info.Name.Buffer = OrigInfo->Name.Buffer;
            Info.Name.Length = OrigInfo->Name.Length;
            Info.Name.MaximumLength = OrigInfo->Name.MaximumLength;
        }
        else
        {
            Info.Name.Buffer = (LPWSTR)DomainName;
            Info.Name.Length = wcslen(DomainName) * sizeof(WCHAR);
            Info.Name.MaximumLength = Info.Name.Length + sizeof(WCHAR);
        }

        if (DomainSid == NULL)
            Info.Sid = OrigInfo->Sid;
        else
            Info.Sid = DomainSid;
    }
    else
    {
        Info.Name.Buffer = (LPWSTR)DomainName;
        Info.Name.Length = wcslen(DomainName) * sizeof(WCHAR);
        Info.Name.MaximumLength = Info.Name.Length + sizeof(WCHAR);
        Info.Sid = DomainSid;
    }

    Status = LsaSetInformationPolicy(PolicyHandle,
                                     PolicyPrimaryDomainInformation,
                                     (PVOID)&Info);
    if (Status != STATUS_SUCCESS)
    {
        DPRINT("LsaSetInformationPolicy failed (Status: 0x%08lx)\n", Status);
    }

    if (OrigInfo != NULL)
        LsaFreeMemory(OrigInfo);

    LsaClose(PolicyHandle);

    return Status;
}
Exemple #25
0
void lsa_close(LSA_HANDLE lsa_handle)
{
  LsaClose(lsa_handle);
}
mDNSBool
LsaGetSecret( const char * inDomain, char * outDomain, unsigned outDomainSize, char * outKey, unsigned outKeySize, char * outSecret, unsigned outSecretSize )
{
    PLSA_UNICODE_STRING		domainLSA;
    PLSA_UNICODE_STRING		keyLSA;
    PLSA_UNICODE_STRING		secretLSA;
    size_t					i;
    size_t					dlen;
    LSA_OBJECT_ATTRIBUTES	attrs;
    LSA_HANDLE				handle = NULL;
    NTSTATUS				res;
    OSStatus				err;

    check( inDomain );
    check( outDomain );
    check( outKey );
    check( outSecret );

    // Initialize

    domainLSA	= NULL;
    keyLSA		= NULL;
    secretLSA	= NULL;

    // Make sure we have enough space to add trailing dot

    dlen = strlen( inDomain );
    err = strcpy_s( outDomain, outDomainSize - 2, inDomain );
    require_noerr( err, exit );

    // If there isn't a trailing dot, add one because the mDNSResponder
    // presents names with the trailing dot.

    if ( outDomain[ dlen - 1 ] != '.' )
    {
        outDomain[ dlen++ ] = '.';
        outDomain[ dlen ] = '\0';
    }

    // Canonicalize name by converting to lower case (keychain and some name servers are case sensitive)

    for ( i = 0; i < dlen; i++ )
    {
        outDomain[i] = (char) tolower( outDomain[i] );  // canonicalize -> lower case
    }

    // attrs are reserved, so initialize to zeroes.

    ZeroMemory( &attrs, sizeof( attrs ) );

    // Get a handle to the Policy object on the local system

    res = LsaOpenPolicy( NULL, &attrs, POLICY_GET_PRIVATE_INFORMATION, &handle );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr( err, exit );

    // Get the encrypted data

    domainLSA = ( PLSA_UNICODE_STRING ) malloc( sizeof( LSA_UNICODE_STRING ) );
    require_action( domainLSA != NULL, exit, err = mStatus_NoMemoryErr );
    err = MakeLsaStringFromUTF8String( domainLSA, outDomain );
    require_noerr( err, exit );

    // Retrieve the key

    res = LsaRetrievePrivateData( handle, domainLSA, &keyLSA );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr_quiet( err, exit );

    // <rdar://problem/4192119> Lsa secrets use a flat naming space.  Therefore, we will prepend "$" to the keyname to
    // make sure it doesn't conflict with a zone name.
    // Strip off the "$" prefix.

    err = MakeUTF8StringFromLsaString( outKey, outKeySize, keyLSA );
    require_noerr( err, exit );
    require_action( outKey[0] == '$', exit, err = kUnknownErr );
    memcpy( outKey, outKey + 1, strlen( outKey ) );

    // Retrieve the secret

    res = LsaRetrievePrivateData( handle, keyLSA, &secretLSA );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr_quiet( err, exit );

    // Convert the secret to UTF8 string

    err = MakeUTF8StringFromLsaString( outSecret, outSecretSize, secretLSA );
    require_noerr( err, exit );

exit:

    if ( domainLSA != NULL )
    {
        if ( domainLSA->Buffer != NULL )
        {
            free( domainLSA->Buffer );
        }

        free( domainLSA );
    }

    if ( keyLSA != NULL )
    {
        LsaFreeMemory( keyLSA );
    }

    if ( secretLSA != NULL )
    {
        LsaFreeMemory( secretLSA );
    }

    if ( handle )
    {
        LsaClose( handle );
        handle = NULL;
    }

    return ( !err ) ? TRUE : FALSE;
}
mDNSBool
LsaSetSecret( const char * inDomain, const char * inKey, const char * inSecret )
{
    size_t					inDomainLength;
    size_t					inKeyLength;
    char					domain[ 1024 ];
    char					key[ 1024 ];
    LSA_OBJECT_ATTRIBUTES	attrs;
    LSA_HANDLE				handle = NULL;
    NTSTATUS				res;
    LSA_UNICODE_STRING		lucZoneName;
    LSA_UNICODE_STRING		lucKeyName;
    LSA_UNICODE_STRING		lucSecretName;
    BOOL					ok = TRUE;
    OSStatus				err;

    require_action( inDomain != NULL, exit, ok = FALSE );
    require_action( inKey != NULL, exit, ok = FALSE );
    require_action( inSecret != NULL, exit, ok = FALSE );

    // If there isn't a trailing dot, add one because the mDNSResponder
    // presents names with the trailing dot.

    ZeroMemory( domain, sizeof( domain ) );
    inDomainLength = strlen( inDomain );
    require_action( inDomainLength > 0, exit, ok = FALSE );
    err = strcpy_s( domain, sizeof( domain ) - 2, inDomain );
    require_action( !err, exit, ok = FALSE );

    if ( domain[ inDomainLength - 1 ] != '.' )
    {
        domain[ inDomainLength++ ] = '.';
        domain[ inDomainLength ] = '\0';
    }

    // <rdar://problem/4192119>
    //
    // Prepend "$" to the key name, so that there will
    // be no conflict between the zone name and the key
    // name

    ZeroMemory( key, sizeof( key ) );
    inKeyLength = strlen( inKey );
    require_action( inKeyLength > 0 , exit, ok = FALSE );
    key[ 0 ] = '$';
    err = strcpy_s( key + 1, sizeof( key ) - 3, inKey );
    require_action( !err, exit, ok = FALSE );
    inKeyLength++;

    if ( key[ inKeyLength - 1 ] != '.' )
    {
        key[ inKeyLength++ ] = '.';
        key[ inKeyLength ] = '\0';
    }

    // attrs are reserved, so initialize to zeroes.

    ZeroMemory( &attrs, sizeof( attrs ) );

    // Get a handle to the Policy object on the local system

    res = LsaOpenPolicy( NULL, &attrs, POLICY_ALL_ACCESS, &handle );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr( err, exit );

    // Intializing PLSA_UNICODE_STRING structures

    err = MakeLsaStringFromUTF8String( &lucZoneName, domain );
    require_noerr( err, exit );

    err = MakeLsaStringFromUTF8String( &lucKeyName, key );
    require_noerr( err, exit );

    err = MakeLsaStringFromUTF8String( &lucSecretName, inSecret );
    require_noerr( err, exit );

    // Store the private data.

    res = LsaStorePrivateData( handle, &lucZoneName, &lucKeyName );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr( err, exit );

    res = LsaStorePrivateData( handle, &lucKeyName, &lucSecretName );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr( err, exit );

exit:

    if ( handle )
    {
        LsaClose( handle );
        handle = NULL;
    }

    return ok;
}
int
__cdecl
main(
    int argc,
    char *argv[]
    )
{
    LSA_HANDLE PolicyHandle;
    WCHAR wComputerName[256]=L"";   // static machine name buffer
    TCHAR AccountName[256];         // static account name buffer
    PSID pSid;
    NTSTATUS Status;
    int iRetVal=RTN_ERROR;          // assume error from main

    if(argc == 1) {
        fprintf(stderr,"Usage: %s <Account> [TargetMachine]\n", argv[0]);
        return RTN_USAGE;
    }

    //
    // Pick up account name on argv[1].
    // Assumes source is ANSI. Resultant string is ANSI or Unicode
    //
    _snwprintf_s(AccountName, 256, 255, TEXT("%hS"), argv[1]);

    //
    // Pick up machine name on argv[2], if appropriate
    // assumes source is ANSI. Resultant string is Unicode.
    //
    if(argc == 3) _snwprintf_s(wComputerName, 256, 255, L"%hS", argv[2]);

    //
    // Open the policy on the target machine. 
    //
    Status = OpenPolicy(
                wComputerName,      // target machine
                POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES,
                &PolicyHandle       // resultant policy handle
                );

    if(Status != STATUS_SUCCESS) {
        DisplayNtStatus("OpenPolicy", Status);
        return RTN_ERROR;
    }

    //
    // Obtain the SID of the user/group.
    // Note that we could target a specific machine, but we don't.
    // Specifying NULL for target machine searches for the SID in the
    // following order: well-known, Built-in and local, primary domain,
    // trusted domains.
    //
    if(GetAccountSid(
            NULL,       // default lookup logic
            AccountName,// account to obtain SID
            &pSid       // buffer to allocate to contain resultant SID
            )) {
        //
        // We only grant the privilege if we succeeded in obtaining the
        // SID. We can actually add SIDs which cannot be looked up, but
        // looking up the SID is a good sanity check which is suitable for
        // most cases.

        //
        // Grant the SeServiceLogonRight to users represented by pSid.
        //
        Status = SetPrivilegeOnAccount(
                    PolicyHandle,           // policy handle
                    pSid,                   // SID to grant privilege
                    L"SeServiceLogonRight", // Unicode privilege
                    TRUE                    // enable the privilege
                    );

        if(Status == STATUS_SUCCESS)
            iRetVal=RTN_OK;
        else
            DisplayNtStatus("SetPrivilegeOnAccount", Status);
    }
    else {
        //
        // Error obtaining SID.
        //
        DisplayWinError("GetAccountSid", GetLastError());
    }

    //
    // Close the policy handle.
    //
    LsaClose(PolicyHandle);

    //
    // Free memory allocated for SID.
    //
    if(pSid != NULL) HeapFree(GetProcessHeap(), 0, pSid);

    return iRetVal;
}
Exemple #29
0
NTSTATUS
LsapGetAccountDomainInfo(
    PPOLICY_ACCOUNT_DOMAIN_INFO *PolicyAccountDomainInfo
    )

/*++

Routine Description:

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


Arguments:

    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 Status, IgnoreStatus;

    LSA_HANDLE PolicyHandle;
    OBJECT_ATTRIBUTES PolicyObjectAttributes;

    //
    // Open the policy database
    //

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

    Status = LsaOpenPolicy( NULL,
                            &PolicyObjectAttributes,
                            POLICY_VIEW_LOCAL_INFORMATION,
                            &PolicyHandle );
    if ( NT_SUCCESS(Status) ) {


        //
        // Query the account domain information
        //

        Status = LsaQueryInformationPolicy( PolicyHandle,
                                            PolicyAccountDomainInformation,
                                            (PVOID *) PolicyAccountDomainInfo );
#if DBG
        if ( NT_SUCCESS(Status) ) {
            ASSERT( (*PolicyAccountDomainInfo) != NULL );
            ASSERT( (*PolicyAccountDomainInfo)->DomainSid != NULL );
        }
#endif // DBG


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

    return(Status);
}
//
// unicode entry point and argv
//
int
__cdecl
wmain(
    int argc,
    wchar_t *argv[]
    )
{
    LPWSTR wComputerName;
    LSA_HANDLE PolicyHandle;
    NTSTATUS Status;

    //
    // pickup machine name if appropriate
    //
    if(argc == 2)
        wComputerName = argv[1];
    else
        wComputerName = NULL; // local machine

    //
    // display current audit state
    //

    Status = OpenPolicy(
                wComputerName,
                POLICY_VIEW_AUDIT_INFORMATION,
                &PolicyHandle
                );

    if(Status == STATUS_SUCCESS) {
        //
        // display current auditing status
        //
        Status = DisplayAudit(PolicyHandle);

        LsaClose(PolicyHandle);

        if(Status != STATUS_SUCCESS) {
            DisplayNtStatus("DisplayAudit", Status);
            return RTN_ERROR;
        }
    } else {
        DisplayNtStatus("OpenPolicy", Status);
        return RTN_ERROR;
    }

    //
    // enable success and failure audits of logon/logoff events
    //

    Status = OpenPolicy(
                wComputerName,
                POLICY_VIEW_AUDIT_INFORMATION |
                POLICY_SET_AUDIT_REQUIREMENTS,
                &PolicyHandle
                );

    if(Status == STATUS_SUCCESS) {

        //
        // enable success and failure auditing of logon/logoff
        //
        Status = SetAuditEvent(
            PolicyHandle,
            AuditCategoryLogon,
            POLICY_AUDIT_EVENT_SUCCESS | POLICY_AUDIT_EVENT_FAILURE
            );

        //
        // enable audits
        //
        if( Status == STATUS_SUCCESS )
            Status = SetAuditMode(PolicyHandle, TRUE);

        LsaClose(PolicyHandle);

        if(Status != STATUS_SUCCESS) {
            DisplayNtStatus("SetAuditMode", Status);
            return RTN_ERROR;
        }
    } else {
        DisplayNtStatus("OpenPolicy", Status);
        return RTN_ERROR;
    }

    return RTN_OK;
}