Esempio n. 1
0
NTSTATUS
LsaSrvSidAppendRid(
    PSID *ppOutSid,
    PSID pInSid,
    DWORD dwRid
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    DWORD dwSidLen = 0;
    PSID pSid = NULL;

    dwSidLen = RtlLengthRequiredSid(pInSid->SubAuthorityCount + 1);
    ntStatus = LsaSrvAllocateMemory((void**)&pSid, dwSidLen);
    BAIL_ON_NTSTATUS_ERROR(ntStatus);

    ntStatus = RtlCopySid(dwSidLen, pSid, pInSid);
    BAIL_ON_NTSTATUS_ERROR(ntStatus);

    ntStatus = RtlAppendRidSid(dwSidLen, pSid, dwRid);
    BAIL_ON_NTSTATUS_ERROR(ntStatus);

    *ppOutSid = pSid;

cleanup:
    return ntStatus;

error:
    if (pSid) {
        LsaSrvFreeMemory(pSid);
    }

    *ppOutSid = NULL;
    goto cleanup;
}
Esempio n. 2
0
NTSTATUS
LsaSrvDuplicateSid(
    PSID *ppSidOut,
    PSID pSidIn
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSID pSid = NULL;
    ULONG ulSidSize = 0;

    ulSidSize = RtlLengthSid(pSidIn);
    ntStatus = LsaSrvAllocateMemory((void**)&pSid,
                                  ulSidSize);
    BAIL_ON_NTSTATUS_ERROR(ntStatus);

    ntStatus = RtlCopySid(ulSidSize, pSid, pSidIn);
    BAIL_ON_NTSTATUS_ERROR(ntStatus);

    *ppSidOut = pSid;

cleanup:
    return ntStatus;

error:
    if (pSid) {
        LsaSrvFreeMemory(pSid);
    }

    *ppSidOut = NULL;
    goto cleanup;
}
Esempio n. 3
0
NTSTATUS
NTAPI
ScDomainIdToSid (
    _In_ PSID SourceSid,
    _In_ ULONG DomainId,
    _Out_ PSID *DestinationSid
    )
{
    ULONG sidCount, sidLength;
    NTSTATUS status;

    /* Get the length of the SID based onthe number of subauthorities */
    sidCount = *RtlSubAuthorityCountSid(SourceSid);
    sidLength = RtlLengthRequiredSid(sidCount + 1);

    /* Allocate it */
    *DestinationSid = RtlAllocateHeap(RtlGetProcessHeap(), 0, sidLength);
    if (*DestinationSid)
    {
        /* Make a copy of it */
        status = RtlCopySid(sidLength, *DestinationSid, SourceSid);
        if (NT_SUCCESS(status))
        {
            /* Increase the subauthority count */
            ++*RtlSubAuthorityCountSid(*DestinationSid);

            /* And add the specific domain RID we're creating */
            *RtlSubAuthoritySid(*DestinationSid, sidCount) = DomainId;

            /* Everything worked */
            status = STATUS_SUCCESS;
        }
        else
        {
            /* The SID copy failed, so free the SID we just allocated */
            RtlFreeHeap(RtlGetProcessHeap(), 0, *DestinationSid);
        }
    }
    else
    {
        /* No space for the SID, bail out */
        status = STATUS_NO_MEMORY;
    }

    /* Return back to the caller */
    return status;
}
Esempio n. 4
0
DWORD
VmDirRESTCacheGetBuiltInAdminsGroupSid(
    PVDIR_REST_HEAD_CACHE   pRestCache,
    PSID*                   ppBuiltInAdminsGroupSid
    )
{
    DWORD   dwError = 0;
    ULONG   ulSidLen = 0;
    BOOLEAN bInLock = FALSE;
    PSID    pSid = NULL;

    if (!pRestCache || !ppBuiltInAdminsGroupSid)
    {
        BAIL_WITH_VMDIR_ERROR(dwError, VMDIR_ERROR_INVALID_PARAMETER);
    }

    VMDIR_RWLOCK_READLOCK(bInLock, gpVdirRestCache->pRWLock, 0);

    if (!RtlValidSid(pRestCache->pBuiltInAdminsGroupSid))
    {
        BAIL_WITH_VMDIR_ERROR(dwError, VMDIR_ERROR_NOT_FOUND);
    }

    ulSidLen = RtlLengthSid(pRestCache->pBuiltInAdminsGroupSid);

    dwError = VmDirAllocateMemory(ulSidLen, (PVOID*)&pSid);
    BAIL_ON_VMDIR_ERROR(dwError);

    dwError = RtlCopySid(ulSidLen, pSid, pRestCache->pBuiltInAdminsGroupSid);
    BAIL_ON_VMDIR_ERROR(dwError);

    *ppBuiltInAdminsGroupSid = pSid;

cleanup:
    VMDIR_RWLOCK_UNLOCK(bInLock, gpVdirRestCache->pRWLock);
    return dwError;

error:
    VMDIR_LOG_ERROR(
            VMDIR_LOG_MASK_ALL,
            "%s failed, error (%d)",
            __FUNCTION__,
            dwError);

    VMDIR_SAFE_FREE_MEMORY(pSid);
    goto cleanup;
}
Esempio n. 5
0
NTSTATUS
LsaSrvAllocateSidFromWC16String(
    PSID *ppSid,
    PCWSTR pwszSidStr
    )
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PSID pSid = NULL;
    ULONG ulSidSize = 0;
    PSID pSidCopy = NULL;

    ntStatus = RtlAllocateSidFromWC16String(&pSid,
                                          pwszSidStr);
    BAIL_ON_NTSTATUS_ERROR(ntStatus);

    ulSidSize = RtlLengthSid(pSid);
    ntStatus = LsaSrvAllocateMemory((void**)&pSidCopy,
                                  ulSidSize);
    BAIL_ON_NTSTATUS_ERROR(ntStatus);

    ntStatus = RtlCopySid(ulSidSize, pSidCopy, pSid);
    BAIL_ON_NTSTATUS_ERROR(ntStatus);

    *ppSid = pSidCopy;

cleanup:
    if (pSid) {
        RTL_FREE(&pSid);
    }

    return ntStatus;

error:
    if (pSidCopy) {
        LsaSrvFreeMemory(pSidCopy);
    }

    *ppSid = NULL;
    goto cleanup;
}
Esempio n. 6
0
/*
 * @implemented
 */
NTSTATUS NTAPI
RtlCopySidAndAttributesArray(ULONG Count,
                             PSID_AND_ATTRIBUTES Src,
                             ULONG SidAreaSize,
                             PSID_AND_ATTRIBUTES Dest,
                             PVOID SidArea,
                             PVOID* RemainingSidArea,
                             PULONG RemainingSidAreaSize)
{
   ULONG SidLength;
   ULONG Length;
   ULONG i;

   PAGED_CODE_RTL();

   Length = SidAreaSize;

   for (i=0; i<Count; i++)
   {
      if (RtlLengthSid(Src[i].Sid) > Length)
      {
         return(STATUS_BUFFER_TOO_SMALL);
      }
      SidLength = RtlLengthSid(Src[i].Sid);
      Length = Length - SidLength;
      Dest[i].Sid = SidArea;
      Dest[i].Attributes = Src[i].Attributes;
      RtlCopySid(SidLength,
                 SidArea,
                 Src[i].Sid);
      SidArea = (PVOID)((ULONG_PTR)SidArea + SidLength);
   }
   *RemainingSidArea = SidArea;
   *RemainingSidAreaSize = Length;
   return(STATUS_SUCCESS);
}
Esempio n. 7
0
File: misc.c Progetto: GYGit/reactos
BOOL
GetUserSidFromToken(HANDLE hToken,
                    PSID *Sid)
{
    PTOKEN_USER UserBuffer, nsb;
    PSID pSid = NULL;
    ULONG Length;
    NTSTATUS Status;

    Length = 256;
    UserBuffer = LocalAlloc(LPTR, Length);
    if (UserBuffer == NULL)
    {
        return FALSE;
    }

    Status = NtQueryInformationToken(hToken,
                                     TokenUser,
                                     (PVOID)UserBuffer,
                                     Length,
                                     &Length);
    if (Status == STATUS_BUFFER_TOO_SMALL)
    {
        nsb = LocalReAlloc(UserBuffer, Length, LMEM_MOVEABLE);
        if (nsb == NULL)
        {
            LocalFree(UserBuffer);
            return FALSE;
        }

        UserBuffer = nsb;
        Status = NtQueryInformationToken(hToken,
                                         TokenUser,
                                         (PVOID)UserBuffer,
                                         Length,
                                         &Length);
    }

    if (!NT_SUCCESS (Status))
    {
        LocalFree(UserBuffer);
        return FALSE;
    }

    Length = RtlLengthSid(UserBuffer->User.Sid);

    pSid = LocalAlloc(LPTR, Length);
    if (pSid == NULL)
    {
        LocalFree(UserBuffer);
        return FALSE;
    }

    Status = RtlCopySid(Length, pSid, UserBuffer->User.Sid);

    LocalFree(UserBuffer);

    if (!NT_SUCCESS (Status))
    {
        LocalFree(pSid);
        return FALSE;
    }

    *Sid = pSid;

    return TRUE;
}
Esempio n. 8
0
NET_API_STATUS
NetUserGetLocalGroups(
    PCWSTR  pwszHostname,
    PCWSTR  pwszUsername,
    DWORD   dwLevel,
    DWORD   dwFlags,
    PVOID  *ppBuffer,
    DWORD   dwMaxBufferSize,
    PDWORD  pdwNumEntries,
    PDWORD  pdwTotalEntries
)
{
    const DWORD dwBuiltinDomainAccess = DOMAIN_ACCESS_OPEN_ACCOUNT |
                                        DOMAIN_ACCESS_ENUM_ACCOUNTS;

    const DWORD dwUserAccess = USER_ACCESS_GET_GROUP_MEMBERSHIP;

    NTSTATUS status = STATUS_SUCCESS;
    WINERROR err = ERROR_SUCCESS;
    PNET_CONN pConn = NULL;
    SAMR_BINDING hSamrBinding = NULL;
    DOMAIN_HANDLE hDomain = NULL;
    DOMAIN_HANDLE hBtinDomain = NULL;
    ACCOUNT_HANDLE hUser = NULL;
    PSID pDomainSid = NULL;
    PSID pUserSid = NULL;
    DWORD dwUserRid = 0;
    DWORD dwSidLen = 0;
    DWORD i = 0;
    PDWORD pdwUserRids = NULL;
    PDWORD pdwBuiltinUserRids = NULL;
    DWORD dwRidsCount = 0;
    DWORD dwBuiltinRidsCount = 0;
    DWORD dwInfoLevelSize = 0;
    DWORD dwTotalNumEntries = 0;
    PWSTR *ppwszAliasNames = NULL;
    PWSTR *ppwszBuiltinAliasNames = NULL;
    PDWORD pdwAliasTypes = NULL;
    PDWORD pdwBuiltinAliasTypes = NULL;
    PWSTR *ppwszLocalGroupNames = NULL;
    PVOID pSourceBuffer = NULL;
    PVOID pBuffer = NULL;
    PVOID pBufferCursor = NULL;
    DWORD dwSize = 0;
    DWORD dwTotalSize = 0;
    DWORD dwNumEntries = 0;
    DWORD dwSpaceAvailable = 0;
    PIO_CREDS pCreds = NULL;
    NET_VALIDATION_LEVEL eValidation = NET_VALIDATION_NONE;

    BAIL_ON_INVALID_PTR(pwszUsername, err);
    BAIL_ON_INVALID_PTR(ppBuffer, err);
    BAIL_ON_INVALID_PTR(pdwNumEntries, err);
    BAIL_ON_INVALID_PTR(pdwTotalEntries, err);

    switch (dwLevel)
    {
    case 0:
        dwInfoLevelSize = sizeof(LOCALGROUP_USERS_INFO_0);
        break;

    default:
        err = ERROR_INVALID_LEVEL;
        BAIL_ON_WIN_ERROR(err);
    }

    status = LwIoGetActiveCreds(NULL, &pCreds);
    BAIL_ON_NT_STATUS(status);

    status = NetConnectSamr(&pConn,
                            pwszHostname,
                            0,
                            dwBuiltinDomainAccess,
                            pCreds);
    BAIL_ON_NT_STATUS(status);

    hSamrBinding = pConn->Rpc.Samr.hBinding;
    hDomain      = pConn->Rpc.Samr.hDomain;
    hBtinDomain  = pConn->Rpc.Samr.hBuiltin;
    pDomainSid   = pConn->Rpc.Samr.pDomainSid;

    status = NetOpenUser(pConn,
                         pwszUsername,
                         dwUserAccess,
                         &hUser,
                         &dwUserRid);
    BAIL_ON_NT_STATUS(status);

    dwSidLen = RtlLengthRequiredSid(pDomainSid->SubAuthorityCount + 1);
    err = LwAllocateMemory(dwSidLen,
                           OUT_PPVOID(&pUserSid));
    BAIL_ON_WIN_ERROR(err);

    status = RtlCopySid(dwSidLen,
                        pUserSid,
                        pDomainSid);
    BAIL_ON_NT_STATUS(status);

    status = RtlAppendRidSid(dwSidLen,
                             pUserSid,
                             dwUserRid);
    BAIL_ON_NT_STATUS(status);

    status = SamrGetAliasMembership(hSamrBinding,
                                    hDomain,
                                    &pUserSid,
                                    1,
                                    &pdwUserRids,
                                    &dwRidsCount);
    BAIL_ON_NT_STATUS(status);

    status = SamrGetAliasMembership(hSamrBinding,
                                    hBtinDomain,
                                    &pUserSid,
                                    1,
                                    &pdwBuiltinUserRids,
                                    &dwBuiltinRidsCount);
    BAIL_ON_NT_STATUS(status);

    dwTotalNumEntries = dwRidsCount + dwBuiltinRidsCount;

    err = LwAllocateMemory(
              sizeof(ppwszLocalGroupNames[0]) * dwTotalNumEntries,
              OUT_PPVOID(&ppwszLocalGroupNames));
    BAIL_ON_WIN_ERROR(err);

    if (dwRidsCount > 0)
    {
        status = SamrLookupRids(hSamrBinding,
                                hDomain,
                                dwRidsCount,
                                pdwUserRids,
                                &ppwszAliasNames,
                                &pdwAliasTypes);
        BAIL_ON_NT_STATUS(status);

        for (i = 0; i < dwRidsCount; i++)
        {
            ppwszLocalGroupNames[i] = ppwszAliasNames[i];
        }
    }

    if (dwBuiltinRidsCount > 0)
    {
        status = SamrLookupRids(hSamrBinding,
                                hBtinDomain,
                                dwBuiltinRidsCount,
                                pdwBuiltinUserRids,
                                &ppwszBuiltinAliasNames,
                                &pdwBuiltinAliasTypes);
        BAIL_ON_NT_STATUS(status);

        for (i = 0; i < dwBuiltinRidsCount; i++)
        {
            ppwszLocalGroupNames[i + dwRidsCount] = ppwszBuiltinAliasNames[i];
        }
    }

    for (i = 0; i < dwTotalNumEntries; i++)
    {
        pSourceBuffer = ppwszLocalGroupNames[i];

        dwSize = 0;
        err = NetAllocateLocalGroupUsersInfo(NULL,
                                             NULL,
                                             dwLevel,
                                             pSourceBuffer,
                                             &dwSize,
                                             eValidation);
        BAIL_ON_WIN_ERROR(err);

        dwTotalSize += dwSize;
        dwNumEntries++;

        if (dwTotalSize > dwMaxBufferSize)
        {
            dwTotalSize -= dwSize;
            dwNumEntries--;
            break;
        }
    }

    if (dwTotalNumEntries > 0 && dwNumEntries == 0)
    {
        err = ERROR_INSUFFICIENT_BUFFER;
        BAIL_ON_WIN_ERROR(err);
    }

    if (dwTotalSize)
    {
        status = NetAllocateMemory(OUT_PPVOID(&pBuffer),
                                   dwTotalSize);
        BAIL_ON_NT_STATUS(status);
    }

    dwSize           = 0;
    pBufferCursor    = pBuffer;
    dwSpaceAvailable = dwTotalSize;

    for (i = 0; i < dwNumEntries; i++)
    {
        pSourceBuffer = ppwszLocalGroupNames[i];
        pBufferCursor = pBuffer + (i * dwInfoLevelSize);

        err = NetAllocateLocalGroupUsersInfo(pBufferCursor,
                                             &dwSpaceAvailable,
                                             dwLevel,
                                             pSourceBuffer,
                                             &dwSize,
                                             eValidation);
        BAIL_ON_WIN_ERROR(err);
    }

    if (dwNumEntries < dwTotalNumEntries)
    {
        err = ERROR_MORE_DATA;
    }

    status = SamrClose(hSamrBinding, hUser);
    BAIL_ON_NT_STATUS(status);

    *ppBuffer        = pBuffer;
    *pdwNumEntries   = dwNumEntries;
    *pdwTotalEntries = dwTotalNumEntries;

cleanup:
    LW_SAFE_FREE_MEMORY(pUserSid);
    LW_SAFE_FREE_MEMORY(ppwszLocalGroupNames);

    if (pdwUserRids)
    {
        SamrFreeMemory(pdwUserRids);
    }

    if (pdwBuiltinUserRids)
    {
        SamrFreeMemory(pdwBuiltinUserRids);
    }

    if (ppwszAliasNames)
    {
        SamrFreeMemory(ppwszAliasNames);
    }

    if (pdwAliasTypes)
    {
        SamrFreeMemory(pdwAliasTypes);
    }

    if (ppwszBuiltinAliasNames)
    {
        SamrFreeMemory(ppwszBuiltinAliasNames);
    }

    if (pdwBuiltinAliasTypes)
    {
        SamrFreeMemory(pdwBuiltinAliasTypes);
    }

    if (pCreds)
    {
        LwIoDeleteCreds(pCreds);
    }

    return err;

error:
    if (pBuffer)
    {
        NetFreeMemory(pBuffer);
    }

    *ppBuffer        = NULL;
    *pdwNumEntries   = 0;
    *pdwTotalEntries = 0;

    goto cleanup;
}
Esempio n. 9
0
VOID
NlChangeLogWorker(
    IN LPVOID ChangeLogWorkerParam
    )
/*++

Routine Description:

    This thread performs the special operations that are required to
    replicate the special local groups such as Administrator, Server
    Operartors, etc., in the NT BUILTIN database to the
    down level systems.

    This thread comes up first time during system bootup and initializes
    required global data.  If this NT (PDC) System is replicating to any
    down level system then it stays back, otherwise it terminates.  Also
    when a down level system is added to the domain, this thread is
    created if it is not running on the system before.

Arguments:

    None.

Return Value:

    Return when there is no down level system on the domain.

--*/
{
    NTSTATUS Status;

#if DBG
    DWORD Count;
#endif


    NlPrint((NL_CHANGELOG, "ChangeLogWorker Thread is starting \n"));

    //
    // check if have initialize the global data before
    //

    if ( !NlGlobalChangeLogWorkInit ) {

        PLSAPR_POLICY_INFORMATION PolicyAccountDomainInfo = NULL;
        DWORD DomainSidLength;

        //
        // wait for SAM service to start.
        //

        if( !NlWaitForSamService(FALSE) ) {

            NlPrint((NL_CRITICAL, "Sam server failed start."));
            goto Cleanup;
        }

        //
        // Open Sam Server
        //

        Status = SamIConnect( NULL,     // No server name
                              &NlGlobalChWorkerSamServerHandle,
                              0,        // Ignore desired access
                              (BOOLEAN) TRUE );
                                        // Indicate we are privileged

        if ( !NT_SUCCESS(Status) ) {

            NlPrint((NL_CRITICAL,
                "Failed to connect to SAM server %lx\n", Status ));

            NlGlobalChWorkerSamServerHandle = NULL;
            goto Cleanup;
        }

        //
        // Open Policy Domain
        //

        Status = LsaIOpenPolicyTrusted( &NlGlobalChWorkerPolicyHandle );

        if ( !NT_SUCCESS(Status) ) {

            NlPrint((NL_CRITICAL,
                "Failed to Open LSA database %lx\n", Status ));

            NlGlobalChWorkerPolicyHandle = NULL;
            goto Cleanup;
        }

        //
        // Open BuiltIn Domain database
        //
        // Note, build in domain SID is made during dll init time.
        //


        Status = SamrOpenDomain( NlGlobalChWorkerSamServerHandle,
                                 DOMAIN_ALL_ACCESS,
                                 NlGlobalChWorkerBuiltinDomainSid,
                                 &NlGlobalChWorkerBuiltinDBHandle );

        if ( !NT_SUCCESS(Status) ) {

            NlPrint((NL_CRITICAL,
                "Failed to Open BUILTIN database %lx\n", Status ));
            NlGlobalChWorkerBuiltinDBHandle = NULL;
            goto Cleanup;
        }

        //
        // Query account domain SID.
        //

        Status = LsarQueryInformationPolicy(
                    NlGlobalChWorkerPolicyHandle,
                    PolicyAccountDomainInformation,
                    &PolicyAccountDomainInfo );

        if ( !NT_SUCCESS(Status) ) {

            NlPrint((NL_CRITICAL,
                "Failed to Query Account domain Sid from LSA %lx\n",
                Status ));

            goto Cleanup;
        }

        if ( PolicyAccountDomainInfo->PolicyAccountDomainInfo.DomainSid == NULL ) {

            LsaIFree_LSAPR_POLICY_INFORMATION(
                PolicyAccountDomainInformation,
                PolicyAccountDomainInfo );

            NlPrint((NL_CRITICAL, "Account domain info from LSA invalid.\n"));
            goto Cleanup;
        }

        //
        // copy domain SID to global data.
        //

        DomainSidLength = RtlLengthSid( PolicyAccountDomainInfo->
                            PolicyAccountDomainInfo.DomainSid );

        NlGlobalChWorkerSamDomainSid = (PSID)NetpMemoryAllocate( DomainSidLength );

        if( NlGlobalChWorkerSamDomainSid == NULL ) {

            Status = STATUS_NO_MEMORY;

            NlPrint((NL_CRITICAL,
                "NlChangeLogWorker is out of memory.\n"));

            goto Cleanup;
        }

        Status = RtlCopySid(
                    DomainSidLength,
                    NlGlobalChWorkerSamDomainSid,
                    PolicyAccountDomainInfo->
                        PolicyAccountDomainInfo.DomainSid );

        if ( !NT_SUCCESS(Status) ) {

            NlPrint((NL_CRITICAL,
                "Failed to copy SAM Domain sid %lx\n", Status ));
            goto Cleanup;
        }

        //
        // Free up Account domain info, we don't need any more.
        //

        LsaIFree_LSAPR_POLICY_INFORMATION(
            PolicyAccountDomainInformation,
            PolicyAccountDomainInfo );

        //
        // Open Account domain
        //

        Status = SamrOpenDomain( NlGlobalChWorkerSamServerHandle,
                                 DOMAIN_ALL_ACCESS,
                                 NlGlobalChWorkerSamDomainSid,
                                 &NlGlobalChWorkerSamDBHandle );

        if ( !NT_SUCCESS(Status) ) {

            NlPrint((NL_CRITICAL,
                "Failed to Open SAM database %lx\n", Status ));
            NlGlobalChWorkerSamDBHandle = NULL;
            goto Cleanup;
        }

        //
        // Initialization done. Never do it again.
        //

        NlGlobalChangeLogWorkInit = TRUE;

    }

    //
    // If SERVERS global group is empty then it implies that we don't
    // have any down level system on this domain. so we can stop this
    // thread.
    //

    if ( NlIsServersGroupEmpty( 0 ) ) {

        NlPrint((NL_CHANGELOG, "Servers Group is empty \n "));

        goto Cleanup;
    }

    //
    // Initialize NlGlobalSpecialServerGroupList.
    //

    Status = NlInitSpecialGroupList();

    if ( !NT_SUCCESS(Status) ) {

        NlPrint((NL_CRITICAL,
            "Failed to initialize Special group list %lx\n", Status ));
        goto Cleanup;
    }

    //
    // process worker queue forever, terminate when we are asked to do
    // so or when the SERVERS group goes empty.
    //

    for( ;; ) {

        DWORD WaitStatus;

        //
        // wait on the queue to become non-empty
        //

        WaitStatus = WaitForSingleObject(
                        NlGlobalChangeLogWorkerQueueEvent,
                        (DWORD)(-1) );

        if ( WaitStatus != 0 ) {

            NlPrint((NL_CRITICAL,
                    "Change log worker failed, "
                    "WaitForSingleObject error: %ld\n",
                    WaitStatus));
            break;
        }

        //
        // empty worker queue.
        //

#if DBG
        Count = 0;
#endif
        for (;;) {

            PLIST_ENTRY ListEntry;
            PWORKER_QUEUE_ENTRY WorkerQueueEntry;

            //
            // if we are asked to leave, do so.
            //

            if( NlGlobalChangeLogWorkerTerminate ) {

                NlPrint((NL_CHANGELOG,
                    "ChangeLogWorker is asked to leave \n"));

                goto Cleanup;
            }

            LOCK_CHANGELOG();

            if( IsListEmpty( &NlGlobalChangeLogWorkerQueue ) ) {

                UNLOCK_CHANGELOG();
                break;
            }

            ListEntry = RemoveHeadList( &NlGlobalChangeLogWorkerQueue );

            UNLOCK_CHANGELOG();

            WorkerQueueEntry = CONTAINING_RECORD( ListEntry,
                                                  WORKER_QUEUE_ENTRY,
                                                  Next );

            //
            // process an queue entry.
            //

            if( !NlProcessQueueEntry( WorkerQueueEntry ) ) {

                NlPrint((NL_CHANGELOG, "Servers group becomes empty \n"));

                NetpMemoryFree( WorkerQueueEntry );
                goto Cleanup;
            }

            //
            // Free this entry.
            //

            NetpMemoryFree( WorkerQueueEntry );
#if DBG
            Count++;
#endif
        }

        NlPrint((NL_CHANGELOG,
            "Changelog worker processed %lu entries.\n", Count) );
    }

Cleanup:

    //
    // empty worker queue and group list
    //

    LOCK_CHANGELOG();

#if DBG
    Count = 0;
#endif
    while ( !IsListEmpty( &NlGlobalChangeLogWorkerQueue ) ) {
        PLIST_ENTRY ListEntry;
        PWORKER_QUEUE_ENTRY WorkerQueueEntry;

        ListEntry = RemoveHeadList( &NlGlobalChangeLogWorkerQueue );

        WorkerQueueEntry = CONTAINING_RECORD( ListEntry,
                                              WORKER_QUEUE_ENTRY,
                                              Next );
        NetpMemoryFree( WorkerQueueEntry );
#if DBG
        Count++;
#endif
    }

#if DBG
    if ( Count != 0 ) {
        NlPrint((NL_CHANGELOG,
            "Changelog worker did not process %lu entries.\n", Count) );
    }
#endif

    while ( !IsListEmpty( &NlGlobalSpecialServerGroupList ) ) {
        PLIST_ENTRY ListEntry;
        PGLOBAL_GROUP_ENTRY ServerEntry;

        ListEntry = RemoveHeadList( &NlGlobalSpecialServerGroupList );

        ServerEntry = CONTAINING_RECORD( ListEntry,
                                         GLOBAL_GROUP_ENTRY,
                                         Next );
        NetpMemoryFree( ServerEntry );
    }

    UNLOCK_CHANGELOG();

    NlPrint((NL_CHANGELOG, "ChangeLogWorker Thread is exiting \n"));

    return;
    UNREFERENCED_PARAMETER( ChangeLogWorkerParam );
}
Esempio n. 10
0
/*
 * @unimplemented
 */
PSID
WINAPI
GetSiteSidFromToken(IN HANDLE TokenHandle)
{
    PTOKEN_GROUPS RestrictedSids;
    ULONG RetLen;
    UINT i;
    NTSTATUS Status;
    PSID PSiteSid = NULL;
    SID_IDENTIFIER_AUTHORITY InternetSiteAuthority = {SECURITY_INTERNETSITE_AUTHORITY};

    Status = NtQueryInformationToken(TokenHandle,
                                     TokenRestrictedSids,
                                     NULL,
                                     0,
                                     &RetLen);
    if (Status != STATUS_BUFFER_TOO_SMALL)
    {
        SetLastError(RtlNtStatusToDosError(Status));
        return NULL;
    }

    RestrictedSids = (PTOKEN_GROUPS)RtlAllocateHeap(RtlGetProcessHeap(),
                                                    0,
                                                    RetLen);
    if (RestrictedSids == NULL)
    {
        SetLastError(ERROR_OUTOFMEMORY);
        return NULL;
    }

    Status = NtQueryInformationToken(TokenHandle,
                                     TokenRestrictedSids,
                                     RestrictedSids,
                                     RetLen,
                                     &RetLen);
    if (NT_SUCCESS(Status))
    {
        for (i = 0; i < RestrictedSids->GroupCount; i++)
        {
            SID* RSSid = RestrictedSids->Groups[i].Sid;

            if (RtlCompareMemory(&(RSSid->IdentifierAuthority),
                                 &InternetSiteAuthority,
                                 sizeof(SID_IDENTIFIER_AUTHORITY)) ==
                                 sizeof(SID_IDENTIFIER_AUTHORITY))
            {
                PSiteSid = RtlAllocateHeap(RtlGetProcessHeap(),
                                           0,
                                           RtlLengthSid((RestrictedSids->
                                                         Groups[i]).Sid));
                if (PSiteSid == NULL)
                {
                    SetLastError(ERROR_OUTOFMEMORY);
                }
                else
                {
                    RtlCopySid(RtlLengthSid(RestrictedSids->Groups[i].Sid),
                               PSiteSid,
                               RestrictedSids->Groups[i].Sid);
                }

                break;
            }
        }
    }
    else
    {
        SetLastError(RtlNtStatusToDosError(Status));
    }

    RtlFreeHeap(RtlGetProcessHeap(), 0, RestrictedSids);
    return PSiteSid;
}
Esempio n. 11
0
NTSTATUS NTAPI
LsaApLogonUserEx (PLSA_CLIENT_REQUEST request, SECURITY_LOGON_TYPE logon_type,
		  PVOID auth, PVOID client_auth_base, ULONG auth_len,
		  PVOID *pbuf, PULONG pbuf_len, PLUID logon_id,
		  PNTSTATUS sub_stat, PLSA_TOKEN_INFORMATION_TYPE tok_type,
		  PVOID *tok, PUNICODE_STRING *account,
		  PUNICODE_STRING *authority, PUNICODE_STRING *machine)
{
  DWORD checksum, i;
  PDWORD csp, csp_end;
  NTSTATUS stat;
  SECPKG_CLIENT_INFO clinf;
  PLSA_TOKEN_INFORMATION_V2 tokinf;

  cyglsa_t *authinf = (cyglsa_t *) auth;

  /* Check if the caller has the SeTcbPrivilege, otherwise refuse service. */
  stat = funcs->GetClientInfo (&clinf);
  if (stat != STATUS_SUCCESS)
    {
      cyglsa_printf ("GetClientInfo failed: 0x%08lx\n", stat);
      return stat;
    }
  if (!clinf.HasTcbPrivilege)
    {
      cyglsa_printf ("Client has no TCB privilege.  Access denied.\n");
      return STATUS_ACCESS_DENIED;
    }

  /* Make a couple of validity checks. */
  if (auth_len < sizeof *authinf
      || authinf->magic != CYG_LSA_MAGIC
      || !authinf->username[0]
      || !authinf->domain[0])
    {
      cyglsa_printf ("Invalid authentication parameter.\n");
      return STATUS_INVALID_PARAMETER;
    }
  checksum = CYG_LSA_MAGIC;
  csp = (PDWORD) &authinf->username;
  csp_end = (PDWORD) ((PBYTE) authinf + auth_len);
  while (csp < csp_end)
    checksum += *csp++;
  if (authinf->checksum != checksum)
    {
      cyglsa_printf ("Invalid checksum.\n");
      return STATUS_INVALID_PARAMETER_3;
    }

  /* Set account to username and authority to domain resp. machine name.
     The name of the logon account name as returned by LookupAccountSid
     is created from here as "authority\account". */
  authinf->username[UNLEN] = '\0';
  authinf->domain[MAX_DOMAIN_NAME_LEN] = '\0';
  if (account && !(*account = uni_alloc (authinf->username,
  					 wcslen (authinf->username))))
    {
      cyglsa_printf ("No memory trying to create account.\n");
      return STATUS_NO_MEMORY;
    }
  if (authority && !(*authority = uni_alloc (authinf->domain,
					     wcslen (authinf->domain))))
    {
      cyglsa_printf ("No memory trying to create authority.\n");
      return STATUS_NO_MEMORY;
    }
  if (machine)
    {
      WCHAR mach[MAX_COMPUTERNAME_LENGTH + 1];
      DWORD msize = MAX_COMPUTERNAME_LENGTH + 1;
      if (!GetComputerNameW (mach, &msize))
        wcscpy (mach, L"UNKNOWN");
      if (!(*machine = uni_alloc (mach, wcslen (mach))))
	{
	  cyglsa_printf ("No memory trying to create machine.\n");
	  return STATUS_NO_MEMORY;
	}
    }
  /* Create a fake buffer in pbuf which is free'd again in the client.
     Windows 2000 tends to crash when setting this pointer to NULL. */
  if (pbuf)
    {
#ifdef JUST_ANOTHER_NONWORKING_SOLUTION
      cygprf_t prf;
      WCHAR sam_username[MAX_DOMAIN_NAME_LEN + UNLEN + 2];
      SECURITY_STRING sam_user, prefix;
      PUCHAR user_auth;
      ULONG user_auth_size;
      WCHAR flatname[UNLEN + 1];
      UNICODE_STRING flatnm;
      TOKEN_SOURCE ts;
      HANDLE token;
#endif /* JUST_ANOTHER_NONWORKING_SOLUTION */

      stat = funcs->AllocateClientBuffer (request, 64UL, pbuf);
      if (!LSA_SUCCESS (stat))
	{
	  cyglsa_printf ("AllocateClientBuffer failed: 0x%08lx\n", stat);
	  return stat;
	}
#ifdef JUST_ANOTHER_NONWORKING_SOLUTION
      prf.magic_pre = MAGIC_PRE;
      prf.token = NULL;
      prf.magic_post = MAGIC_POST;

#if 0
      /* That's how it was supposed to work according to MSDN... */
      wcscpy (sam_username, authinf->domain);
      wcscat (sam_username, L"\\");
      wcscat (sam_username, authinf->username);
#else
      /* That's the only solution which worked, and then it only worked
         for machine local accounts.  No domain authentication possible.
	 STATUS_NO_SUCH_USER galore! */
      wcscpy (sam_username, authinf->username);
#endif
      RtlInitUnicodeString (&sam_user, sam_username);
      RtlInitUnicodeString (&prefix, L"");
      RtlInitEmptyUnicodeString (&flatnm, flatname,
				 (UNLEN + 1) * sizeof (WCHAR));

      stat = funcs->GetAuthDataForUser (&sam_user, SecNameSamCompatible,
					NULL, &user_auth,
					&user_auth_size, &flatnm);
      if (!NT_SUCCESS (stat))
	{
	  char sam_u[MAX_DOMAIN_NAME_LEN + UNLEN + 2];
	  wcstombs (sam_u, sam_user.Buffer, sizeof (sam_u));
	  cyglsa_printf ("GetAuthDataForUser (%u,%u,%s) failed: 0x%08lx\n",
		  sam_user.Length, sam_user.MaximumLength, sam_u, stat);
	  return stat;
	}

      memcpy (ts.SourceName, "Cygwin.1", 8);
      ts.SourceIdentifier.HighPart = 0;
      ts.SourceIdentifier.LowPart = 0x0104;
      RtlInitEmptyUnicodeString (&flatnm, flatname,
				 (UNLEN + 1) * sizeof (WCHAR));
      stat = funcs->ConvertAuthDataToToken (user_auth, user_auth_size,
					    SecurityDelegation, &ts,
					    Interactive, *authority,
					    &token, logon_id, &flatnm,
					    sub_stat);
      if (!NT_SUCCESS (stat))
	{
	  cyglsa_printf ("ConvertAuthDataToToken failed: 0x%08lx\n", stat);
	  return stat;
	}

      stat = funcs->DuplicateHandle (token, &prf.token);
      if (!NT_SUCCESS (stat))
	{
	  cyglsa_printf ("DuplicateHandle failed: 0x%08lx\n", stat);
	  return stat;
	}
      
      stat = funcs->CopyToClientBuffer (request, sizeof prf, *pbuf, &prf);
      if (!NT_SUCCESS (stat))
	{
	  cyglsa_printf ("CopyToClientBuffer failed: 0x%08lx\n", stat);
	  return stat;
	}
      funcs->FreeLsaHeap (user_auth);
#endif /* JUST_ANOTHER_NONWORKING_SOLUTION */
    }
  if (pbuf_len)
    *pbuf_len = 64UL;

  /* A PLSA_TOKEN_INFORMATION_V2 is allocated in one piece, so... */
#if defined (__x86_64__) || defined (_M_AMD64)
    {
      /* ...on 64 bit systems we have to convert the incoming 32 bit offsets
	 into 64 bit pointers.  That requires to re-evaluate the size of the
	 outgoing tokinf structure and a somewhat awkward procedure to copy
	 the information over. */
      LONG_PTR base;
      PBYTE tptr;
      DWORD size, newsize;
      PSID src_sid;
      PCYG_TOKEN_GROUPS src_grps;
      PTOKEN_GROUPS grps;
      PTOKEN_PRIVILEGES src_privs;
      PACL src_acl;

      base = (LONG_PTR) &authinf->inf;

      newsize = authinf->inf_size;
      newsize += sizeof (TOKEN_USER) - sizeof (CYG_TOKEN_USER); /* User SID */
      newsize += sizeof (PTOKEN_GROUPS) - sizeof (OFFSET); /* Groups */
      src_grps = (PCYG_TOKEN_GROUPS) (base + authinf->inf.Groups);
      newsize += src_grps->GroupCount		  /* Group SIDs */
      		 * (sizeof (SID_AND_ATTRIBUTES)
		    - sizeof (CYG_SID_AND_ATTRIBUTES));
      newsize += sizeof (PSID) - sizeof (OFFSET); /* Primary Group SID */
      newsize += sizeof (PTOKEN_PRIVILEGES) - sizeof (OFFSET); /* Privileges */
      newsize += 0; /* Owner SID */
      newsize += sizeof (PACL) - sizeof (OFFSET); /* Default DACL */

      if (!(tokinf = funcs->AllocateLsaHeap (newsize)))
	return STATUS_NO_MEMORY;
      tptr = (PBYTE)(tokinf + 1);

      tokinf->ExpirationTime = authinf->inf.ExpirationTime;
      /* User SID */
      src_sid = (PSID) (base + authinf->inf.User.User.Sid);
      size = RtlLengthSid (src_sid);
      RtlCopySid (size, (PSID) tptr, src_sid);
      tokinf->User.User.Sid = (PSID) tptr;
      tptr += size;
      tokinf->User.User.Attributes = authinf->inf.User.User.Attributes;
      /* Groups */
      grps = (PTOKEN_GROUPS) tptr;
      tokinf->Groups = grps;
      grps->GroupCount = src_grps->GroupCount;
      tptr += sizeof grps->GroupCount
	      + grps->GroupCount * sizeof (SID_AND_ATTRIBUTES);
      /* Group SIDs */
      for (i = 0; i < src_grps->GroupCount; ++i)
	{
	  src_sid = (PSID) (base + src_grps->Groups[i].Sid);
	  size = RtlLengthSid (src_sid);
	  RtlCopySid (size, (PSID) tptr, src_sid);
	  tokinf->Groups->Groups[i].Sid = (PSID) tptr;
	  tptr += size;
	  tokinf->Groups->Groups[i].Attributes = src_grps->Groups[i].Attributes;
	}
      /* Primary Group SID */
      src_sid = (PSID) (base + authinf->inf.PrimaryGroup.PrimaryGroup);
      size = RtlLengthSid (src_sid);
      RtlCopySid (size, (PSID) tptr, src_sid);
      tokinf->PrimaryGroup.PrimaryGroup = (PSID) tptr;
      tptr += size;
      /* Privileges */
      src_privs = (PTOKEN_PRIVILEGES) (base + authinf->inf.Privileges);
      size = sizeof src_privs->PrivilegeCount
	     + src_privs->PrivilegeCount * sizeof (LUID_AND_ATTRIBUTES);
      memcpy (tptr, src_privs, size);
      tokinf->Privileges = (PTOKEN_PRIVILEGES) tptr;
      tptr += size;
      /* Owner */
      tokinf->Owner.Owner = NULL;
      /* Default DACL */
      src_acl = (PACL) (base + authinf->inf.DefaultDacl.DefaultDacl);
      size = src_acl->AclSize;
      memcpy (tptr, src_acl, size);
      tokinf->DefaultDacl.DefaultDacl = (PACL) tptr;
    }
#else
    {
      /* ...on 32 bit systems we just allocate tokinf with the same size as
         we get, copy the whole structure and convert offsets into pointers. */

      /* Allocate LUID for usage in the logon SID on Windows 2000.  This is
	 not done in the 64 bit code above for hopefully obvious reasons... */
      LUID logon_sid_id;

      if (must_create_logon_sid
	  && !NT_SUCCESS (NtAllocateLocallyUniqueId (&logon_sid_id)))
	return STATUS_INSUFFICIENT_RESOURCES;

      if (!(tokinf = funcs->AllocateLsaHeap (authinf->inf_size)))
	return STATUS_NO_MEMORY;
      memcpy (tokinf, &authinf->inf, authinf->inf_size);

      /* User SID */
      tokinf->User.User.Sid = (PSID)
	      ((PBYTE) tokinf + (LONG_PTR) tokinf->User.User.Sid);
      /* Groups */
      tokinf->Groups = (PTOKEN_GROUPS)
	      ((PBYTE) tokinf + (LONG_PTR) tokinf->Groups);
      /* Group SIDs */
      for (i = 0; i < tokinf->Groups->GroupCount; ++i)
	{
	  tokinf->Groups->Groups[i].Sid = (PSID)
		((PBYTE) tokinf + (LONG_PTR) tokinf->Groups->Groups[i].Sid);
	  if (must_create_logon_sid
	      && tokinf->Groups->Groups[i].Attributes & SE_GROUP_LOGON_ID
	      && *RtlSubAuthorityCountSid (tokinf->Groups->Groups[i].Sid) == 3
	      && *RtlSubAuthoritySid (tokinf->Groups->Groups[i].Sid, 0)
		 == SECURITY_LOGON_IDS_RID)
	    {
	      *RtlSubAuthoritySid (tokinf->Groups->Groups[i].Sid, 1)
	      = logon_sid_id.HighPart;
	      *RtlSubAuthoritySid (tokinf->Groups->Groups[i].Sid, 2)
	      = logon_sid_id.LowPart;
	    }
	}

      /* Primary Group SID */
      tokinf->PrimaryGroup.PrimaryGroup = (PSID)
	      ((PBYTE) tokinf + (LONG_PTR) tokinf->PrimaryGroup.PrimaryGroup);
      /* Privileges */
      tokinf->Privileges = (PTOKEN_PRIVILEGES)
	      ((PBYTE) tokinf + (LONG_PTR) tokinf->Privileges);
      /* Owner SID */
      tokinf->Owner.Owner = NULL;
      /* Default DACL */
      tokinf->DefaultDacl.DefaultDacl = (PACL)
	      ((PBYTE) tokinf + (LONG_PTR) tokinf->DefaultDacl.DefaultDacl);

    }
#endif

  *tok = (PVOID) tokinf;
  *tok_type = LsaTokenInformationV2;

  print_tokinf (tokinf, authinf->inf_size, authinf, &authinf->inf,
		(PVOID)((LONG_PTR) &authinf->inf + authinf->inf_size));

  /* Create logon session. */
  stat = NtAllocateLocallyUniqueId (logon_id);
  if (!NT_SUCCESS (stat))
    {
      funcs->FreeLsaHeap (*tok);
      *tok = NULL;
      cyglsa_printf ("NtAllocateLocallyUniqueId status 0x%08lx\n", stat);
      return STATUS_INSUFFICIENT_RESOURCES;
    }
  stat = funcs->CreateLogonSession (logon_id);
  if (stat != STATUS_SUCCESS)
    {
      funcs->FreeLsaHeap (*tok);
      *tok = NULL;
      cyglsa_printf ("CreateLogonSession failed: 0x%08lx\n", stat);
      return stat;
    }

  cyglsa_printf ("BINGO!!!\n", stat);
  return STATUS_SUCCESS;
}
Esempio n. 12
0
NTSTATUS
NTAPI
RtlpAddKnownAce(IN PACL Acl,
                IN ULONG Revision,
                IN ULONG Flags,
                IN ACCESS_MASK AccessMask,
                IN PSID Sid,
                IN UCHAR Type)
{
    PKNOWN_ACE Ace;
    ULONG AceSize, InvalidFlags;
    PAGED_CODE_RTL();

    /* Check the validity of the SID */
    if (!RtlValidSid(Sid)) return STATUS_INVALID_SID;

    /* Check the validity of the revision */
    if ((Acl->AclRevision > ACL_REVISION4) || (Revision > ACL_REVISION4))
    {
        return STATUS_REVISION_MISMATCH;
    }

    /* Pick the smallest of the revisions */
    if (Revision < Acl->AclRevision) Revision = Acl->AclRevision;

    /* Validate the flags */
    if (Type == SYSTEM_AUDIT_ACE_TYPE)
    {
        InvalidFlags = Flags & ~(VALID_INHERIT_FLAGS |
                                 SUCCESSFUL_ACCESS_ACE_FLAG |
                                 FAILED_ACCESS_ACE_FLAG);
    }
    else
    {
        InvalidFlags = Flags & ~VALID_INHERIT_FLAGS;
    }

    /* If flags are invalid, bail out */
    if (InvalidFlags != 0) return STATUS_INVALID_PARAMETER;

    /* If ACL is invalid, bail out */
    if (!RtlValidAcl(Acl)) return STATUS_INVALID_ACL;

    /* If there's no free ACE, bail out */
    if (!RtlFirstFreeAce(Acl, (PACE*)&Ace)) return STATUS_INVALID_ACL;

    /* Calculate the size of the ACE and bail out if it's too small */
    AceSize = RtlLengthSid(Sid) + sizeof(ACE);
    if (!(Ace) || ((ULONG_PTR)Ace + AceSize > (ULONG_PTR)Acl + Acl->AclSize))
    {
        return STATUS_ALLOTTED_SPACE_EXCEEDED;
    }

    /* Initialize the header and common fields */
    Ace->Header.AceFlags = (BYTE)Flags;
    Ace->Header.AceType = Type;
    Ace->Header.AceSize = (WORD)AceSize;
    Ace->Mask = AccessMask;

    /* Copy the SID */
    RtlCopySid(RtlLengthSid(Sid), &Ace->SidStart, Sid);

    /* Fill out the ACL header and return */
    Acl->AceCount++;
    Acl->AclRevision = (BYTE)Revision;
    return STATUS_SUCCESS;
}
Esempio n. 13
0
/******************************************************************************
 * CopySid [ADVAPI32.@]
 *
 * PARAMS
 *   nDestinationSidLength []
 *   pDestinationSid       []
 *   pSourceSid            []
 */
BOOL WINAPI
CopySid( DWORD nDestinationSidLength, PSID pDestinationSid, PSID pSourceSid )
{
    return RtlCopySid(nDestinationSidLength, pDestinationSid, pSourceSid);
}
Esempio n. 14
0
    BAIL_ON_LSA_ERROR(dwError);

    dwError = LwAllocateWellKnownSid(WinBuiltinAdministratorsSid,
                                   NULL,
                                   &pBuiltinAdminsSid,
                                   NULL);
    BAIL_ON_LSA_ERROR(dwError);

    dwAccountSidSize = RtlLengthRequiredSid(
                                   pDomainSid->SubAuthorityCount + 1);
    dwError = LwAllocateMemory(dwAccountSidSize,
                               OUT_PPVOID(&pAccountSid));
    BAIL_ON_LSA_ERROR(dwError);

    ntStatus = RtlCopySid(dwAccountSidSize,
                          pAccountSid,
                          pDomainSid);
    BAIL_ON_NT_STATUS(ntStatus);

    ntStatus = RtlAppendRidSid(dwAccountSidSize,
                               pAccountSid,
                               dwRid);
    BAIL_ON_NT_STATUS(ntStatus);

    dwError = LwAllocateWellKnownSid(WinWorldSid,
                                   NULL,
                                   &pWorldSid,
                                   NULL);
    BAIL_ON_LSA_ERROR(dwError);

    dwError = LocalDirCreateDacl(&pDacl,
Esempio n. 15
0
SECURITY_STATUS SEC_ENTRY
GetSecurityUserInfo(
    IN PLUID pLogonId,
    IN ULONG fFlags,
    OUT PSecurityUserData * ppUserInfo)
{
    NTSTATUS Status, FinalStatus;
    PVOID GetInfoBuffer = NULL;
    PVOID GetInfoResponseBuffer = NULL;
    PMSV1_0_GETUSERINFO_REQUEST GetInfoRequest;
    PMSV1_0_GETUSERINFO_RESPONSE GetInfoResponse;
    ULONG ResponseSize;
    ULONG RegionSize = sizeof(MSV1_0_GETUSERINFO_REQUEST);
    PSecurityUserData UserInfo = NULL;
    ULONG UserInfoSize;
    PUCHAR Where;
    SECURITY_STATUS scRet;
    PClient Client = NULL;


    scRet = IsOkayToExec(&Client);
    if (!NT_SUCCESS(scRet))
    {
        return(scRet);
    }

    //
    //  Allocate virtual memory for the response buffer.
    //

    Status = ZwAllocateVirtualMemory(
                NtCurrentProcess(),
                &GetInfoBuffer, 0L,
                &RegionSize,
                MEM_COMMIT,
                PAGE_READWRITE
                );

    GetInfoRequest = GetInfoBuffer;

    if (!NT_SUCCESS(Status)) {
        scRet = Status;
        goto Cleanup;
    }

    GetInfoRequest->MessageType = MsV1_0GetUserInfo;

    RtlCopyLuid(&GetInfoRequest->LogonId, pLogonId);

    Status = LsaCallAuthenticationPackage(
                Client->hPort,
                PackageId,
                GetInfoRequest,
                RegionSize,
                &GetInfoResponseBuffer,
                &ResponseSize,
                &FinalStatus);

    GetInfoResponse = GetInfoResponseBuffer;

    if (!NT_SUCCESS(Status)) {
        GetInfoResponseBuffer = NULL;
        scRet = Status;
        goto Cleanup;
    }


    if (!NT_SUCCESS(FinalStatus)) {
        scRet = FinalStatus;
        goto Cleanup;
    }

    ASSERT(GetInfoResponse->MessageType == MsV1_0GetUserInfo);

    //
    // Build a SecurityUserData
    //

    UserInfoSize = sizeof(SecurityUserData) +
                   GetInfoResponse->UserName.MaximumLength +
                   GetInfoResponse->LogonDomainName.MaximumLength +
                   GetInfoResponse->LogonServer.MaximumLength +
                   RtlLengthSid(GetInfoResponse->UserSid);



    scRet = ZwAllocateVirtualMemory(
                NtCurrentProcess(),
                &UserInfo,
                0L,
                &UserInfoSize,
                MEM_COMMIT,
                PAGE_READWRITE
                );
    if (!NT_SUCCESS(scRet))
    {
        goto Cleanup;
    }

    //
    // Pack in the SID first, to respectalignment boundaries.
    //

    Where = (PUCHAR) (UserInfo + 1);
    UserInfo->pSid = (PSID) (Where);
    RtlCopySid(
        UserInfoSize,
        Where,
        GetInfoResponse->UserSid
        );
    Where += RtlLengthSid(Where);

    //
    // Pack in the strings
    //

    PutString(
        (PSTRING) &UserInfo->UserName,
        (PSTRING) &GetInfoResponse->UserName,
        0,
        &Where
        );

    PutString(
        (PSTRING) &UserInfo->LogonDomainName,
        (PSTRING) &GetInfoResponse->LogonDomainName,
        0,
        &Where
        );

    PutString(
        (PSTRING) &UserInfo->LogonServer,
        (PSTRING) &GetInfoResponse->LogonServer,
        0,
        &Where
        );

    *ppUserInfo = UserInfo;
    UserInfo = NULL;
    scRet = STATUS_SUCCESS;

Cleanup:
    if (GetInfoRequest != NULL)
    {
        ZwFreeVirtualMemory(
            NtCurrentProcess(),
            &GetInfoRequest,
            &RegionSize,
            MEM_RELEASE
            );

    }

    if (UserInfo != NULL)
    {
        FreeContextBuffer(UserInfo);
    }

    if (GetInfoResponseBuffer != NULL)
    {
        LsaFreeReturnBuffer(GetInfoResponseBuffer);
    }

    return(scRet);
}
Esempio n. 16
0
BOOLEAN
TSeVariableInitialization()
/*++

Routine Description:

    This function initializes the global variables used in security
    tests.

Arguments:

    None.

Return Value:

    TRUE if variables successfully initialized.
    FALSE if not successfully initialized.

--*/
{
    ULONG SidWithZeroSubAuthorities;
    ULONG SidWithOneSubAuthority;
    ULONG SidWithThreeSubAuthorities;
    ULONG SidWithFourSubAuthorities;

    SID_IDENTIFIER_AUTHORITY NullSidAuthority    = SECURITY_NULL_SID_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY WorldSidAuthority   = SECURITY_WORLD_SID_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY LocalSidAuthority   = SECURITY_LOCAL_SID_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY CreatorSidAuthority = SECURITY_CREATOR_SID_AUTHORITY;

    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;


    SID_IDENTIFIER_AUTHORITY BedrockAuthority = BEDROCK_AUTHORITY;

    SID_IDENTIFIER_AUTHORITY BedrockAAuthority = BEDROCKA_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY BedrockBAuthority = BEDROCKB_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY BedrockCAuthority = BEDROCKC_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY BedrockDAuthority = BEDROCKD_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY BedrockEAuthority = BEDROCKE_AUTHORITY;

    //
    //  The following SID sizes need to be allocated
    //

    SidWithZeroSubAuthorities  = RtlLengthRequiredSid( 0 );
    SidWithOneSubAuthority     = RtlLengthRequiredSid( 1 );
    SidWithThreeSubAuthorities = RtlLengthRequiredSid( 3 );
    SidWithFourSubAuthorities  = RtlLengthRequiredSid( 4 );

    //
    //  Allocate and initialize the universal SIDs
    //

    NullSid    = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);
    WorldSid   = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);
    LocalSid   = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);
    CreatorOwnerSid = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);
    CreatorGroupSid = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);

    RtlInitializeSid( NullSid,    &NullSidAuthority, 1 );
    RtlInitializeSid( WorldSid,   &WorldSidAuthority, 1 );
    RtlInitializeSid( LocalSid,   &LocalSidAuthority, 1 );
    RtlInitializeSid( CreatorOwnerSid, &CreatorSidAuthority, 1 );
    RtlInitializeSid( CreatorGroupSid, &CreatorSidAuthority, 1 );

    *(RtlSubAuthoritySid( NullSid, 0 ))    = SECURITY_NULL_RID;
    *(RtlSubAuthoritySid( WorldSid, 0 ))   = SECURITY_WORLD_RID;
    *(RtlSubAuthoritySid( LocalSid, 0 ))   = SECURITY_LOCAL_RID;
    *(RtlSubAuthoritySid( CreatorOwnerSid, 0 )) = SECURITY_CREATOR_OWNER_RID;
    *(RtlSubAuthoritySid( CreatorGroupSid, 0 )) = SECURITY_CREATOR_GROUP_RID;

    //
    // Allocate and initialize the NT defined SIDs
    //

    NtAuthoritySid  = (PSID)TstAllocatePool(PagedPool,SidWithZeroSubAuthorities);
    DialupSid       = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);
    NetworkSid      = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);
    BatchSid        = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);
    InteractiveSid  = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);
    LocalSystemSid  = (PSID)TstAllocatePool(PagedPool,SidWithOneSubAuthority);

    RtlInitializeSid( NtAuthoritySid,   &NtAuthority, 0 );
    RtlInitializeSid( DialupSid,        &NtAuthority, 1 );
    RtlInitializeSid( NetworkSid,       &NtAuthority, 1 );
    RtlInitializeSid( BatchSid,         &NtAuthority, 1 );
    RtlInitializeSid( InteractiveSid,   &NtAuthority, 1 );
    RtlInitializeSid( LocalSystemSid,   &NtAuthority, 1 );

    *(RtlSubAuthoritySid( DialupSid,       0 )) = SECURITY_DIALUP_RID;
    *(RtlSubAuthoritySid( NetworkSid,      0 )) = SECURITY_NETWORK_RID;
    *(RtlSubAuthoritySid( BatchSid,        0 )) = SECURITY_BATCH_RID;
    *(RtlSubAuthoritySid( InteractiveSid,  0 )) = SECURITY_INTERACTIVE_RID;
    *(RtlSubAuthoritySid( LocalSystemSid,  0 )) = SECURITY_LOCAL_SYSTEM_RID;



    //
    // Allocate and initialize the Bedrock SIDs
    //

    BedrockDomainSid  = (PSID)TstAllocatePool(PagedPool,SidWithThreeSubAuthorities);
    BedrockADomainSid  = (PSID)TstAllocatePool(PagedPool,SidWithThreeSubAuthorities);
    BedrockBDomainSid  = (PSID)TstAllocatePool(PagedPool,SidWithThreeSubAuthorities);
    BedrockCDomainSid  = (PSID)TstAllocatePool(PagedPool,SidWithThreeSubAuthorities);
    BedrockDDomainSid  = (PSID)TstAllocatePool(PagedPool,SidWithThreeSubAuthorities);
    BedrockEDomainSid  = (PSID)TstAllocatePool(PagedPool,SidWithThreeSubAuthorities);

    FredSid           = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);
    WilmaSid          = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);
    PebblesSid        = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);
    DinoSid           = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);

    BarneySid         = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);
    BettySid          = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);
    BambamSid         = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);

    FlintstoneSid     = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);
    RubbleSid         = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);

    AdultSid          = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);
    ChildSid          = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);

    NeandertholSid    = (PSID)TstAllocatePool(PagedPool,SidWithFourSubAuthorities);

    RtlInitializeSid( BedrockDomainSid,   &BedrockAuthority, 3 );
    *(RtlSubAuthoritySid( BedrockDomainSid, 0)) = BEDROCK_SUBAUTHORITY_0;
    *(RtlSubAuthoritySid( BedrockDomainSid, 1)) = BEDROCK_SUBAUTHORITY_1;
    *(RtlSubAuthoritySid( BedrockDomainSid, 2)) = BEDROCK_SUBAUTHORITY_2;

    RtlInitializeSid( BedrockADomainSid,   &BedrockAAuthority, 3 );
    *(RtlSubAuthoritySid( BedrockADomainSid, 0)) = BEDROCKA_SUBAUTHORITY_0;
    *(RtlSubAuthoritySid( BedrockADomainSid, 1)) = BEDROCKA_SUBAUTHORITY_1;
    *(RtlSubAuthoritySid( BedrockADomainSid, 2)) = BEDROCKA_SUBAUTHORITY_2;


    RtlInitializeSid( BedrockBDomainSid,   &BedrockBAuthority, 3 );
    *(RtlSubAuthoritySid( BedrockBDomainSid, 0)) = BEDROCKB_SUBAUTHORITY_0;
    *(RtlSubAuthoritySid( BedrockBDomainSid, 1)) = BEDROCKB_SUBAUTHORITY_1;
    *(RtlSubAuthoritySid( BedrockBDomainSid, 2)) = BEDROCKB_SUBAUTHORITY_2;

    RtlInitializeSid( BedrockCDomainSid,   &BedrockCAuthority, 3 );
    *(RtlSubAuthoritySid( BedrockCDomainSid, 0)) = BEDROCKC_SUBAUTHORITY_0;
    *(RtlSubAuthoritySid( BedrockCDomainSid, 1)) = BEDROCKC_SUBAUTHORITY_1;
    *(RtlSubAuthoritySid( BedrockCDomainSid, 2)) = BEDROCKC_SUBAUTHORITY_2;

    RtlInitializeSid( BedrockDDomainSid,   &BedrockDAuthority, 3 );
    *(RtlSubAuthoritySid( BedrockDDomainSid, 0)) = BEDROCKD_SUBAUTHORITY_0;
    *(RtlSubAuthoritySid( BedrockDDomainSid, 1)) = BEDROCKD_SUBAUTHORITY_1;
    *(RtlSubAuthoritySid( BedrockDDomainSid, 2)) = BEDROCKD_SUBAUTHORITY_2;

    RtlInitializeSid( BedrockEDomainSid,   &BedrockEAuthority, 3 );
    *(RtlSubAuthoritySid( BedrockEDomainSid, 0)) = BEDROCKE_SUBAUTHORITY_0;
    *(RtlSubAuthoritySid( BedrockEDomainSid, 1)) = BEDROCKE_SUBAUTHORITY_1;
    *(RtlSubAuthoritySid( BedrockEDomainSid, 2)) = BEDROCKE_SUBAUTHORITY_2;

    RtlCopySid( SidWithFourSubAuthorities, FredSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( FredSid )) += 1;
    *(RtlSubAuthoritySid( FredSid, 3)) = FRED_RID;

    RtlCopySid( SidWithFourSubAuthorities, WilmaSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( WilmaSid )) += 1;
    *(RtlSubAuthoritySid( WilmaSid, 3)) = WILMA_RID;

    RtlCopySid( SidWithFourSubAuthorities, PebblesSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( PebblesSid )) += 1;
    *(RtlSubAuthoritySid( PebblesSid, 3)) = PEBBLES_RID;

    RtlCopySid( SidWithFourSubAuthorities, DinoSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( DinoSid )) += 1;
    *(RtlSubAuthoritySid( DinoSid, 3)) = DINO_RID;

    RtlCopySid( SidWithFourSubAuthorities, BarneySid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( BarneySid )) += 1;
    *(RtlSubAuthoritySid( BarneySid, 3)) = BARNEY_RID;

    RtlCopySid( SidWithFourSubAuthorities, BettySid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( BettySid )) += 1;
    *(RtlSubAuthoritySid( BettySid, 3)) = BETTY_RID;

    RtlCopySid( SidWithFourSubAuthorities, BambamSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( BambamSid )) += 1;
    *(RtlSubAuthoritySid( BambamSid, 3)) = BAMBAM_RID;

    RtlCopySid( SidWithFourSubAuthorities, FlintstoneSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( FlintstoneSid )) += 1;
    *(RtlSubAuthoritySid( FlintstoneSid, 3)) = FLINTSTONE_RID;

    RtlCopySid( SidWithFourSubAuthorities, RubbleSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( RubbleSid )) += 1;
    *(RtlSubAuthoritySid( RubbleSid, 3)) = RUBBLE_RID;

    RtlCopySid( SidWithFourSubAuthorities, AdultSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( AdultSid )) += 1;
    *(RtlSubAuthoritySid( AdultSid, 3)) = ADULT_RID;

    RtlCopySid( SidWithFourSubAuthorities, ChildSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( ChildSid )) += 1;
    *(RtlSubAuthoritySid( ChildSid, 3)) = CHILD_RID;

    RtlCopySid( SidWithFourSubAuthorities, NeandertholSid, BedrockDomainSid);
    *(RtlSubAuthorityCountSid( NeandertholSid )) += 1;
    *(RtlSubAuthoritySid( NeandertholSid, 3)) = NEANDERTHOL_RID;

    CreateTokenPrivilege =
        RtlConvertLongToLargeInteger(SE_CREATE_TOKEN_PRIVILEGE);
    AssignPrimaryTokenPrivilege =
        RtlConvertLongToLargeInteger(SE_ASSIGNPRIMARYTOKEN_PRIVILEGE);
    LockMemoryPrivilege =
        RtlConvertLongToLargeInteger(SE_LOCK_MEMORY_PRIVILEGE);
    IncreaseQuotaPrivilege =
        RtlConvertLongToLargeInteger(SE_INCREASE_QUOTA_PRIVILEGE);
    UnsolicitedInputPrivilege =
        RtlConvertLongToLargeInteger(SE_UNSOLICITED_INPUT_PRIVILEGE);
    TcbPrivilege =
        RtlConvertLongToLargeInteger(SE_TCB_PRIVILEGE);
    SecurityPrivilege =
        RtlConvertLongToLargeInteger(SE_SECURITY_PRIVILEGE);
    TakeOwnershipPrivilege =
        RtlConvertLongToLargeInteger(SE_TAKE_OWNERSHIP_PRIVILEGE);
    LpcReplyBoostPrivilege =
        RtlConvertLongToLargeInteger(SE_LPC_REPLY_BOOST_PRIVILEGE);
    CreatePagefilePrivilege =
        RtlConvertLongToLargeInteger(SE_CREATE_PAGEFILE_PRIVILEGE);
    IncreaseBasePriorityPrivilege =
        RtlConvertLongToLargeInteger(SE_INC_BASE_PRIORITY_PRIVILEGE);
    SystemProfilePrivilege =
        RtlConvertLongToLargeInteger(SE_SYSTEM_PROFILE_PRIVILEGE);
    SystemtimePrivilege =
        RtlConvertLongToLargeInteger(SE_SYSTEMTIME_PRIVILEGE);
    ProfileSingleProcessPrivilege =
        RtlConvertLongToLargeInteger(SE_PROF_SINGLE_PROCESS_PRIVILEGE);
    CreatePermanentPrivilege =
        RtlConvertLongToLargeInteger(SE_CREATE_PERMANENT_PRIVILEGE);
    BackupPrivilege =
        RtlConvertLongToLargeInteger(SE_BACKUP_PRIVILEGE);
    RestorePrivilege =
        RtlConvertLongToLargeInteger(SE_RESTORE_PRIVILEGE);
    ShutdownPrivilege =
        RtlConvertLongToLargeInteger(SE_SHUTDOWN_PRIVILEGE);
    DebugPrivilege =
        RtlConvertLongToLargeInteger(SE_DEBUG_PRIVILEGE);


    return TRUE;

}
Esempio n. 17
0
DWORD
LocalMarshalAttrToSid(
    PDIRECTORY_ENTRY  pEntry,
    PWSTR             pwszAttrName,
    PSID             *ppSid
    )
{
    DWORD dwError = 0;
    NTSTATUS ntStatus = 0;
    PDIRECTORY_ATTRIBUTE pAttr = NULL;
    PATTRIBUTE_VALUE pAttrValue = NULL;
    PSID pSid = NULL;
    DWORD dwSidSize = 0;
    PSID pRetSid = NULL;

    BAIL_ON_INVALID_POINTER(pEntry);

    dwError = LocalFindAttribute(
                    pEntry,
                    pwszAttrName,
                    &pAttr);
    BAIL_ON_LSA_ERROR(dwError);

    if (pAttr->ulNumValues > 1)
    {
        dwError = LW_ERROR_DATA_ERROR;
    }
    else if (pAttr->ulNumValues == 0)
    {
        dwError = LW_ERROR_NO_ATTRIBUTE_VALUE;
    }
    else
    {
        pAttrValue = &pAttr->pValues[0];

        if (pAttrValue->Type == DIRECTORY_ATTR_TYPE_UNICODE_STRING)
        {
            ntStatus = RtlAllocateSidFromWC16String(
                                  &pSid,
                                  pAttrValue->data.pwszStringValue);
            BAIL_ON_NT_STATUS(ntStatus);
        }
        else if (pAttrValue->Type == DIRECTORY_ATTR_TYPE_ANSI_STRING)
        {
            ntStatus = RtlAllocateSidFromCString(
                                  &pSid,
                                  pAttrValue->data.pszStringValue);
            BAIL_ON_NT_STATUS(ntStatus);
        }
        else
        {
            dwError = LW_ERROR_INVALID_ATTRIBUTE_VALUE;
        }
    }
    BAIL_ON_LSA_ERROR(dwError);

    dwSidSize = RtlLengthSid(pSid);
    dwError = LwAllocateMemory(
                    dwSidSize,
                    OUT_PPVOID(&pRetSid));
    BAIL_ON_LSA_ERROR(dwError);

    ntStatus = RtlCopySid(
                    dwSidSize,
                    pRetSid,
                    pSid);
    BAIL_ON_NT_STATUS(ntStatus);

    *ppSid = pRetSid;

cleanup:
    RTL_FREE(&pSid);

    if (dwError == ERROR_SUCCESS &&
        ntStatus != STATUS_SUCCESS)
    {
        dwError = LwNtStatusToWin32Error(ntStatus);
    }

    return dwError;

error:
    LW_SAFE_FREE_MEMORY(pRetSid);
    *ppSid = NULL;

    goto cleanup;
}