Example #1
0
static NTSTATUS
LsapGetDomainInfo(VOID)
{
    PLSA_DB_OBJECT PolicyObject = NULL;
    PUNICODE_STRING DomainName = NULL;
    ULONG AttributeSize;
    LPWSTR SidString = NULL;
    NTSTATUS Status;

    /* Get the built-in domain SID and name */
    Status = RtlAllocateAndInitializeSid(&NtAuthority,
                                         1,
                                         SECURITY_BUILTIN_DOMAIN_RID,
                                         0, 0, 0, 0, 0, 0, 0,
                                         &BuiltinDomainSid);
    if (!NT_SUCCESS(Status))
        return Status;

    /**/
    RtlInitUnicodeString(&BuiltinDomainName,
                         L"BUILTIN");

    /* Open the 'Policy' object */
    Status = LsapOpenDbObject(NULL,
                              NULL,
                              L"Policy",
                              LsaDbPolicyObject,
                              0,
                              TRUE,
                              &PolicyObject);
    if (!NT_SUCCESS(Status))
        goto done;

    /* Get the account domain SID */
    AttributeSize = 0;
    Status = LsapGetObjectAttribute(PolicyObject,
                                    L"PolAcDmS",
                                    NULL,
                                    &AttributeSize);
    if (!NT_SUCCESS(Status))
        goto done;

    if (AttributeSize > 0)
    {
        AccountDomainSid = RtlAllocateHeap(RtlGetProcessHeap(),
                                           HEAP_ZERO_MEMORY,
                                           AttributeSize);
        if (AccountDomainSid == NULL)
        {
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto done;
        }

        Status = LsapGetObjectAttribute(PolicyObject,
                                        L"PolAcDmS",
                                        AccountDomainSid,
                                        &AttributeSize);
        if (!NT_SUCCESS(Status))
            goto done;
    }

    /* Get the account domain name */
    AttributeSize = 0;
    Status = LsapGetObjectAttribute(PolicyObject,
                                    L"PolAcDmN",
                                    NULL,
                                    &AttributeSize);
    if (!NT_SUCCESS(Status))
        goto done;

    if (AttributeSize > 0)
    {
        DomainName = RtlAllocateHeap(RtlGetProcessHeap(),
                                     HEAP_ZERO_MEMORY,
                                     AttributeSize);
        if (DomainName == NULL)
        {
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto done;
        }

        Status = LsapGetObjectAttribute(PolicyObject,
                                        L"PolAcDmN",
                                        DomainName,
                                        &AttributeSize);
        if (!NT_SUCCESS(Status))
            goto done;

        DomainName->Buffer = (LPWSTR)((ULONG_PTR)DomainName + (ULONG_PTR)DomainName->Buffer);

        AccountDomainName.Length = DomainName->Length;
        AccountDomainName.MaximumLength = DomainName->Length + sizeof(WCHAR);
        AccountDomainName.Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
                                   HEAP_ZERO_MEMORY,
                                   AccountDomainName.MaximumLength);
        if (AccountDomainName.Buffer == NULL)
        {
            ERR("Failed to allocate the account domain name buffer\n");
            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto done;
        }

        RtlCopyMemory(AccountDomainName.Buffer,
                      DomainName->Buffer,
                      DomainName->Length);
    }

    ConvertSidToStringSidW(BuiltinDomainSid, &SidString);
    TRACE("Builtin Domain SID: %S\n", SidString);
    LocalFree(SidString);
    SidString = NULL;

    TRACE("Builtin Domain Name: %wZ\n", &BuiltinDomainName);

    ConvertSidToStringSidW(AccountDomainSid, &SidString);
    TRACE("Account Domain SID: %S\n", SidString);
    LocalFree(SidString);
    SidString = NULL;

    TRACE("Account Domain Name: %wZ\n", &AccountDomainName);

done:
    if (DomainName != NULL)
        RtlFreeHeap(RtlGetProcessHeap(), 0, DomainName);

    if (PolicyObject != NULL)
        LsapCloseDbObject(PolicyObject);

    return Status;
}
Example #2
0
NTSTATUS
NTAPI
CreateBaseAcls(OUT PACL* Dacl,
               OUT PACL* RestrictedDacl)
{
    PSID SystemSid, WorldSid, RestrictedSid;
    SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
    SID_IDENTIFIER_AUTHORITY WorldAuthority = {SECURITY_WORLD_SID_AUTHORITY};
    NTSTATUS Status;
#if 0 // Unused code
    UCHAR KeyValueBuffer[0x40];
    PKEY_VALUE_PARTIAL_INFORMATION KeyValuePartialInfo;
    UNICODE_STRING KeyName;
    ULONG ProtectionMode = 0;
#endif
    ULONG AclLength;
#if 0 // Unused code
    ULONG ResultLength;
    HANDLE hKey;
    OBJECT_ATTRIBUTES ObjectAttributes;

    /* Open the Session Manager Key */
    RtlInitUnicodeString(&KeyName, SM_REG_KEY);
    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);
    Status = NtOpenKey(&hKey, KEY_READ, &ObjectAttributes);
    if (NT_SUCCESS(Status))
    {
        /* Read the key value */
        RtlInitUnicodeString(&KeyName, L"ProtectionMode");
        Status = NtQueryValueKey(hKey,
                                 &KeyName,
                                 KeyValuePartialInformation,
                                 KeyValueBuffer,
                                 sizeof(KeyValueBuffer),
                                 &ResultLength);

        /* Make sure it's what we expect it to be */
        KeyValuePartialInfo = (PKEY_VALUE_PARTIAL_INFORMATION)KeyValueBuffer;
        if ((NT_SUCCESS(Status)) && (KeyValuePartialInfo->Type == REG_DWORD) &&
            (*(PULONG)KeyValuePartialInfo->Data))
        {
            /* Save the Protection Mode */
            ProtectionMode = *(PULONG)KeyValuePartialInfo->Data;
        }

        /* Close the handle */
        NtClose(hKey);
    }
#endif

    /* Allocate the System SID */
    Status = RtlAllocateAndInitializeSid(&NtAuthority,
                                         1, SECURITY_LOCAL_SYSTEM_RID,
                                         0, 0, 0, 0, 0, 0, 0,
                                         &SystemSid);
    ASSERT(NT_SUCCESS(Status));

    /* Allocate the World SID */
    Status = RtlAllocateAndInitializeSid(&WorldAuthority,
                                         1, SECURITY_WORLD_RID,
                                         0, 0, 0, 0, 0, 0, 0,
                                         &WorldSid);
    ASSERT(NT_SUCCESS(Status));

    /* Allocate the restricted SID */
    Status = RtlAllocateAndInitializeSid(&NtAuthority,
                                         1, SECURITY_RESTRICTED_CODE_RID,
                                         0, 0, 0, 0, 0, 0, 0,
                                         &RestrictedSid);
    ASSERT(NT_SUCCESS(Status));

    /* Allocate one ACL with 3 ACEs each for one SID */
    AclLength = sizeof(ACL) + 3 * sizeof(ACCESS_ALLOWED_ACE) +
                    RtlLengthSid(SystemSid) +
                    RtlLengthSid(WorldSid)  +
                    RtlLengthSid(RestrictedSid);
    *Dacl = RtlAllocateHeap(BaseSrvHeap, 0, AclLength);
    ASSERT(*Dacl != NULL);

    /* Set the correct header fields */
    Status = RtlCreateAcl(*Dacl, AclLength, ACL_REVISION2);
    ASSERT(NT_SUCCESS(Status));

    /* Give the appropriate rights to each SID */
    /* FIXME: Should check SessionId/ProtectionMode */
    Status = RtlAddAccessAllowedAce(*Dacl, ACL_REVISION2, DIRECTORY_QUERY | DIRECTORY_TRAVERSE | DIRECTORY_CREATE_OBJECT | DIRECTORY_CREATE_SUBDIRECTORY | READ_CONTROL, WorldSid);
    ASSERT(NT_SUCCESS(Status));
    Status = RtlAddAccessAllowedAce(*Dacl, ACL_REVISION2, DIRECTORY_ALL_ACCESS, SystemSid);
    ASSERT(NT_SUCCESS(Status));
    Status = RtlAddAccessAllowedAce(*Dacl, ACL_REVISION2, DIRECTORY_TRAVERSE, RestrictedSid);
    ASSERT(NT_SUCCESS(Status));

    /* Now allocate the restricted DACL */
    *RestrictedDacl = RtlAllocateHeap(BaseSrvHeap, 0, AclLength);
    ASSERT(*RestrictedDacl != NULL);

    /* Initialize it */
    Status = RtlCreateAcl(*RestrictedDacl, AclLength, ACL_REVISION2);
    ASSERT(NT_SUCCESS(Status));

    /* And add the same ACEs as before */
    /* FIXME: Not really fully correct */
    Status = RtlAddAccessAllowedAce(*RestrictedDacl, ACL_REVISION2, DIRECTORY_QUERY | DIRECTORY_TRAVERSE | DIRECTORY_CREATE_OBJECT | DIRECTORY_CREATE_SUBDIRECTORY | READ_CONTROL, WorldSid);
    ASSERT(NT_SUCCESS(Status));
    Status = RtlAddAccessAllowedAce(*RestrictedDacl, ACL_REVISION2, DIRECTORY_ALL_ACCESS, SystemSid);
    ASSERT(NT_SUCCESS(Status));
    Status = RtlAddAccessAllowedAce(*RestrictedDacl, ACL_REVISION2, DIRECTORY_TRAVERSE, RestrictedSid);
    ASSERT(NT_SUCCESS(Status));

    /* The SIDs are captured, can free them now */
    RtlFreeSid(RestrictedSid);
    RtlFreeSid(WorldSid);
    RtlFreeSid(SystemSid);
    return Status;
}
Example #3
0
static NTSTATUS
Fat12WriteFAT(IN HANDLE FileHandle,
              IN ULONG SectorOffset,
              IN PFAT16_BOOT_SECTOR BootSector,
              IN OUT PFORMAT_CONTEXT Context)
{
    IO_STATUS_BLOCK IoStatusBlock;
    NTSTATUS Status;
    PUCHAR Buffer;
    LARGE_INTEGER FileOffset;
    ULONG i;
    ULONG Size;
    ULONG Sectors;

    /* Allocate buffer */
    Buffer = (PUCHAR)RtlAllocateHeap(RtlGetProcessHeap(),
                                     0,
                                     32 * 1024);
    if (Buffer == NULL)
        return STATUS_INSUFFICIENT_RESOURCES;

    /* Zero the buffer */
    memset(Buffer, 0, 32 * 1024);

    /* FAT cluster 0 & 1*/
    Buffer[0] = 0xf8; /* Media type */
    Buffer[1] = 0xff;
    Buffer[2] = 0xff;

    /* Write first sector of the FAT */
    FileOffset.QuadPart = (SectorOffset + BootSector->ReservedSectors) * BootSector->BytesPerSector;
    Status = NtWriteFile(FileHandle,
                         NULL,
                         NULL,
                         NULL,
                         &IoStatusBlock,
                         Buffer,
                         BootSector->BytesPerSector,
                         &FileOffset,
                         NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("NtWriteFile() failed (Status %lx)\n", Status);
        RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
        return Status;
    }

    UpdateProgress(Context, 1);

    /* Zero the begin of the buffer */
    memset(Buffer, 0, 3);

    /* Zero the rest of the FAT */
    Sectors = 32 * 1024 / BootSector->BytesPerSector;
    for (i = 1; i < (ULONG)BootSector->FATSectors; i += Sectors)
    {
        /* Zero some sectors of the FAT */
        FileOffset.QuadPart = (SectorOffset + BootSector->ReservedSectors + i) * BootSector->BytesPerSector;
        if (((ULONG)BootSector->FATSectors - i) <= Sectors)
        {
            Sectors = (ULONG)BootSector->FATSectors - i;
        }

        Size = Sectors * BootSector->BytesPerSector;
        Status = NtWriteFile(FileHandle,
                             NULL,
                             NULL,
                             NULL,
                             &IoStatusBlock,
                             Buffer,
                             Size,
                             &FileOffset,
                             NULL);
        if (!NT_SUCCESS(Status))
        {
            DPRINT("NtWriteFile() failed (Status %lx)\n", Status);
            RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
            return Status;
        }

        UpdateProgress(Context, Sectors);
    }

    /* Free the buffer */
    RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);

    return Status;
}
Example #4
0
static BOOLEAN
GetDisplayIdentifier(PWSTR Identifier,
    ULONG IdentifierLength)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING KeyName;
    WCHAR Buffer[32];
    HANDLE BusKey;
    HANDLE BusInstanceKey;
    HANDLE ControllerKey;
    HANDLE ControllerInstanceKey;
    ULONG BusInstance;
    ULONG ControllerInstance;
    ULONG BufferLength;
    ULONG ReturnedLength;
    PKEY_VALUE_PARTIAL_INFORMATION ValueInfo;
    NTSTATUS Status;

    DPRINT("GetDisplayIdentifier() called\n");

    /* Open the bus key */
    RtlInitUnicodeString(&KeyName,
                         L"\\Registry\\Machine\\HARDWARE\\Description\\System\\MultifunctionAdapter");
    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    Status = NtOpenKey(&BusKey,
                       KEY_ENUMERATE_SUB_KEYS,
                       &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("NtOpenKey() failed (Status %lx)\n", Status);
        return FALSE;
    }

    BusInstance = 0;
    while (TRUE)
    {
        swprintf(Buffer, L"%lu", BusInstance);
        RtlInitUnicodeString(&KeyName,
                             Buffer);
        InitializeObjectAttributes(&ObjectAttributes,
                                   &KeyName,
                                   OBJ_CASE_INSENSITIVE,
                                   BusKey,
                                   NULL);

        Status = NtOpenKey(&BusInstanceKey,
                           KEY_ENUMERATE_SUB_KEYS,
                           &ObjectAttributes);
        if (!NT_SUCCESS(Status))
        {
            DPRINT("NtOpenKey() failed (Status %lx)\n", Status);
            NtClose(BusKey);
            return FALSE;
        }

        /* Open the controller type key */
        RtlInitUnicodeString(&KeyName,
                             L"DisplayController");
        InitializeObjectAttributes(&ObjectAttributes,
                                   &KeyName,
                                   OBJ_CASE_INSENSITIVE,
                                   BusInstanceKey,
                                   NULL);

        Status = NtOpenKey(&ControllerKey,
                           KEY_ENUMERATE_SUB_KEYS,
                           &ObjectAttributes);
        if (NT_SUCCESS(Status))
        {
            ControllerInstance = 0;

            while (TRUE)
            {
                /* Open the pointer controller instance key */
                swprintf(Buffer, L"%lu", ControllerInstance);
                RtlInitUnicodeString(&KeyName,
                                     Buffer);
                InitializeObjectAttributes(&ObjectAttributes,
                                           &KeyName,
                                           OBJ_CASE_INSENSITIVE,
                                           ControllerKey,
                                           NULL);

                Status = NtOpenKey(&ControllerInstanceKey,
                                   KEY_QUERY_VALUE,
                                   &ObjectAttributes);
                if (!NT_SUCCESS(Status))
                {
                    DPRINT("NtOpenKey() failed (Status %lx)\n", Status);
                    NtClose(ControllerKey);
                    NtClose(BusInstanceKey);
                    NtClose(BusKey);
                    return FALSE;
                }

                /* Get controller identifier */
                RtlInitUnicodeString(&KeyName,
                                     L"Identifier");

                BufferLength = sizeof(KEY_VALUE_PARTIAL_INFORMATION) +
                               256 * sizeof(WCHAR);
                ValueInfo = (KEY_VALUE_PARTIAL_INFORMATION*) RtlAllocateHeap(RtlGetProcessHeap(),
                                                                             0,
                                                                             BufferLength);
                if (ValueInfo == NULL)
                {
                    DPRINT("RtlAllocateHeap() failed\n");
                    NtClose(ControllerInstanceKey);
                    NtClose(ControllerKey);
                    NtClose(BusInstanceKey);
                    NtClose(BusKey);
                    return FALSE;
                }

                Status = NtQueryValueKey(ControllerInstanceKey,
                                         &KeyName,
                                         KeyValuePartialInformation,
                                         ValueInfo,
                                         BufferLength,
                                         &ReturnedLength);
                if (NT_SUCCESS(Status))
                {
                    DPRINT("Identifier: %S\n", (PWSTR)ValueInfo->Data);

                    BufferLength = min(ValueInfo->DataLength / sizeof(WCHAR), IdentifierLength);
                    RtlCopyMemory (Identifier,
                                   ValueInfo->Data,
                                   BufferLength * sizeof(WCHAR));
                    Identifier[BufferLength] = 0;

                    RtlFreeHeap(RtlGetProcessHeap(),
                                0,
                                ValueInfo);

                    NtClose(ControllerInstanceKey);
                    NtClose(ControllerKey);
                    NtClose(BusInstanceKey);
                    NtClose(BusKey);
                    return TRUE;
                }

                NtClose(ControllerInstanceKey);

                ControllerInstance++;
            }

            NtClose(ControllerKey);
        }

        NtClose(BusInstanceKey);

        BusInstance++;
    }

    NtClose(BusKey);

    return FALSE;
}
Example #5
0
PGENERIC_LIST
CreateLanguageList(HINF InfFile, WCHAR * DefaultLanguage) 
{
    CHAR Buffer[128];
    PGENERIC_LIST List;
    INFCONTEXT Context;
    PWCHAR KeyName;
    PWCHAR KeyValue;
    PWCHAR UserData;
    ULONG uIndex = 0;

    /* Get default language id */
    if (!SetupFindFirstLineW (InfFile, L"NLS", L"DefaultLanguage", &Context))
        return NULL;

    if (!INF_GetData (&Context, NULL, &KeyValue))
        return NULL;

    wcscpy(DefaultLanguage, KeyValue);

    SelectedLanguageId = KeyValue;

    List = CreateGenericList();
    if (List == NULL)
        return NULL;

    if (!SetupFindFirstLineW (InfFile, L"Language", NULL, &Context))
    {
        DestroyGenericList(List, FALSE);
        return NULL; 
    }

    do
    {
        if (!INF_GetData (&Context, &KeyName, &KeyValue))
        {
            /* FIXME: Handle error! */
            DPRINT("INF_GetData() failed\n");
            break;
        }

        UserData = (WCHAR*) RtlAllocateHeap(ProcessHeap,
                                            0,
                                            (wcslen(KeyName) + 1) * sizeof(WCHAR));
        if (UserData == NULL)
        {
            /* FIXME: Handle error! */
        }

        wcscpy(UserData, KeyName);

        if (!_wcsicmp(KeyName, DefaultLanguage)) DefaultLanguageIndex = uIndex;

        sprintf(Buffer, "%S", KeyValue);
        AppendGenericListEntry(List,
                               Buffer,
                               UserData,
                               FALSE);
        uIndex++;
    } while (SetupFindNextLine(&Context, &Context));

    return List;
}
Example #6
0
/*
 * @implemented
 */
VOID
WINAPI
GetStartupInfoA(LPSTARTUPINFOA lpStartupInfo)
{
    PRTL_USER_PROCESS_PARAMETERS Params;
    ANSI_STRING AnsiString;

    if (lpStartupInfo == NULL)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return;
    }

    Params = NtCurrentPeb ()->ProcessParameters;

    RtlAcquirePebLock ();

    /* FIXME - not thread-safe */
    if (lpLocalStartupInfo == NULL)
    {
        /* create new local startup info (ansi) */
        lpLocalStartupInfo = RtlAllocateHeap(RtlGetProcessHeap(),
                                             0,
                                             sizeof(STARTUPINFOA));
        if (lpLocalStartupInfo == NULL)
        {
            RtlReleasePebLock();
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            return;
        }

        lpLocalStartupInfo->cb = sizeof(STARTUPINFOA);

        /* copy window title string */
        RtlUnicodeStringToAnsiString(&AnsiString,
                                     &Params->WindowTitle,
                                     TRUE);
        lpLocalStartupInfo->lpTitle = AnsiString.Buffer;

        /* copy desktop info string */
        RtlUnicodeStringToAnsiString(&AnsiString,
                                     &Params->DesktopInfo,
                                     TRUE);
        lpLocalStartupInfo->lpDesktop = AnsiString.Buffer;

        /* copy shell info string */
        RtlUnicodeStringToAnsiString(&AnsiString,
                                     &Params->ShellInfo,
                                     TRUE);
        lpLocalStartupInfo->lpReserved = AnsiString.Buffer;

        lpLocalStartupInfo->dwX = Params->StartingX;
        lpLocalStartupInfo->dwY = Params->StartingY;
        lpLocalStartupInfo->dwXSize = Params->CountX;
        lpLocalStartupInfo->dwYSize = Params->CountY;
        lpLocalStartupInfo->dwXCountChars = Params->CountCharsX;
        lpLocalStartupInfo->dwYCountChars = Params->CountCharsY;
        lpLocalStartupInfo->dwFillAttribute = Params->FillAttribute;
        lpLocalStartupInfo->dwFlags = Params->WindowFlags;
        lpLocalStartupInfo->wShowWindow = (WORD)Params->ShowWindowFlags;
        lpLocalStartupInfo->cbReserved2 = Params->RuntimeData.Length;
        lpLocalStartupInfo->lpReserved2 = (LPBYTE)Params->RuntimeData.Buffer;

        lpLocalStartupInfo->hStdInput = Params->StandardInput;
        lpLocalStartupInfo->hStdOutput = Params->StandardOutput;
        lpLocalStartupInfo->hStdError = Params->StandardError;
    }

    RtlReleasePebLock();

    /* copy local startup info data to external startup info */
    memcpy(lpStartupInfo,
           lpLocalStartupInfo,
           sizeof(STARTUPINFOA));
}
Example #7
0
static BOOLEAN
GetComputerIdentifier(PWSTR Identifier,
                      ULONG IdentifierLength)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING KeyName;
    LPCWSTR ComputerIdentifier;
    HANDLE ProcessorsKey;
    PKEY_FULL_INFORMATION pFullInfo;
    ULONG Size, SizeNeeded;
    NTSTATUS Status;

    DPRINT("GetComputerIdentifier() called\n");

    Size = sizeof(KEY_FULL_INFORMATION);
    pFullInfo = (PKEY_FULL_INFORMATION)RtlAllocateHeap(RtlGetProcessHeap(), 0, Size);
    if (!pFullInfo)
    {
        DPRINT("RtlAllocateHeap() failed\n");
        return FALSE;
    }

    /* Open the processors key */
    RtlInitUnicodeString(&KeyName,
                         L"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor");
    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    Status = NtOpenKey(&ProcessorsKey,
                       KEY_QUERY_VALUE ,
                       &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("NtOpenKey() failed (Status 0x%lx)\n", Status);
        RtlFreeHeap(RtlGetProcessHeap(), 0, pFullInfo);
        return FALSE;
    }

    /* Get number of subkeys */
    Status = NtQueryKey(
        ProcessorsKey,
        KeyFullInformation,
        pFullInfo,
        Size,
        &Size);
    NtClose(ProcessorsKey);

    if (!NT_SUCCESS(Status) && Status != STATUS_BUFFER_OVERFLOW)
    {
        DPRINT("NtQueryKey() failed (Status 0x%lx)\n", Status);
        RtlFreeHeap(RtlGetProcessHeap(), 0, pFullInfo);
        return FALSE;
    }

    /* Find computer identifier */
    if (pFullInfo->SubKeys == 0)
    {
        /* Something strange happened. No processor detected */
        RtlFreeHeap(RtlGetProcessHeap(), 0, pFullInfo);
        return FALSE;
    }

    if (IsAcpiComputer())
    {
        if (pFullInfo->SubKeys == 1)
        {
            /* Computer is mono-CPU */
            ComputerIdentifier = L"ACPI UP";
        }
        else
        {
            /* Computer is multi-CPUs */
            ComputerIdentifier = L"ACPI MP";
        }
    }
    else
    {
        if (pFullInfo->SubKeys == 1)
        {
            /* Computer is mono-CPU */
            ComputerIdentifier = L"PC UP";
        }
        else
        {
            /* Computer is multi-CPUs */
            ComputerIdentifier = L"PC MP";
        }
    }

    RtlFreeHeap(RtlGetProcessHeap(), 0, pFullInfo);

    /* Copy computer identifier to return buffer */
    SizeNeeded = (wcslen(ComputerIdentifier) + 1) * sizeof(WCHAR);
    if (SizeNeeded > IdentifierLength)
        return FALSE;

    RtlCopyMemory(Identifier, ComputerIdentifier, SizeNeeded);

    return TRUE;
}
Example #8
0
DNS_STATUS WINAPI
DnsQuery_W(LPCWSTR Name,
           WORD Type,
           DWORD Options,
           PIP4_ARRAY Servers,
           PDNS_RECORD *QueryResultSet,
           PVOID *Reserved)
{
    UINT i;
    PCHAR Buffer;
    DNS_STATUS Status;
    PDNS_RECORD QueryResultWide;
    PDNS_RECORD ConvertedRecord = 0, LastRecord = 0;

    Buffer = DnsWToC(Name);

    Status = DnsQuery_A(Buffer, Type, Options, Servers, &QueryResultWide, Reserved);

    while(Status == ERROR_SUCCESS && QueryResultWide)
    {
        switch(QueryResultWide->wType)
        {
            case DNS_TYPE_A:
            case DNS_TYPE_WKS:
                ConvertedRecord = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(DNS_RECORD));
                ConvertedRecord->pName = (PCHAR)DnsCToW(QueryResultWide->pName);
                ConvertedRecord->wType = QueryResultWide->wType;
                ConvertedRecord->wDataLength = QueryResultWide->wDataLength;
                memcpy(ConvertedRecord, QueryResultWide, QueryResultWide->wDataLength);
                break;

            case DNS_TYPE_CNAME:
            case DNS_TYPE_PTR:
            case DNS_TYPE_NS:
            case DNS_TYPE_MB:
            case DNS_TYPE_MD:
            case DNS_TYPE_MF:
            case DNS_TYPE_MG:
            case DNS_TYPE_MR:
                ConvertedRecord = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(DNS_RECORD));
                ConvertedRecord->pName = (PCHAR)DnsCToW(QueryResultWide->pName);
                ConvertedRecord->wType = QueryResultWide->wType;
                ConvertedRecord->wDataLength = sizeof(DNS_PTR_DATA);
                ConvertedRecord->Data.PTR.pNameHost = (PCHAR)DnsCToW(QueryResultWide->Data.PTR.pNameHost);
                break;

            case DNS_TYPE_MINFO:
                ConvertedRecord = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(DNS_RECORD));
                ConvertedRecord->pName = (PCHAR)DnsCToW(QueryResultWide->pName);
                ConvertedRecord->wType = QueryResultWide->wType;
                ConvertedRecord->wDataLength = sizeof(DNS_MINFO_DATA);
                ConvertedRecord->Data.MINFO.pNameMailbox = (PCHAR)DnsCToW(QueryResultWide->Data.MINFO.pNameMailbox);
                ConvertedRecord->Data.MINFO.pNameErrorsMailbox = (PCHAR)DnsCToW(QueryResultWide->Data.MINFO.pNameErrorsMailbox);
                break;

            case DNS_TYPE_MX:
                ConvertedRecord = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(DNS_RECORD));
                ConvertedRecord->pName = (PCHAR)DnsCToW(QueryResultWide->pName);
                ConvertedRecord->wType = QueryResultWide->wType;
                ConvertedRecord->wDataLength = sizeof(DNS_MX_DATA);
                ConvertedRecord->Data.MX.pNameExchange = (PCHAR)DnsCToW( QueryResultWide->Data.MX.pNameExchange);
                ConvertedRecord->Data.MX.wPreference = QueryResultWide->Data.MX.wPreference;
                break;

            case DNS_TYPE_HINFO:
                ConvertedRecord = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(DNS_TXT_DATA) + QueryResultWide->Data.TXT.dwStringCount);
                ConvertedRecord->pName = (PCHAR)DnsCToW( QueryResultWide->pName );
                ConvertedRecord->wType = QueryResultWide->wType;
                ConvertedRecord->wDataLength = sizeof(DNS_TXT_DATA) + (sizeof(PWCHAR) * QueryResultWide->Data.TXT.dwStringCount);
                ConvertedRecord->Data.TXT.dwStringCount = QueryResultWide->Data.TXT.dwStringCount;

                for(i = 0; i < ConvertedRecord->Data.TXT.dwStringCount; i++)
                    ConvertedRecord->Data.TXT.pStringArray[i] = (PCHAR)DnsCToW(QueryResultWide->Data.TXT.pStringArray[i]);

                break;

            case DNS_TYPE_NULL:
                ConvertedRecord = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(DNS_NULL_DATA) + QueryResultWide->Data.Null.dwByteCount);
                ConvertedRecord->pName = (PCHAR)DnsCToW(QueryResultWide->pName);
                ConvertedRecord->wType = QueryResultWide->wType;
                ConvertedRecord->wDataLength = sizeof(DNS_NULL_DATA) + QueryResultWide->Data.Null.dwByteCount;
                ConvertedRecord->Data.Null.dwByteCount = QueryResultWide->Data.Null.dwByteCount;
                memcpy(&ConvertedRecord->Data.Null.Data, &QueryResultWide->Data.Null.Data, QueryResultWide->Data.Null.dwByteCount);
                break;
        }

        if(LastRecord)
        {
            LastRecord->pNext = ConvertedRecord;
            LastRecord = LastRecord->pNext;
        }
        else
        {
            LastRecord = *QueryResultSet = ConvertedRecord;
        }
    }

    if (LastRecord)
        LastRecord->pNext = 0;

    /* The name */
    RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);

    return Status;
}
Example #9
0
DNS_STATUS WINAPI
DnsQuery_A(LPCSTR Name,
           WORD Type,
           DWORD Options,
           PIP4_ARRAY Servers,
           PDNS_RECORD *QueryResultSet,
           PVOID *Reserved)
{
    adns_state astate;
    int quflags = 0;
    int adns_error;
    adns_answer *answer;
    LPSTR CurrentName;
    unsigned i, CNameLoop;

    *QueryResultSet = 0;

    switch(Type)
    {
        case DNS_TYPE_A:
            adns_error = adns_init(&astate, adns_if_noenv | adns_if_noerrprint | adns_if_noserverwarn, 0);

            if(adns_error != adns_s_ok)
                return DnsIntTranslateAdnsToDNS_STATUS(adns_error);

            if (Servers)
            {
                for(i = 0; i < Servers->AddrCount; i++)
                {
                    adns_addserver(astate, *((struct in_addr *)&Servers->AddrArray[i]));
                }
            }

            /*
             * adns doesn't resolve chained CNAME records (a CNAME which points to
             * another CNAME pointing to another... pointing to an A record), according
             * to a mailing list thread the authors believe that chained CNAME records
             * are invalid and the DNS entries should be fixed. That's a nice academic
             * standpoint, but there certainly are chained CNAME records out there,
             * even some fairly major ones (at the time of this writing
             * download.mozilla.org is a chained CNAME). Everyone else seems to resolve
             * these fine, so we should too. So we loop here to try to resolve CNAME
             * chains ourselves. Of course, there must be a limit to protect against
             * CNAME loops.
             */

#define CNAME_LOOP_MAX 16

            CurrentName = (LPSTR) Name;

            for (CNameLoop = 0; CNameLoop < CNAME_LOOP_MAX; CNameLoop++)
            {
                adns_error = adns_synchronous(astate, CurrentName, adns_r_addr, quflags, &answer);

                if(adns_error != adns_s_ok)
                {
                    adns_finish(astate);

                    if (CurrentName != Name)
                        RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentName);

                    return DnsIntTranslateAdnsToDNS_STATUS(adns_error);
                }

                if(answer && answer->rrs.addr)
                {
                    if (CurrentName != Name)
                        RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentName);

                    *QueryResultSet = (PDNS_RECORD)RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(DNS_RECORD));

                    if (NULL == *QueryResultSet)
                    {
                        adns_finish( astate );
                        return ERROR_OUTOFMEMORY;
                    }

                    (*QueryResultSet)->pNext = NULL;
                    (*QueryResultSet)->wType = Type;
                    (*QueryResultSet)->wDataLength = sizeof(DNS_A_DATA);
                    (*QueryResultSet)->Data.A.IpAddress = answer->rrs.addr->addr.inet.sin_addr.s_addr;

                    adns_finish(astate);

                    (*QueryResultSet)->pName = xstrsave( Name );

                    return NULL != (*QueryResultSet)->pName ? ERROR_SUCCESS : ERROR_OUTOFMEMORY;
                }

                if (NULL == answer || adns_s_prohibitedcname != answer->status || NULL == answer->cname)
                {
                    adns_finish(astate);

                    if (CurrentName != Name)
                        RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentName);

                    return ERROR_FILE_NOT_FOUND;
                }

                if (CurrentName != Name)
                    RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentName);

                CurrentName = xstrsave(answer->cname);

                if (!CurrentName)
                {
                    adns_finish(astate);
                    return ERROR_OUTOFMEMORY;
                }
            }

            adns_finish(astate);
            RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentName);
            return ERROR_FILE_NOT_FOUND;

        default:
            return ERROR_OUTOFMEMORY; /* XXX arty: find a better error code. */
    }
}
Example #10
0
void *__cdecl
calloc(size_t nmemb, size_t size)
{
    return (void *)RtlAllocateHeap(ProcessHeap, HEAP_ZERO_MEMORY, nmemb * size);
}
Example #11
0
NTSTATUS
NlInitialize(
    VOID
    )

/*++

Routine Description:

    Initialize NETLOGON portion of msv1_0 authentication package.

Arguments:

    None.

Return Status:

    STATUS_SUCCESS - Indicates NETLOGON successfully initialized.

--*/

{
    NTSTATUS Status;
    LPWSTR ComputerName;
    DWORD ComputerNameLength = MAX_COMPUTERNAME_LENGTH + 1;
    NT_PRODUCT_TYPE NtProductType;
    UNICODE_STRING TempUnicodeString;

    //
    // Initialize global data
    //

    NlpEnumerationHandle = 0;
    NlpSessionCount = 0;

    NlpComputerName.Buffer = NULL;
    NlpSamDomainName.Buffer = NULL;
    NlpSamDomainId = NULL;
    NlpSamDomainHandle = NULL;



    //
    // Get the name of this machine.
    //

    ComputerName = RtlAllocateHeap(
                        MspHeap, 0,
                        ComputerNameLength * sizeof(WCHAR) );

    if (ComputerName == NULL ||
        !GetComputerNameW( ComputerName, &ComputerNameLength )) {

        KdPrint(( "MsV1_0: Cannot get computername %lX\n", GetLastError() ));

        NlpLanmanInstalled = FALSE;
        RtlFreeHeap( MspHeap, 0, ComputerName );
        ComputerName = NULL;
    } else {

        NlpLanmanInstalled = TRUE;
    }

    RtlInitUnicodeString( &NlpComputerName, ComputerName );

    //
    // Determine if this machine is running Windows NT or Lanman NT.
    //  LanMan NT runs on a domain controller.
    //

    if ( !RtlGetNtProductType( &NtProductType ) ) {
        KdPrint(( "MsV1_0: Nt Product Type undefined (WinNt assumed)\n" ));
        NtProductType = NtProductWinNt;
    }

    NlpWorkstation = (BOOLEAN)(NtProductType != NtProductLanManNt);


#ifdef notdef

    //
    // Initialize any locks.
    //

    RtlInitializeCriticalSection(&NlpActiveLogonLock);
    RtlInitializeCriticalSection(&NlpSessionCountLock);

    //
    // initialize the cache - creates a critical section is all
    //

    NlpCacheInitialize();
#endif // notdef


    //
    // Attempt to load Netapi.dll
    //

    NlpLoadNetapiDll();

#ifdef COMPILED_BY_DEVELOPER
    KdPrint(("msv1_0: COMPILED_BY_DEVELOPER breakpoint.\n"));
    DbgBreakPoint();
#endif // COMPILED_BY_DEVELOPER



    //
    // Initialize useful encryption constants
    //

    Status = RtlCalculateLmOwfPassword( "", &NlpNullLmOwfPassword );
    ASSERT( NT_SUCCESS(Status) );

    RtlInitUnicodeString(&TempUnicodeString, NULL);
    Status = RtlCalculateNtOwfPassword(&TempUnicodeString,
                                       &NlpNullNtOwfPassword);
    ASSERT( NT_SUCCESS(Status) );




#ifdef notdef
    //
    // If we weren't successful,
    //  Clean up global resources we intended to initialize.
    //

    if ( !NT_SUCCESS(Status) ) {
        if ( NlpComputerName.Buffer != NULL ) {
            MIDL_user_free( NlpComputerName.Buffer );
        }

    }
#endif // notdef

    return STATUS_SUCCESS;

}
Example #12
0
/* Needed by zlib, but we don't want the dependency on msvcrt.dll */
void *__cdecl
malloc(size_t size)
{
    return RtlAllocateHeap(ProcessHeap, HEAP_ZERO_MEMORY, size);
}
Example #13
0
voidpf
MSZipAlloc(voidpf opaque, uInt items, uInt size)
{
    return (voidpf)RtlAllocateHeap(ProcessHeap, 0, items * size);
}
Example #14
0
NTSTATUS
LsapOpenDbObject(IN PLSA_DB_OBJECT ParentObject,
                 IN LPWSTR ContainerName,
                 IN LPWSTR ObjectName,
                 IN LSA_DB_OBJECT_TYPE ObjectType,
                 IN ACCESS_MASK DesiredAccess,
                 IN BOOLEAN Trusted,
                 OUT PLSA_DB_OBJECT *DbObject)
{
    PLSA_DB_OBJECT NewObject;
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING KeyName;
    HANDLE ParentKeyHandle;
    HANDLE ContainerKeyHandle = NULL;
    HANDLE ObjectKeyHandle = NULL;
    NTSTATUS Status;

    if (DbObject == NULL)
        return STATUS_INVALID_PARAMETER;

    if (ParentObject == NULL)
        ParentKeyHandle = SecurityKeyHandle;
    else
        ParentKeyHandle = ParentObject->KeyHandle;

    if (ContainerName != NULL)
    {
        /* Open the container key */
        RtlInitUnicodeString(&KeyName,
                             ContainerName);

        InitializeObjectAttributes(&ObjectAttributes,
                                   &KeyName,
                                   OBJ_CASE_INSENSITIVE,
                                   ParentKeyHandle,
                                   NULL);

        Status = NtOpenKey(&ContainerKeyHandle,
                           KEY_ALL_ACCESS,
                           &ObjectAttributes);
        if (!NT_SUCCESS(Status))
        {
            return Status;
        }

        /* Open the object key */
        RtlInitUnicodeString(&KeyName,
                             ObjectName);

        InitializeObjectAttributes(&ObjectAttributes,
                                   &KeyName,
                                   OBJ_CASE_INSENSITIVE,
                                   ContainerKeyHandle,
                                   NULL);

        Status = NtOpenKey(&ObjectKeyHandle,
                           KEY_ALL_ACCESS,
                           &ObjectAttributes);

        NtClose(ContainerKeyHandle);

        if (!NT_SUCCESS(Status))
        {
            return Status;
        }
    }
    else
    {
        /* Open the object key */
        RtlInitUnicodeString(&KeyName,
                             ObjectName);

        InitializeObjectAttributes(&ObjectAttributes,
                                   &KeyName,
                                   OBJ_CASE_INSENSITIVE,
                                   ParentKeyHandle,
                                   NULL);

        Status = NtOpenKey(&ObjectKeyHandle,
                           KEY_ALL_ACCESS,
                           &ObjectAttributes);
        if (!NT_SUCCESS(Status))
        {
            return Status;
        }
    }

    NewObject = RtlAllocateHeap(RtlGetProcessHeap(),
                                0,
                                sizeof(LSA_DB_OBJECT));
    if (NewObject == NULL)
    {
        NtClose(ObjectKeyHandle);
        return STATUS_NO_MEMORY;
    }

    NewObject->Signature = LSAP_DB_SIGNATURE;
    NewObject->RefCount = 1;
    NewObject->ObjectType = ObjectType;
    NewObject->Access = DesiredAccess;
    NewObject->KeyHandle = ObjectKeyHandle;
    NewObject->ParentObject = ParentObject;
    NewObject->Trusted = Trusted;

    if (ParentObject != NULL)
        ParentObject->RefCount++;

    *DbObject = NewObject;

    return STATUS_SUCCESS;
}
Example #15
0
static NTSTATUS
ReadRecord(IN  PEVTLOGFILE LogFile,
           IN  ULONG RecordNumber,
           OUT PEVENTLOGRECORD Record,
           IN  SIZE_T  BufSize, // Length
           OUT PSIZE_T BytesRead OPTIONAL,
           OUT PSIZE_T BytesNeeded OPTIONAL,
           IN  BOOLEAN Ansi)
{
    NTSTATUS Status;
    PEVENTLOGRECORD UnicodeBuffer = NULL;
    PEVENTLOGRECORD Src, Dst;
    ANSI_STRING StringA;
    UNICODE_STRING StringW;
    PVOID SrcPtr, DstPtr;
    DWORD i;
    DWORD dwPadding;
    DWORD dwRecordLength;
    PDWORD pLength;

    if (!Ansi)
    {
        return ElfReadRecord(LogFile,
                             RecordNumber,
                             Record,
                             BufSize,
                             BytesRead,
                             BytesNeeded);
    }

    if (BytesRead)
        *BytesRead = 0;

    if (BytesNeeded)
        *BytesNeeded = 0;

    UnicodeBuffer = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, BufSize);
    if (UnicodeBuffer == NULL)
    {
        DPRINT1("Alloc failed!\n");
        return STATUS_NO_MEMORY;
    }

    Status = ElfReadRecord(LogFile,
                           RecordNumber,
                           UnicodeBuffer,
                           BufSize,
                           BytesRead,
                           BytesNeeded);
    if (!NT_SUCCESS(Status))
        goto Quit;

    Src = UnicodeBuffer;
    Dst = Record;

    Dst->Reserved      = Src->Reserved;
    Dst->RecordNumber  = Src->RecordNumber;
    Dst->TimeGenerated = Src->TimeGenerated;
    Dst->TimeWritten   = Src->TimeWritten;
    Dst->EventID       = Src->EventID;
    Dst->EventType     = Src->EventType;
    Dst->EventCategory = Src->EventCategory;
    Dst->NumStrings    = Src->NumStrings;
    Dst->UserSidLength = Src->UserSidLength;
    Dst->DataLength    = Src->DataLength;

    SrcPtr = (PVOID)((ULONG_PTR)Src + sizeof(EVENTLOGRECORD));
    DstPtr = (PVOID)((ULONG_PTR)Dst + sizeof(EVENTLOGRECORD));

    /* Convert the module name */
    RtlInitUnicodeString(&StringW, SrcPtr);
    Status = RtlUnicodeStringToAnsiString(&StringA, &StringW, TRUE);
    if (NT_SUCCESS(Status))
    {
        RtlCopyMemory(DstPtr, StringA.Buffer, StringA.MaximumLength);
        DstPtr = (PVOID)((ULONG_PTR)DstPtr + StringA.MaximumLength);

        RtlFreeAnsiString(&StringA);
    }
    else
    {
        RtlZeroMemory(DstPtr, StringW.MaximumLength / sizeof(WCHAR));
        DstPtr = (PVOID)((ULONG_PTR)DstPtr + StringW.MaximumLength / sizeof(WCHAR));
    }
    SrcPtr = (PVOID)((ULONG_PTR)SrcPtr + StringW.MaximumLength);

    /* Convert the computer name */
    RtlInitUnicodeString(&StringW, SrcPtr);
    Status = RtlUnicodeStringToAnsiString(&StringA, &StringW, TRUE);
    if (NT_SUCCESS(Status))
    {
        RtlCopyMemory(DstPtr, StringA.Buffer, StringA.MaximumLength);
        DstPtr = (PVOID)((ULONG_PTR)DstPtr + StringA.MaximumLength);

        RtlFreeAnsiString(&StringA);
    }
    else
    {
        RtlZeroMemory(DstPtr, StringW.MaximumLength / sizeof(WCHAR));
        DstPtr = (PVOID)((ULONG_PTR)DstPtr + StringW.MaximumLength / sizeof(WCHAR));
    }

    /* Add the padding and the User SID */
    dwPadding = sizeof(ULONG) - (((ULONG_PTR)DstPtr - (ULONG_PTR)Dst) % sizeof(ULONG));
    RtlZeroMemory(DstPtr, dwPadding);

    SrcPtr = (PVOID)((ULONG_PTR)Src + Src->UserSidOffset);
    DstPtr = (PVOID)((ULONG_PTR)DstPtr + dwPadding);

    Dst->UserSidOffset = (DWORD)((ULONG_PTR)DstPtr - (ULONG_PTR)Dst);
    RtlCopyMemory(DstPtr, SrcPtr, Src->UserSidLength);

    /* Convert the strings */
    SrcPtr = (PVOID)((ULONG_PTR)Src + Src->StringOffset);
    DstPtr = (PVOID)((ULONG_PTR)DstPtr + Src->UserSidLength);
    Dst->StringOffset = (DWORD)((ULONG_PTR)DstPtr - (ULONG_PTR)Dst);

    for (i = 0; i < Dst->NumStrings; i++)
    {
        RtlInitUnicodeString(&StringW, SrcPtr);
        Status = RtlUnicodeStringToAnsiString(&StringA, &StringW, TRUE);
        if (NT_SUCCESS(Status))
        {
            RtlCopyMemory(DstPtr, StringA.Buffer, StringA.MaximumLength);
            DstPtr = (PVOID)((ULONG_PTR)DstPtr + StringA.MaximumLength);

            RtlFreeAnsiString(&StringA);
        }
        else
        {
            RtlZeroMemory(DstPtr, StringW.MaximumLength / sizeof(WCHAR));
            DstPtr = (PVOID)((ULONG_PTR)DstPtr + StringW.MaximumLength / sizeof(WCHAR));
        }
        SrcPtr = (PVOID)((ULONG_PTR)SrcPtr + StringW.MaximumLength);
    }

    /* Copy the binary data */
    SrcPtr = (PVOID)((ULONG_PTR)Src + Src->DataOffset);
    Dst->DataOffset = (ULONG_PTR)DstPtr - (ULONG_PTR)Dst;
    RtlCopyMemory(DstPtr, SrcPtr, Src->DataLength);
    DstPtr = (PVOID)((ULONG_PTR)DstPtr + Src->DataLength);

    /* Add the padding */
    dwPadding = sizeof(ULONG) - (((ULONG_PTR)DstPtr - (ULONG_PTR)Dst) % sizeof(ULONG));
    RtlZeroMemory(DstPtr, dwPadding);

    /* Set the record length at the beginning and the end of the record */
    dwRecordLength = (DWORD)((ULONG_PTR)DstPtr + dwPadding + sizeof(ULONG) - (ULONG_PTR)Dst);
    Dst->Length = dwRecordLength;
    pLength = (PDWORD)((ULONG_PTR)DstPtr + dwPadding);
    *pLength = dwRecordLength;

    if (BytesRead)
        *BytesRead = dwRecordLength;

    Status = STATUS_SUCCESS;

Quit:
    RtlFreeHeap(GetProcessHeap(), 0, UnicodeBuffer);

    return Status;
}
Example #16
0
BOOL
SetCtrlHandler(
    IN PHANDLER_ROUTINE HandlerRoutine
)

/*++

Routine Description:

    This routine adds a ctrl handler to the process's list.

Arguments:

    HandlerRoutine - pointer to ctrl handler.

Return Value:

    TRUE - success.

--*/

{
    PHANDLER_ROUTINE *NewHandlerList;

    //
    // NULL handler routine is not stored in table. It is
    // used to temporarily inhibit ^C event handling
    //

    if ( !HandlerRoutine ) {
        NtCurrentPeb()->ProcessParameters->ConsoleFlags = IGNORE_CTRL_C;
        return TRUE;
    }

    if (HandlerListLength == AllocatedHandlerListLength) {

        //
        // grow list
        //

        NewHandlerList = (PHANDLER_ROUTINE *) RtlAllocateHeap( RtlProcessHeap(), 0,
                         sizeof(PHANDLER_ROUTINE) * (HandlerListLength + LIST_INCREMENT));
        if (!NewHandlerList) {
            SET_LAST_ERROR(ERROR_NOT_ENOUGH_MEMORY);
            return FALSE;
        }

        //
        // copy list
        //

        RtlCopyMemory(NewHandlerList,HandlerList,sizeof(PHANDLER_ROUTINE) * HandlerListLength);

        if (HandlerList != SingleHandler) {

            //
            // free old list
            //

            RtlFreeHeap(RtlProcessHeap(), 0, HandlerList);
        }
        HandlerList = NewHandlerList;
        AllocatedHandlerListLength += LIST_INCREMENT;
    }
    ASSERT (HandlerListLength < AllocatedHandlerListLength);

    HandlerList[HandlerListLength] = HandlerRoutine;
    HandlerListLength++;
    return TRUE;
}
Example #17
0
PEVENTLOGRECORD
LogfAllocAndBuildNewRecord(PSIZE_T pRecSize,
                           ULONG   Time,
                           USHORT  wType,
                           USHORT  wCategory,
                           ULONG   dwEventId,
                           PUNICODE_STRING SourceName,
                           PUNICODE_STRING ComputerName,
                           ULONG   dwSidLength,
                           PSID    pUserSid,
                           USHORT  wNumStrings,
                           PWSTR   pStrings,
                           ULONG   dwDataSize,
                           PVOID   pRawData)
{
    SIZE_T RecSize;
    SIZE_T SourceNameSize, ComputerNameSize, StringLen;
    PBYTE Buffer;
    PEVENTLOGRECORD pRec;
    PWSTR str;
    UINT i, pos;

    SourceNameSize   = (SourceName   && SourceName->Buffer)   ? SourceName->Length   : 0;
    ComputerNameSize = (ComputerName && ComputerName->Buffer) ? ComputerName->Length : 0;

    RecSize = sizeof(EVENTLOGRECORD) + /* Add the sizes of the strings, NULL-terminated */
        SourceNameSize + ComputerNameSize + 2*sizeof(UNICODE_NULL);

    /* Align on DWORD boundary for the SID */
    RecSize = ROUND_UP(RecSize, sizeof(ULONG));

    RecSize += dwSidLength;

    /* Add the sizes for the strings array */
    ASSERT((pStrings == NULL && wNumStrings == 0) ||
           (pStrings != NULL && wNumStrings >= 0));
    for (i = 0, str = pStrings; i < wNumStrings; i++)
    {
        StringLen = wcslen(str) + 1; // str must be != NULL
        RecSize += StringLen * sizeof(WCHAR);
        str += StringLen;
    }

    /* Add the data size */
    RecSize += dwDataSize;

    /* Align on DWORD boundary for the full structure */
    RecSize = ROUND_UP(RecSize, sizeof(ULONG));

    /* Size of the trailing 'Length' member */
    RecSize += sizeof(ULONG);

    Buffer = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, RecSize);
    if (!Buffer)
    {
        DPRINT1("Cannot allocate heap!\n");
        return NULL;
    }

    pRec = (PEVENTLOGRECORD)Buffer;
    pRec->Length = RecSize;
    pRec->Reserved = LOGFILE_SIGNATURE;

    /*
     * Do not assign here any precomputed record number to the event record.
     * The true record number will be assigned atomically and sequentially in
     * LogfWriteRecord, so that all the event records will have consistent and
     * unique record numbers.
     */
    pRec->RecordNumber = 0;

    /*
     * Set the generated time, and temporarily set the written time
     * with the generated time.
     */
    pRec->TimeGenerated = Time;
    pRec->TimeWritten   = Time;

    pRec->EventID = dwEventId;
    pRec->EventType = wType;
    pRec->EventCategory = wCategory;

    pos = sizeof(EVENTLOGRECORD);

    /* NOTE: Equivalents of RtlStringCbCopyUnicodeString calls */
    if (SourceNameSize)
    {
        StringCbCopyNW((PWSTR)(Buffer + pos), SourceNameSize + sizeof(UNICODE_NULL),
                       SourceName->Buffer, SourceNameSize);
    }
    pos += SourceNameSize + sizeof(UNICODE_NULL);
    if (ComputerNameSize)
    {
        StringCbCopyNW((PWSTR)(Buffer + pos), ComputerNameSize + sizeof(UNICODE_NULL),
                       ComputerName->Buffer, ComputerNameSize);
    }
    pos += ComputerNameSize + sizeof(UNICODE_NULL);

    /* Align on DWORD boundary for the SID */
    pos = ROUND_UP(pos, sizeof(ULONG));

    pRec->UserSidLength = 0;
    pRec->UserSidOffset = 0;
    if (dwSidLength)
    {
        RtlCopyMemory(Buffer + pos, pUserSid, dwSidLength);
        pRec->UserSidLength = dwSidLength;
        pRec->UserSidOffset = pos;
        pos += dwSidLength;
    }

    pRec->StringOffset = pos;
    for (i = 0, str = pStrings; i < wNumStrings; i++)
    {
        StringLen = wcslen(str) + 1; // str must be != NULL
        StringCchCopyW((PWSTR)(Buffer + pos), StringLen, str);
        str += StringLen;
        pos += StringLen * sizeof(WCHAR);
    }
    pRec->NumStrings = wNumStrings;

    pRec->DataLength = 0;
    pRec->DataOffset = 0;
    if (dwDataSize)
    {
        RtlCopyMemory(Buffer + pos, pRawData, dwDataSize);
        pRec->DataLength = dwDataSize;
        pRec->DataOffset = pos;
        pos += dwDataSize;
    }

    /* Align on DWORD boundary for the full structure */
    pos = ROUND_UP(pos, sizeof(ULONG));

    /* Initialize the trailing 'Length' member */
    *((PDWORD)(Buffer + pos)) = RecSize;

    *pRecSize = RecSize;
    return pRec;
}
Example #18
0
NTSTATUS NTAPI
ConDrvWriteConsole(IN PCONSOLE Console,
                   IN PTEXTMODE_SCREEN_BUFFER ScreenBuffer,
                   IN BOOLEAN Unicode,
                   IN PVOID StringBuffer,
                   IN ULONG NumCharsToWrite,
                   OUT PULONG NumCharsWritten OPTIONAL)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PWCHAR Buffer = NULL;
    ULONG Written = 0;
    ULONG Length;

    if (Console == NULL || ScreenBuffer == NULL /* || StringBuffer == NULL */)
        return STATUS_INVALID_PARAMETER;

    /* Validity checks */
    ASSERT(Console == ScreenBuffer->Header.Console);
    ASSERT((StringBuffer != NULL) || (StringBuffer == NULL && NumCharsToWrite == 0));

    /* Stop here if the console is paused */
    if (Console->UnpauseEvent != NULL) return STATUS_PENDING;

    /* Convert the string to UNICODE */
    if (Unicode)
    {
        Buffer = StringBuffer;
    }
    else
    {
        Length = MultiByteToWideChar(Console->OutputCodePage, 0,
                                     (PCHAR)StringBuffer,
                                     NumCharsToWrite,
                                     NULL, 0);
        Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, Length * sizeof(WCHAR));
        if (Buffer)
        {
            MultiByteToWideChar(Console->OutputCodePage, 0,
                                (PCHAR)StringBuffer,
                                NumCharsToWrite,
                                (PWCHAR)Buffer, Length);
        }
        else
        {
            Status = STATUS_NO_MEMORY;
        }
    }

    /* Send it */
    if (Buffer)
    {
        if (NT_SUCCESS(Status))
        {
            Status = TermWriteStream(Console,
                                     ScreenBuffer,
                                     Buffer,
                                     NumCharsToWrite,
                                     TRUE);
            if (NT_SUCCESS(Status))
            {
                Written = NumCharsToWrite;
            }
        }

        if (!Unicode) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
    }

    if (NumCharsWritten) *NumCharsWritten = Written;

    return Status;
}
Example #19
0
static PVOID
RosSymAllocMemUM(ULONG_PTR Size)
{
  return RtlAllocateHeap(RtlGetProcessHeap(), 0, Size);
}
Example #20
0
NTSTATUS NTAPI
ConDrvWriteConsoleOutputString(IN PCONSOLE Console,
                               IN PTEXTMODE_SCREEN_BUFFER Buffer,
                               IN CODE_TYPE CodeType,
                               IN PVOID StringBuffer,
                               IN ULONG NumCodesToWrite,
                               IN PCOORD WriteCoord,
                               // OUT PCOORD EndCoord,
                               OUT PULONG NumCodesWritten OPTIONAL)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PVOID WriteBuffer = NULL;
    PWCHAR tmpString = NULL;
    DWORD X, Y, Length; // , Written = 0;
    ULONG CodeSize;
    PCHAR_INFO Ptr;

    if (Console == NULL || Buffer == NULL || WriteCoord == NULL /* || EndCoord == NULL */)
    {
        return STATUS_INVALID_PARAMETER;
    }

    /* Validity checks */
    ASSERT(Console == Buffer->Header.Console);
    ASSERT((StringBuffer != NULL) || (StringBuffer == NULL && NumCodesToWrite == 0));

    //
    // FIXME: Make overflow checks on WriteCoord !!!!!!
    //

    if (NumCodesWritten) *NumCodesWritten = 0;

    switch (CodeType)
    {
        case CODE_ASCII:
            CodeSize = RTL_FIELD_SIZE(CODE_ELEMENT, AsciiChar);
            break;

        case CODE_UNICODE:
            CodeSize = RTL_FIELD_SIZE(CODE_ELEMENT, UnicodeChar);
            break;

        case CODE_ATTRIBUTE:
            CodeSize = RTL_FIELD_SIZE(CODE_ELEMENT, Attribute);
            break;

        default:
            return STATUS_INVALID_PARAMETER;
    }

    if (CodeType == CODE_ASCII)
    {
        /* Convert the ASCII string into Unicode before writing it to the console */
        Length = MultiByteToWideChar(Console->OutputCodePage, 0,
                                     (PCHAR)StringBuffer,
                                     NumCodesToWrite,
                                     NULL, 0);
        tmpString = WriteBuffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, Length * sizeof(WCHAR));
        if (WriteBuffer)
        {
            MultiByteToWideChar(Console->OutputCodePage, 0,
                                (PCHAR)StringBuffer,
                                NumCodesToWrite,
                                (PWCHAR)WriteBuffer, Length);
        }
        else
        {
            Status = STATUS_NO_MEMORY;
        }

        // FIXME: Quick fix: fix the CodeType and CodeSize since the
        // ASCII string was converted into UNICODE.
        // A proper fix needs to be written.
        CodeType = CODE_UNICODE;
        CodeSize = RTL_FIELD_SIZE(CODE_ELEMENT, UnicodeChar);
    }
    else
    {
        /* For CODE_UNICODE or CODE_ATTRIBUTE, we are already OK */
        WriteBuffer = StringBuffer;
    }

    if (WriteBuffer == NULL || !NT_SUCCESS(Status)) goto Cleanup;

    X = WriteCoord->X;
    Y = (WriteCoord->Y + Buffer->VirtualY) % Buffer->ScreenBufferSize.Y;
    Length = NumCodesToWrite;
    // Ptr = ConioCoordToPointer(Buffer, X, Y); // Doesn't work
    // Ptr = &Buffer->Buffer[X + Y * Buffer->ScreenBufferSize.X]; // May work

    while (Length--)
    {
        // Ptr = ConioCoordToPointer(Buffer, X, Y); // Doesn't work either
        Ptr = &Buffer->Buffer[X + Y * Buffer->ScreenBufferSize.X];

        switch (CodeType)
        {
            case CODE_ASCII:
            case CODE_UNICODE:
                Ptr->Char.UnicodeChar = *(PWCHAR)WriteBuffer;
                break;

            case CODE_ATTRIBUTE:
                Ptr->Attributes = *(PWORD)WriteBuffer;
                break;
        }
        WriteBuffer = (PVOID)((ULONG_PTR)WriteBuffer + CodeSize);
        // ++Ptr;

        // Written++;
        if (++X == Buffer->ScreenBufferSize.X)
        {
            X = 0;

            if (++Y == Buffer->ScreenBufferSize.Y)
            {
                Y = 0;
            }
        }
    }

    if ((PCONSOLE_SCREEN_BUFFER)Buffer == Console->ActiveBuffer)
    {
        SMALL_RECT UpdateRect;
        ConioComputeUpdateRect(Buffer, &UpdateRect, WriteCoord, NumCodesToWrite);
        TermDrawRegion(Console, &UpdateRect);
    }

    // EndCoord->X = X;
    // EndCoord->Y = (Y + Buffer->ScreenBufferSize.Y - Buffer->VirtualY) % Buffer->ScreenBufferSize.Y;

Cleanup:
    if (tmpString) RtlFreeHeap(RtlGetProcessHeap(), 0, tmpString);

    if (NumCodesWritten) *NumCodesWritten = NumCodesToWrite; // Written;
    return Status;
}
Example #21
0
static BOOLEAN
IsAcpiComputer(VOID)
{
   UNICODE_STRING MultiKeyPathU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\MultifunctionAdapter");
   UNICODE_STRING IdentifierU = RTL_CONSTANT_STRING(L"Identifier");
   UNICODE_STRING AcpiBiosIdentifier = RTL_CONSTANT_STRING(L"ACPI BIOS");
   OBJECT_ATTRIBUTES ObjectAttributes;
   PKEY_BASIC_INFORMATION pDeviceInformation = NULL;
   ULONG DeviceInfoLength = sizeof(KEY_BASIC_INFORMATION) + 50 * sizeof(WCHAR);
   PKEY_VALUE_PARTIAL_INFORMATION pValueInformation = NULL;
   ULONG ValueInfoLength = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 50 * sizeof(WCHAR);
   ULONG RequiredSize;
   ULONG IndexDevice = 0;
   UNICODE_STRING DeviceName, ValueName;
   HANDLE hDevicesKey = NULL;
   HANDLE hDeviceKey = NULL;
   NTSTATUS Status;
   BOOLEAN ret = FALSE;

   InitializeObjectAttributes(&ObjectAttributes, &MultiKeyPathU, OBJ_CASE_INSENSITIVE, NULL, NULL);
   Status = NtOpenKey(&hDevicesKey, KEY_ENUMERATE_SUB_KEYS, &ObjectAttributes);
   if (!NT_SUCCESS(Status))
   {
      DPRINT("NtOpenKey() failed with status 0x%08lx\n", Status);
      goto cleanup;
   }

   pDeviceInformation = RtlAllocateHeap(RtlGetProcessHeap(), 0, DeviceInfoLength);
   if (!pDeviceInformation)
   {
      DPRINT("RtlAllocateHeap() failed\n");
      Status = STATUS_NO_MEMORY;
      goto cleanup;
   }

   pValueInformation = RtlAllocateHeap(RtlGetProcessHeap(), 0, ValueInfoLength);
   if (!pDeviceInformation)
   {
      DPRINT("RtlAllocateHeap() failed\n");
      Status = STATUS_NO_MEMORY;
      goto cleanup;
   }

   while (TRUE)
   {
      Status = NtEnumerateKey(hDevicesKey, IndexDevice, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
      if (Status == STATUS_NO_MORE_ENTRIES)
         break;
      else if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
      {
         RtlFreeHeap(RtlGetProcessHeap(), 0, pDeviceInformation);
         DeviceInfoLength = RequiredSize;
         pDeviceInformation = RtlAllocateHeap(RtlGetProcessHeap(), 0, DeviceInfoLength);
         if (!pDeviceInformation)
         {
            DPRINT("RtlAllocateHeap() failed\n");
            Status = STATUS_NO_MEMORY;
            goto cleanup;
         }
         Status = NtEnumerateKey(hDevicesKey, IndexDevice, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
      }
      if (!NT_SUCCESS(Status))
      {
         DPRINT("NtEnumerateKey() failed with status 0x%08lx\n", Status);
         goto cleanup;
      }
      IndexDevice++;

      /* Open device key */
      DeviceName.Length = DeviceName.MaximumLength = pDeviceInformation->NameLength;
      DeviceName.Buffer = pDeviceInformation->Name;
      InitializeObjectAttributes(&ObjectAttributes, &DeviceName, OBJ_CASE_INSENSITIVE, hDevicesKey, NULL);
      Status = NtOpenKey(
         &hDeviceKey,
         KEY_QUERY_VALUE,
         &ObjectAttributes);
      if (!NT_SUCCESS(Status))
      {
         DPRINT("NtOpenKey() failed with status 0x%08lx\n", Status);
         goto cleanup;
      }

      /* Read identifier */
      Status = NtQueryValueKey(hDeviceKey, &IdentifierU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
      if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
      {
         RtlFreeHeap(RtlGetProcessHeap(), 0, pValueInformation);
         ValueInfoLength = RequiredSize;
         pValueInformation = RtlAllocateHeap(RtlGetProcessHeap(), 0, ValueInfoLength);
         if (!pValueInformation)
         {
            DPRINT("RtlAllocateHeap() failed\n");
            Status = STATUS_NO_MEMORY;
            goto cleanup;
         }
         Status = NtQueryValueKey(hDeviceKey, &IdentifierU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
      }
      if (!NT_SUCCESS(Status))
      {
         DPRINT("NtQueryValueKey() failed with status 0x%08lx\n", Status);
         goto nextdevice;
      }
      else if (pValueInformation->Type != REG_SZ)
      {
         DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_SZ);
         goto nextdevice;
      }

      ValueName.Length = ValueName.MaximumLength = pValueInformation->DataLength;
      ValueName.Buffer = (PWCHAR)pValueInformation->Data;
      if (ValueName.Length >= sizeof(WCHAR) && ValueName.Buffer[ValueName.Length / sizeof(WCHAR) - 1] == UNICODE_NULL)
         ValueName.Length -= sizeof(WCHAR);
      if (RtlCompareUnicodeString(&ValueName, &AcpiBiosIdentifier, FALSE) == 0)
      {
         DPRINT("Found ACPI BIOS\n");
         ret = TRUE;
         goto cleanup;
      }

nextdevice:
      NtClose(hDeviceKey);
      hDeviceKey = NULL;
   }

cleanup:
   if (pDeviceInformation)
      RtlFreeHeap(RtlGetProcessHeap(), 0, pDeviceInformation);
   if (pValueInformation)
      RtlFreeHeap(RtlGetProcessHeap(), 0, pValueInformation);
   if (hDevicesKey)
      NtClose(hDevicesKey);
   if (hDeviceKey)
      NtClose(hDeviceKey);
   return ret;
}
Example #22
0
VOID
NtProcessStartup(
    PPEB Peb
    )
{
    int argc;
    char **argv;
    char **envp;
    char **dst;
    char *nullPtr = NULL;
    PCH s, d;
    ULONG n, DebugParameter;
    PULONG BadPointer;
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
    PUNICODE_STRING p;
    ANSI_STRING AnsiString;

    ASSERT( Peb != NULL );
    ProcessParameters = RtlNormalizeProcessParams( Peb->ProcessParameters );

    DebugParameter = 0;
    argc = 0;
    argv = &nullPtr;
    envp = &nullPtr;

    if (ARGUMENT_PRESENT( ProcessParameters )) {
        DebugParameter = ProcessParameters->DebugFlags;

        dst = RtlAllocateHeap( Peb->ProcessHeap, 0, 512 * sizeof( PCH ) );
        argv = dst;
        *dst = NULL;

        //
        // Now extract the arguments from the process command line.
        // using whitespace as separator characters.
        //

        p = &ProcessParameters->CommandLine;
        if (p->Buffer == NULL || p->Length == 0) {
            p = &ProcessParameters->ImagePathName;
            }
        RtlUnicodeStringToAnsiString( &AnsiString, p, TRUE );
        s = AnsiString.Buffer;
        n = AnsiString.Length;
        if (s != NULL) {
            d = RtlAllocateHeap( Peb->ProcessHeap, 0, n+2 );
            while (*s) {
                //
                // Skip over any white space.
                //

                while (*s && *s <= ' ') {
                    s++;
                    }

                //
                // Copy token to next white space separator and null terminate
                //

                if (*s) {
                    *dst++ = d;
                    argc++;
                    while (*s > ' ') {
                        *d++ = *s++;
                        }
                    *d++ = '\0';
                    }
                }
            }
        *dst++ = NULL;

        envp = dst;
        s = ProcessParameters->Environment;
        if (s != NULL) {
            while (*s) {
                *dst++ = s;
                while (*s++) {
                    ;
                    }
                }
            }
        *dst++ = NULL;
        }

    if (DebugParameter != 0) {
        DbgBreakPoint();
        }

    NtTerminateProcess( NtCurrentProcess(),
                        main( argc, argv, envp, DebugParameter )
                      );

    BadPointer = (PULONG)1;
    *BadPointer = 0;
}
Example #23
0
PGENERIC_LIST
CreateDisplayDriverList(HINF InfFile)
{
    CHAR Buffer[128];
    PGENERIC_LIST List;
    INFCONTEXT Context;
    PWCHAR KeyName;
    PWCHAR KeyValue;
    PWCHAR UserData;
    WCHAR DisplayIdentifier[128];
    WCHAR DisplayKey[32];

    /* Get the display identification */
    if (!GetDisplayIdentifier(DisplayIdentifier, 128))
    {
        DisplayIdentifier[0] = 0;
    }

    DPRINT("Display identifier: '%S'\n", DisplayIdentifier);

    /* Search for matching device identifier */
    if (!SetupFindFirstLineW(InfFile, L"Map.Display", NULL, &Context))
    {
        /* FIXME: error message */
        return NULL;
    }

    do
    {
        if (!INF_GetDataField(&Context, 1, &KeyValue))
        {
            /* FIXME: Handle error! */
            DPRINT("INF_GetDataField() failed\n");
            return NULL;
        }

        DPRINT("KeyValue: %S\n", KeyValue);
        if (wcsstr(DisplayIdentifier, KeyValue))
        {
            if (!INF_GetDataField(&Context, 0, &KeyName))
            {
                /* FIXME: Handle error! */
                DPRINT("INF_GetDataField() failed\n");
                return NULL;
            }

            DPRINT("Display key: %S\n", KeyName);
            wcscpy(DisplayKey, KeyName);
        }
    } while (SetupFindNextLine(&Context, &Context));

    List = CreateGenericList();
    if (List == NULL)
        return NULL;

    if (!SetupFindFirstLineW (InfFile, L"Display", NULL, &Context))
    {
        DestroyGenericList(List, FALSE);
        return NULL;
    }

    do
    {
        if (!INF_GetDataField(&Context, 0, &KeyName))
        {
            DPRINT1("INF_GetDataField() failed\n");
            break;
        }

        if (!INF_GetDataField(&Context, 1, &KeyValue))
        {
            DPRINT1("INF_GetDataField() failed\n");
            break;
        }

        UserData = (WCHAR*) RtlAllocateHeap(ProcessHeap,
                                            0,
                                            (wcslen(KeyName) + 1) * sizeof(WCHAR));
        if (UserData == NULL)
        {
            DPRINT1("RtlAllocateHeap() failed\n");
            DestroyGenericList(List, TRUE);
            return NULL;
        }

        wcscpy(UserData, KeyName);

        sprintf(Buffer, "%S", KeyValue);
        AppendGenericListEntry(List,
                               Buffer,
                               UserData,
                               _wcsicmp(KeyName, DisplayKey) ? FALSE : TRUE);
    } while (SetupFindNextLine(&Context, &Context));

#if 0
    AppendGenericListEntry(List, "Other display driver", NULL, TRUE);
#endif

    return List;
}
Example #24
0
NTSTATUS
SampFixBug18471 (
    IN ULONG Revision
    )
/*++

Routine Description:

    This routine fixes bug 18471, that SAM does not adjust the protection
    on groups that are members of administrative aliases in the builtin
    domain. It fixes this by opening a fixed set of known aliases
    (Administrators, Account Operators, Backup Operators, Print Operators,
    and Server Operators), and enumerating their members.  To fix this,
    we will remove all the members of these aliases (except the
    Administrator user account) and re-add them.

Arguments:

    Revision - Revision of the Sam server.

Return Value:


    Note:


--*/
{
    NTSTATUS            Status;
    ULONG               Index, Index2;
    PSID                BuiltinDomainSid = NULL;
    SID_IDENTIFIER_AUTHORITY BuiltinAuthority = SECURITY_NT_AUTHORITY;
    PSID                AccountDomainSid;
    ULONG               AccountDomainIndex = 0xffffffff;
    ULONG               BuiltinDomainIndex = 0xffffffff;
    SAMPR_PSID_ARRAY    AliasMembership;
    ULONG               MemberRid;
    ULONG               SdRevision;
    PSECURITY_DESCRIPTOR OldDescriptor;
    PSECURITY_DESCRIPTOR SecurityDescriptor;
    ULONG               SecurityDescriptorLength;
    SAMP_OBJECT_TYPE    MemberType;
    PSAMP_OBJECT        MemberContext;
    PSAMP_OBJECT        AliasContext;
    SAMP_V1_0A_FIXED_LENGTH_GROUP GroupV1Fixed;
    SAMP_V1_0A_FIXED_LENGTH_USER UserV1Fixed;

    //
    // Check the revision on the server to see if this upgrade has
    // already been performed.
    //


    if (Revision >= SAMP_SERVER_REVISION) {

        //
        // This upgrade has already been performed.
        //

        goto Cleanup;
    }


    //
    // Build a the BuiltIn domain SID.
    //

    BuiltinDomainSid  = RtlAllocateHeap(RtlProcessHeap(), 0,RtlLengthRequiredSid( 1 ));

    if ( BuiltinDomainSid == NULL ) {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto Cleanup;
    }

    RtlInitializeSid( BuiltinDomainSid,   &BuiltinAuthority, 1 );
    *(RtlSubAuthoritySid( BuiltinDomainSid,  0 )) = SECURITY_BUILTIN_DOMAIN_RID;


    //
    // Lookup the index of the account domain
    //

    for (Index = 0;
         Index < SampDefinedDomainsCount ;
         Index++ ) {

        if (RtlEqualSid( BuiltinDomainSid, SampDefinedDomains[Index].Sid)) {
            BuiltinDomainIndex = Index;
        } else {
            AccountDomainIndex = Index;
        }
    }

    ASSERT(AccountDomainIndex < SampDefinedDomainsCount);
    ASSERT(BuiltinDomainIndex < SampDefinedDomainsCount);

    AccountDomainSid = SampDefinedDomains[AccountDomainIndex].Sid;

    //
    // Create out transaction log
    //

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




    //
    // Now loop through and open the aliases we are intersted in
    //

    for (Index = 0;
         Index < ADMINISTRATIVE_ALIAS_COUNT ;
         Index++ )
    {

        SampSetTransactionDomain( BuiltinDomainIndex );

        SampAcquireReadLock();

        Status = SampCreateAccountContext(
                    SampAliasObjectType,
                    AdministrativeRids[Index],
                    TRUE,                       // Trusted client
                    TRUE,                       // Account exists
                    &AliasContext
                    );

        if ( !NT_SUCCESS(Status) ) {

            SampReleaseReadLock();
            if (Status == STATUS_NO_SUCH_ALIAS) {
                Status = STATUS_SUCCESS;
                continue;
            } else {

                goto Cleanup;
            }
        }


        //
        // Get the members in the alias so we can remove and re-add them
        //

        Status = SampRetrieveAliasMembers(
                    AliasContext,
                    &(AliasMembership.Count),
                    (PSID **)&(AliasMembership.Sids)
                    );

        SampDeleteContext(AliasContext);
        SampReleaseReadLock();
        if (!NT_SUCCESS(Status)) {
            break;
        }

        //
        // Write that we are opening this alias to the log.  We don't need
        // to do this for administrators, since for them we the update is
        // idempotent.
        //

        if (AdministrativeRids[Index] != DOMAIN_ALIAS_RID_ADMINS) {
            Status = SampAddAliasTo18471Key(
                        AdministrativeRids[Index]
                        );
            if (!NT_SUCCESS(Status)) {
                break;
            }
        }


        //
        // Loop through the members and split each sid.  For every
        // member in the account domain , remove it and re-add it from
        // this alias.
        //




        for (Index2 = 0; Index2 < AliasMembership.Count ; Index2++ )
        {
            //
            // Check to see if this account is in the account domain
            //

            if ( SampMatchDomainPrefix(
                    (PSID) AliasMembership.Sids[Index2].SidPointer,
                    AccountDomainSid
                    ) )
            {

                //
                // Get the RID for this member
                //

                MemberRid = *RtlSubAuthoritySid(
                                AliasMembership.Sids[Index2].SidPointer,
                                *RtlSubAuthorityCountSid(
                                    AliasMembership.Sids[Index2].SidPointer
                                ) - 1
                                );

                //
                // Now remove and re-add the administratie nature of this
                // membership
                //

                if (AdministrativeRids[Index] == DOMAIN_ALIAS_RID_ADMINS) {

                    Status = SampAcquireWriteLock();
                    if (!NT_SUCCESS(Status)) {
                        break;
                    }

                    SampSetTransactionDomain( AccountDomainIndex );

                    //
                    // Try to create a context for the account as a group.
                    //

                    Status = SampCreateAccountContext(
                                     SampGroupObjectType,
                                     MemberRid,
                                     TRUE, // Trusted client
                                     TRUE, // Account exists
                                     &MemberContext
                                     );

                    if (!NT_SUCCESS( Status ) ) {

                        //
                        // If this ID does not exist as a group, that's fine -
                        // it might be a user or might have been deleted.
                        //

                        SampReleaseWriteLock( FALSE );
                        if (Status == STATUS_NO_SUCH_GROUP) {
                            Status = STATUS_SUCCESS;
                            continue;
                        }
                        break;
                    }

                    //
                    // Now set a flag in the group itself,
                    // so that when users are added and removed
                    // in the future it is known whether this
                    // group is in an ADMIN alias or not.
                    //

                    Status = SampRetrieveGroupV1Fixed(
                                   MemberContext,
                                   &GroupV1Fixed
                                   );

                    if ( NT_SUCCESS(Status)) {

                        GroupV1Fixed.AdminCount = 1;

                        Status = SampReplaceGroupV1Fixed(
                                    MemberContext,
                                    &GroupV1Fixed
                                    );
                        //
                        // Modify the security descriptor to
                        // prevent account operators from adding
                        // anybody to this group
                        //

                        if ( NT_SUCCESS( Status ) ) {

                            Status = SampGetAccessAttribute(
                                        MemberContext,
                                        SAMP_GROUP_SECURITY_DESCRIPTOR,
                                        FALSE, // don't make copy
                                        &SdRevision,
                                        &OldDescriptor
                                        );

                            if (NT_SUCCESS(Status)) {

                                Status = SampModifyAccountSecurity(
                                            SampGroupObjectType,
                                            TRUE, // this is an admin
                                            OldDescriptor,
                                            &SecurityDescriptor,
                                            &SecurityDescriptorLength
                                            );
                            }

                            if ( NT_SUCCESS( Status ) ) {

                                //
                                // Write the new security descriptor into the object
                                //

                                Status = SampSetAccessAttribute(
                                               MemberContext,
                                               SAMP_USER_SECURITY_DESCRIPTOR,
                                               SecurityDescriptor,
                                               SecurityDescriptorLength
                                               );

                                MIDL_user_free( SecurityDescriptor );
                            }



                        }
                        if (NT_SUCCESS(Status)) {

                            //
                            // Add the modified group to the current transaction
                            // Don't use the open key handle since we'll be deleting the context.
                            //

                            Status = SampStoreObjectAttributes(MemberContext, FALSE);

                        }

                    }

                    //
                    // Clean up the group context
                    //

                    SampDeleteContext(MemberContext);

                    //
                    // we don't want the modified count to change
                    //

                    SampTransactionWithinDomain = FALSE;

                    if (NT_SUCCESS(Status)) {
                        Status = SampReleaseWriteLock( TRUE );
                    } else {
                        (VOID) SampReleaseWriteLock( FALSE );
                    }

                }
                else
                {


                    //
                    // Check to see if we've already upgraded this member
                    //

                    Status = SampCheckMemberUpgradedFor18471(
                                AdministrativeRids[Index],
                                MemberRid);

                    if (NT_SUCCESS(Status)) {

                        //
                        // This member already was upgraded.
                        //

                        continue;
                    } else {

                        //
                        // We continue on with the upgrade
                        //

                        Status = STATUS_SUCCESS;
                    }

                    //
                    // Change the operator account for the other
                    // aliases.
                    //

                    if (NT_SUCCESS(Status)) {

                        Status = SampAcquireWriteLock();
                        if (!NT_SUCCESS(Status)) {
                            break;
                        }

                        SampSetTransactionDomain( AccountDomainIndex );

                        Status = SampChangeAccountOperatorAccessToMember(
                                    AliasMembership.Sids[Index2].SidPointer,
                                    NoChange,
                                    AddToAdmin
                                    );

                        //
                        // If that succeeded, add this member to the log
                        // as one that was upgraded.
                        //

                        if (NT_SUCCESS(Status)) {
                            Status = SampAddMemberRidTo18471Key(
                                        AdministrativeRids[Index],
                                        MemberRid
                                        );

                        }

                        //
                        // We don't want the modified count to be updated so
                        // make this not a domain transaction
                        //

                        SampTransactionWithinDomain = FALSE;
                                                if (NT_SUCCESS(Status)) {
                            Status = SampReleaseWriteLock( TRUE );
                        } else {
                            (VOID) SampReleaseWriteLock( FALSE );
                        }

                    }

                    if (!NT_SUCCESS(Status)) {
                        break;
                    }

                }
            }
        }

        SamIFree_SAMPR_PSID_ARRAY(
            &AliasMembership
            );
        AliasMembership.Sids = NULL;


        //
        // If something up above failed or the upgrade was already done,
        // exit now.
        //

        if (!NT_SUCCESS(Status)) {
            break;
        }
    }

Cleanup:

    if (BuiltinDomainSid != NULL) {
        RtlFreeHeap(
            RtlProcessHeap(),
            0,
            BuiltinDomainSid
            );
    }

    if (NT_SUCCESS(Status)) {
        Status = SampCleanup18471();
    }
    return(Status);
}
Example #25
0
PGENERIC_LIST
CreateKeyboardLayoutList(HINF InfFile, WCHAR * DefaultKBLayout)
{
    CHAR Buffer[128];
    PGENERIC_LIST List;
    INFCONTEXT Context;
    PWCHAR KeyName;
    PWCHAR KeyValue;
    PWCHAR UserData;
    const MUI_LAYOUTS * LayoutsList;
    ULONG uIndex = 0;
    BOOL KeyboardLayoutsFound = FALSE;

    /* Get default layout id */
    if (!SetupFindFirstLineW (InfFile, L"NLS", L"DefaultLayout", &Context))
        return NULL;

    if (!INF_GetData (&Context, NULL, &KeyValue))
        return NULL;

    wcscpy(DefaultKBLayout, KeyValue);

    List = CreateGenericList();
    if (List == NULL)
        return NULL;

    LayoutsList = MUIGetLayoutsList();

    do
    {
        if (!SetupFindFirstLineW(InfFile, L"KeyboardLayout", NULL, &Context))
        {
            DestroyGenericList(List, FALSE);
            return NULL;
        }

        do
        {
            if (!INF_GetData (&Context, &KeyName, &KeyValue))
            {
                /* FIXME: Handle error! */
                DPRINT("INF_GetData() failed\n");
                DestroyGenericList(List, FALSE);
                return NULL;
            }

            if (_wcsicmp(LayoutsList[uIndex].LayoutID, KeyName) == 0)
            {
                UserData = (WCHAR*) RtlAllocateHeap(ProcessHeap,
                                                0,
                                                (wcslen(KeyName) + 1) * sizeof(WCHAR));

                if (UserData == NULL)
                {
                    /* FIXME: Handle error! */
                    DPRINT("RtlAllocateHeap() failed\n");
                    DestroyGenericList(List, FALSE);
                    return NULL;
                }

                wcscpy(UserData, KeyName);

                sprintf(Buffer, "%S", KeyValue);
                AppendGenericListEntry(List,
                                       Buffer,
                                       UserData,
                                       _wcsicmp(KeyName, DefaultKBLayout) ? FALSE : TRUE);
                KeyboardLayoutsFound = TRUE;
            }

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

        uIndex++;

    } while (LayoutsList[uIndex].LangID != NULL);

    /* FIXME: Handle this case */
    if (!KeyboardLayoutsFound)
    {
        DPRINT1("No keyboard layouts have been found\n");
        DestroyGenericList(List, FALSE);
        return NULL;
    }

    return List;
}
Example #26
0
File: heap.c Project: awoland/wine
/***********************************************************************
 *           HeapAlloc    (KERNEL32.@)
 */
LPVOID WINAPI HeapAlloc( HANDLE heap, DWORD flags, SIZE_T size )
{
    return RtlAllocateHeap( heap, flags, size );
}
Example #27
0
VOID
NTAPI
BaseInitializeStaticServerData(IN PCSR_SERVER_DLL LoadedServerDll)
{
    NTSTATUS Status;
    BOOLEAN Success;
    WCHAR Buffer[MAX_PATH];
    PWCHAR HeapBuffer;
    UNICODE_STRING SystemRootString;
    UNICODE_STRING UnexpandedSystemRootString = RTL_CONSTANT_STRING(L"%SystemRoot%");
    UNICODE_STRING BaseSrvCSDString;
    UNICODE_STRING BaseSrvWindowsDirectory;
    UNICODE_STRING BaseSrvWindowsSystemDirectory;
    UNICODE_STRING BnoString;
    OBJECT_ATTRIBUTES ObjectAttributes;
    ULONG SessionId;
    HANDLE BaseSrvNamedObjectDirectory;
    HANDLE BaseSrvRestrictedObjectDirectory;
    PACL BnoDacl, BnoRestrictedDacl;
    PSECURITY_DESCRIPTOR BnoSd;
    HANDLE SymHandle;
    UNICODE_STRING DirectoryName, SymlinkName;
    ULONG LuidEnabled;
    RTL_QUERY_REGISTRY_TABLE BaseServerRegistryConfigurationTable[2] =
    {
        {
            NULL,
            RTL_QUERY_REGISTRY_DIRECT,
            L"CSDVersion",
            &BaseSrvCSDString,
            REG_NONE, NULL, 0
        },

        {0}
    };

    /* Initialize the memory */
    BaseSrvHeap = RtlGetProcessHeap();                  // Initialize our own heap.
    BaseSrvSharedHeap = LoadedServerDll->SharedSection; // Get the CSR shared heap.

    /* Get the session ID */
    SessionId = NtCurrentPeb()->SessionId;

    /* Get the Windows directory */
    RtlInitEmptyUnicodeString(&SystemRootString, Buffer, sizeof(Buffer));
    Status = RtlExpandEnvironmentStrings_U(NULL,
                                           &UnexpandedSystemRootString,
                                           &SystemRootString,
                                           NULL);
    ASSERT(NT_SUCCESS(Status));

    /* Create the base directory */
    Buffer[SystemRootString.Length / sizeof(WCHAR)] = UNICODE_NULL;
    Success = RtlCreateUnicodeString(&BaseSrvWindowsDirectory,
                                     SystemRootString.Buffer);
    ASSERT(Success);

    /* Create the system directory */
    wcscat(SystemRootString.Buffer, L"\\System32");
    Success = RtlCreateUnicodeString(&BaseSrvWindowsSystemDirectory,
                                     SystemRootString.Buffer);
    ASSERT(Success);

    /* Create the kernel32 path */
    wcscat(SystemRootString.Buffer, L"\\kernel32.dll");
    Success = RtlCreateUnicodeString(&BaseSrvKernel32DllPath,
                                     SystemRootString.Buffer);
    ASSERT(Success);

    /* FIXME: Check Session ID */
    wcscpy(Buffer, L"\\BaseNamedObjects");
    RtlInitUnicodeString(&BnoString, Buffer);

    /* Allocate the server data */
    BaseStaticServerData = RtlAllocateHeap(BaseSrvSharedHeap,
                                           HEAP_ZERO_MEMORY,
                                           sizeof(BASE_STATIC_SERVER_DATA));
    ASSERT(BaseStaticServerData != NULL);

    /* Process timezone information */
    BaseStaticServerData->TermsrvClientTimeZoneId = TIME_ZONE_ID_INVALID;
    BaseStaticServerData->TermsrvClientTimeZoneChangeNum = 0;
    Status = NtQuerySystemInformation(SystemTimeOfDayInformation,
                                      &BaseStaticServerData->TimeOfDay,
                                      sizeof(BaseStaticServerData->TimeOfDay),
                                      NULL);
    ASSERT(NT_SUCCESS(Status));

    /* Make a shared heap copy of the Windows directory */
    BaseStaticServerData->WindowsDirectory = BaseSrvWindowsDirectory;
    HeapBuffer = RtlAllocateHeap(BaseSrvSharedHeap,
                                 0,
                                 BaseSrvWindowsDirectory.MaximumLength);
    ASSERT(HeapBuffer);
    RtlCopyMemory(HeapBuffer,
                  BaseStaticServerData->WindowsDirectory.Buffer,
                  BaseSrvWindowsDirectory.MaximumLength);
    BaseStaticServerData->WindowsDirectory.Buffer = HeapBuffer;

    /* Make a shared heap copy of the System directory */
    BaseStaticServerData->WindowsSystemDirectory = BaseSrvWindowsSystemDirectory;
    HeapBuffer = RtlAllocateHeap(BaseSrvSharedHeap,
                                 0,
                                 BaseSrvWindowsSystemDirectory.MaximumLength);
    ASSERT(HeapBuffer);
    RtlCopyMemory(HeapBuffer,
                  BaseStaticServerData->WindowsSystemDirectory.Buffer,
                  BaseSrvWindowsSystemDirectory.MaximumLength);
    BaseStaticServerData->WindowsSystemDirectory.Buffer = HeapBuffer;

    /* This string is not used */
    RtlInitEmptyUnicodeString(&BaseStaticServerData->WindowsSys32x86Directory,
                              NULL,
                              0);

    /* Make a shared heap copy of the BNO directory */
    BaseStaticServerData->NamedObjectDirectory = BnoString;
    BaseStaticServerData->NamedObjectDirectory.MaximumLength = BnoString.Length +
                                                               sizeof(UNICODE_NULL);
    HeapBuffer = RtlAllocateHeap(BaseSrvSharedHeap,
                                 0,
                                 BaseStaticServerData->NamedObjectDirectory.MaximumLength);
    ASSERT(HeapBuffer);
    RtlCopyMemory(HeapBuffer,
                  BaseStaticServerData->NamedObjectDirectory.Buffer,
                  BaseStaticServerData->NamedObjectDirectory.MaximumLength);
    BaseStaticServerData->NamedObjectDirectory.Buffer = HeapBuffer;

    /*
     * Confirmed that in Windows, CSDNumber and RCNumber are actually Length
     * and MaximumLength of the CSD String, since the same UNICODE_STRING is
     * being queried twice, the first time as a ULONG!
     *
     * Somehow, in Windows this doesn't cause a buffer overflow, but it might
     * in ReactOS, so this code is disabled until someone figures out WTF.
     */
    BaseStaticServerData->CSDNumber = 0;
    BaseStaticServerData->RCNumber = 0;

    /* Initialize the CSD string and query its value from the registry */
    RtlInitEmptyUnicodeString(&BaseSrvCSDString, Buffer, sizeof(Buffer));
    Status = RtlQueryRegistryValues(RTL_REGISTRY_WINDOWS_NT,
                                    L"",
                                    BaseServerRegistryConfigurationTable,
                                    NULL,
                                    NULL);
    if (NT_SUCCESS(Status))
    {
        /* Copy into the shared buffer */
        wcsncpy(BaseStaticServerData->CSDVersion,
                BaseSrvCSDString.Buffer,
                BaseSrvCSDString.Length / sizeof(WCHAR));
    }
    else
    {
        /* NULL-terminate to indicate nothing is there */
        BaseStaticServerData->CSDVersion[0] = UNICODE_NULL;
    }

    /* Cache the system information */
    Status = NtQuerySystemInformation(SystemBasicInformation,
                                      &BaseStaticServerData->SysInfo,
                                      sizeof(BaseStaticServerData->SysInfo),
                                      NULL);
    ASSERT(NT_SUCCESS(Status));

    /* Setup the ini file mappings */
    Status = BaseSrvInitializeIniFileMappings(BaseStaticServerData);
    ASSERT(NT_SUCCESS(Status));

    /* FIXME: Should query the registry for these */
    BaseStaticServerData->DefaultSeparateVDM = FALSE;
    BaseStaticServerData->IsWowTaskReady = FALSE;

    /* Allocate a security descriptor and create it */
    BnoSd = RtlAllocateHeap(BaseSrvHeap, 0, 1024);
    ASSERT(BnoSd);
    Status = RtlCreateSecurityDescriptor(BnoSd, SECURITY_DESCRIPTOR_REVISION);
    ASSERT(NT_SUCCESS(Status));

    /* Create the BNO and \Restricted DACLs */
    Status = CreateBaseAcls(&BnoDacl, &BnoRestrictedDacl);
    ASSERT(NT_SUCCESS(Status));

    /* Set the BNO DACL as active for now */
    Status = RtlSetDaclSecurityDescriptor(BnoSd, TRUE, BnoDacl, FALSE);
    ASSERT(NT_SUCCESS(Status));

    /* Create the BNO directory */
    RtlInitUnicodeString(&BnoString, L"\\BaseNamedObjects");
    InitializeObjectAttributes(&ObjectAttributes,
                               &BnoString,
                               OBJ_OPENIF | OBJ_PERMANENT | OBJ_CASE_INSENSITIVE,
                               NULL,
                               BnoSd);
    Status = NtCreateDirectoryObject(&BaseSrvNamedObjectDirectory,
                                     DIRECTORY_ALL_ACCESS,
                                     &ObjectAttributes);
    ASSERT(NT_SUCCESS(Status));

    /* Check if we are session 0 */
    if (SessionId == 0)
    {
        /* Mark this as a session 0 directory */
        Status = NtSetInformationObject(BaseSrvNamedObjectDirectory,
                                        ObjectSessionInformation,
                                        NULL,
                                        0);
        ASSERT(NT_SUCCESS(Status));
    }

    /* Check if LUID device maps are enabled */
    Status = NtQueryInformationProcess(NtCurrentProcess(),
                                       ProcessLUIDDeviceMapsEnabled,
                                       &LuidEnabled,
                                       sizeof(LuidEnabled),
                                       NULL);
    ASSERT(NT_SUCCESS(Status));
    BaseStaticServerData->LUIDDeviceMapsEnabled = (BOOLEAN)LuidEnabled;
    if (!BaseStaticServerData->LUIDDeviceMapsEnabled)
    {
        /* Make Global point back to BNO */
        RtlInitUnicodeString(&DirectoryName, L"Global");
        RtlInitUnicodeString(&SymlinkName, L"\\BaseNamedObjects");
        InitializeObjectAttributes(&ObjectAttributes,
                                   &DirectoryName,
                                   OBJ_OPENIF | OBJ_PERMANENT | OBJ_CASE_INSENSITIVE,
                                   BaseSrvNamedObjectDirectory,
                                   BnoSd);
        Status = NtCreateSymbolicLinkObject(&SymHandle,
                                            SYMBOLIC_LINK_ALL_ACCESS,
                                            &ObjectAttributes,
                                            &SymlinkName);
        if ((NT_SUCCESS(Status)) && SessionId == 0) NtClose(SymHandle);

        /* Make local point back to \Sessions\x\BNO */
        RtlInitUnicodeString(&DirectoryName, L"Local");
        ASSERT(SessionId == 0);
        InitializeObjectAttributes(&ObjectAttributes,
                                   &DirectoryName,
                                   OBJ_OPENIF | OBJ_PERMANENT | OBJ_CASE_INSENSITIVE,
                                   BaseSrvNamedObjectDirectory,
                                   BnoSd);
        Status = NtCreateSymbolicLinkObject(&SymHandle,
                                            SYMBOLIC_LINK_ALL_ACCESS,
                                            &ObjectAttributes,
                                            &SymlinkName);
        if ((NT_SUCCESS(Status)) && SessionId == 0) NtClose(SymHandle);

        /* Make Session point back to BNOLINKS */
        RtlInitUnicodeString(&DirectoryName, L"Session");
        RtlInitUnicodeString(&SymlinkName, L"\\Sessions\\BNOLINKS");
        InitializeObjectAttributes(&ObjectAttributes,
                                   &DirectoryName,
                                   OBJ_OPENIF | OBJ_PERMANENT | OBJ_CASE_INSENSITIVE,
                                   BaseSrvNamedObjectDirectory,
                                   BnoSd);
        Status = NtCreateSymbolicLinkObject(&SymHandle,
                                            SYMBOLIC_LINK_ALL_ACCESS,
                                            &ObjectAttributes,
                                            &SymlinkName);
        if ((NT_SUCCESS(Status)) && SessionId == 0) NtClose(SymHandle);

        /* Create the BNO\Restricted directory and set the restricted DACL */
        RtlInitUnicodeString(&DirectoryName, L"Restricted");
        Status = RtlSetDaclSecurityDescriptor(BnoSd, TRUE, BnoRestrictedDacl, FALSE);
        ASSERT(NT_SUCCESS(Status));
        InitializeObjectAttributes(&ObjectAttributes,
                                   &DirectoryName,
                                   OBJ_OPENIF | OBJ_PERMANENT | OBJ_CASE_INSENSITIVE,
                                   BaseSrvNamedObjectDirectory,
                                   BnoSd);
        Status = NtCreateDirectoryObject(&BaseSrvRestrictedObjectDirectory,
                                         DIRECTORY_ALL_ACCESS,
                                         &ObjectAttributes);
        ASSERT(NT_SUCCESS(Status));
    }

    /* Initialize NLS */
    BaseSrvNLSInit(BaseStaticServerData);

    /* Finally, set the pointer */
    LoadedServerDll->SharedSection = BaseStaticServerData;
}
Example #28
0
NTSTATUS
LogfCreate(PLOGFILE* LogFile,
           PCWSTR    LogName,
           PUNICODE_STRING FileName,
           ULONG     MaxSize,
           ULONG     Retention,
           BOOLEAN   Permanent,
           BOOLEAN   Backup)
{
    NTSTATUS Status;
    OBJECT_ATTRIBUTES ObjectAttributes;
    IO_STATUS_BLOCK IoStatusBlock;
    FILE_STANDARD_INFORMATION FileStdInfo;
    PLOGFILE pLogFile;
    SIZE_T LogNameLen;
    BOOLEAN CreateNew;

    pLogFile = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*pLogFile));
    if (!pLogFile)
    {
        DPRINT1("Cannot allocate heap!\n");
        return STATUS_NO_MEMORY;
    }

    LogNameLen = (LogName ? wcslen(LogName) : 0) + 1;
    pLogFile->LogName = RtlAllocateHeap(GetProcessHeap(),
                                        HEAP_ZERO_MEMORY,
                                        LogNameLen * sizeof(WCHAR));
    if (pLogFile->LogName == NULL)
    {
        DPRINT1("Cannot allocate heap\n");
        Status = STATUS_NO_MEMORY;
        goto Quit;
    }

    if (LogName)
        StringCchCopyW(pLogFile->LogName, LogNameLen, LogName);

    InitializeObjectAttributes(&ObjectAttributes,
                               FileName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    DPRINT1("Going to create or open %wZ\n", FileName);
    Status = NtCreateFile(&pLogFile->FileHandle,
                          Backup ? (GENERIC_READ | SYNCHRONIZE)
                                 : (GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE),
                          &ObjectAttributes,
                          &IoStatusBlock,
                          NULL,
                          FILE_ATTRIBUTE_NORMAL,
                          FILE_SHARE_READ,
                          Backup ? FILE_OPEN : FILE_OPEN_IF,
                          FILE_SYNCHRONOUS_IO_NONALERT,
                          NULL,
                          0);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Cannot create file `%wZ' (Status 0x%08lx)\n", FileName, Status);
        goto Quit;
    }

    CreateNew = (IoStatusBlock.Information == FILE_CREATED);
    DPRINT1("%wZ %s successfully\n", FileName, CreateNew ? "created" : "opened");

    /*
     * Retrieve the log file size and check whether the file is not too large;
     * this log format only supports files of theoretical size < 0xFFFFFFFF .
     *
     * As it happens that, on Windows (and ReactOS), retrieving the End-Of-File
     * information using NtQueryInformationFile with the FileEndOfFileInformation
     * class is invalid (who knows why...), use instead the FileStandardInformation
     * class, and the EndOfFile member of the returned FILE_STANDARD_INFORMATION
     * structure will give the desired information.
     */
    Status = NtQueryInformationFile(pLogFile->FileHandle,
                                    &IoStatusBlock,
                                    &FileStdInfo,
                                    sizeof(FileStdInfo),
                                    FileStandardInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("EventLog: NtQueryInformationFile failed (Status 0x%08lx)\n", Status);
        goto Quit;
    }
    if (FileStdInfo.EndOfFile.HighPart != 0)
    {
        DPRINT1("EventLog: Log `%wZ' is too large.\n", FileName);
        Status = STATUS_EVENTLOG_FILE_CORRUPT; // STATUS_FILE_TOO_LARGE;
        goto Quit;
    }

    DPRINT("Initializing LogFile `%S'\n", pLogFile->LogName);

    Status = ElfCreateFile(&pLogFile->LogFile,
                           FileName,
                           FileStdInfo.EndOfFile.LowPart,
                           MaxSize,
                           Retention,
                           CreateNew,
                           Backup,
                           LogfpAlloc,
                           LogfpFree,
                           LogfpSetFileSize,
                           LogfpWriteFile,
                           LogfpReadFile,
                           LogfpFlushFile);
    if (!NT_SUCCESS(Status))
        goto Quit;

    pLogFile->Permanent = Permanent;

    RtlInitializeResource(&pLogFile->Lock);

    LogfListAddItem(pLogFile);

Quit:
    if (!NT_SUCCESS(Status))
    {
        if (pLogFile->FileHandle != NULL)
            NtClose(pLogFile->FileHandle);

        if (pLogFile->LogName)
            RtlFreeHeap(GetProcessHeap(), 0, pLogFile->LogName);

        RtlFreeHeap(GetProcessHeap(), 0, pLogFile);
    }
    else
    {
        *LogFile = pLogFile;
    }

    return Status;
}
Example #29
0
static NTSTATUS
Fat12WriteRootDirectory(IN HANDLE FileHandle,
                        IN PFAT16_BOOT_SECTOR BootSector,
                        IN OUT PFORMAT_CONTEXT Context)
{
    IO_STATUS_BLOCK IoStatusBlock;
    NTSTATUS Status = STATUS_SUCCESS;
    PUCHAR Buffer;
    LARGE_INTEGER FileOffset;
    ULONG FirstRootDirSector;
    ULONG RootDirSectors;
    ULONG Sectors;
    ULONG Size;
    ULONG i;

    DPRINT("BootSector->ReservedSectors = %hu\n", BootSector->ReservedSectors);
    DPRINT("BootSector->FATSectors = %hu\n", BootSector->FATSectors);
    DPRINT("BootSector->SectorsPerCluster = %u\n", BootSector->SectorsPerCluster);

    /* Write cluster */
    RootDirSectors = ((BootSector->RootEntries * 32) +
        (BootSector->BytesPerSector - 1)) / BootSector->BytesPerSector;
    FirstRootDirSector =
        BootSector->ReservedSectors + (BootSector->FATCount * BootSector->FATSectors);

    DPRINT("RootDirSectors = %lu\n", RootDirSectors);
    DPRINT("FirstRootDirSector = %lu\n", FirstRootDirSector);

    /* Allocate buffer for the cluster */
    Buffer = (PUCHAR)RtlAllocateHeap(RtlGetProcessHeap(),
                                     0,
                                     32 * 1024);
    if (Buffer == NULL)
        return STATUS_INSUFFICIENT_RESOURCES;

    /* Zero the buffer */
    memset(Buffer, 0, 32 * 1024);

    Sectors = 32 * 1024 / BootSector->BytesPerSector;
    for (i = 0; i < RootDirSectors; i += Sectors)
    {
        /* Zero some sectors of the root directory */
        FileOffset.QuadPart = (FirstRootDirSector + i) * BootSector->BytesPerSector;

        if ((RootDirSectors - i) <= Sectors)
        {
            Sectors = RootDirSectors - i;
        }

        Size = Sectors * BootSector->BytesPerSector;

        Status = NtWriteFile(FileHandle,
                             NULL,
                             NULL,
                             NULL,
                             &IoStatusBlock,
                             Buffer,
                             Size,
                             &FileOffset,
                             NULL);
        if (!NT_SUCCESS(Status))
        {
            DPRINT("NtWriteFile() failed (Status %lx)\n", Status);
            RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
            return Status;
        }

        UpdateProgress(Context, Sectors);
    }

    /* Free the buffer */
    RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);

    return Status;
}
Example #30
0
static NTSTATUS
LsapCreateDatabaseObjects(VOID)
{
    PLSAP_POLICY_AUDIT_EVENTS_DATA AuditEventsInfo = NULL;
    POLICY_DEFAULT_QUOTA_INFO QuotaInfo;
    POLICY_MODIFICATION_INFO ModificationInfo;
    POLICY_AUDIT_FULL_QUERY_INFO AuditFullInfo = {FALSE, FALSE};
    POLICY_AUDIT_LOG_INFO AuditLogInfo;
    GUID DnsDomainGuid;
    PLSA_DB_OBJECT PolicyObject = NULL;
    PSID AccountDomainSid = NULL;
    PSECURITY_DESCRIPTOR PolicySd = NULL;
    ULONG PolicySdSize = 0;
    ULONG AuditEventsCount;
    ULONG AuditEventsSize;
    ULONG i;
    NTSTATUS Status;

    /* Initialize the default quota limits */
    QuotaInfo.QuotaLimits.PagedPoolLimit = 0x2000000;
    QuotaInfo.QuotaLimits.NonPagedPoolLimit = 0x100000;
    QuotaInfo.QuotaLimits.MinimumWorkingSetSize = 0x10000;
    QuotaInfo.QuotaLimits.MaximumWorkingSetSize = 0xF000000;
    QuotaInfo.QuotaLimits.PagefileLimit = 0;
    QuotaInfo.QuotaLimits.TimeLimit.QuadPart = 0;

    /* Initialize the audit log attribute */
    AuditLogInfo.AuditLogPercentFull = 0;
    AuditLogInfo.MaximumLogSize = 0;			// DWORD
    AuditLogInfo.AuditRetentionPeriod.QuadPart = 0;	// LARGE_INTEGER
    AuditLogInfo.AuditLogFullShutdownInProgress = 0;	// BYTE
    AuditLogInfo.TimeToShutdown.QuadPart = 0;		// LARGE_INTEGER
    AuditLogInfo.NextAuditRecordId = 0;			// DWORD

    /* Initialize the Audit Events attribute */
    AuditEventsCount = AuditCategoryAccountLogon - AuditCategorySystem + 1;
    AuditEventsSize = sizeof(LSAP_POLICY_AUDIT_EVENTS_DATA) + AuditEventsCount * sizeof(DWORD);
    AuditEventsInfo = RtlAllocateHeap(RtlGetProcessHeap(),
                                      HEAP_ZERO_MEMORY,
                                      AuditEventsSize);
    if (AuditEventsInfo == NULL)
        return STATUS_INSUFFICIENT_RESOURCES;

    AuditEventsInfo->AuditingMode = FALSE;
    AuditEventsInfo->MaximumAuditEventCount = AuditEventsCount;
    for (i = 0; i < AuditEventsCount; i++)
        AuditEventsInfo->AuditEvents[i] = 0;

    /* Initialize the DNS Domain GUID attribute */
    memset(&DnsDomainGuid, 0, sizeof(GUID));

    /* Initialize the modification attribute */
    ModificationInfo.ModifiedId.QuadPart = 0;
    NtQuerySystemTime(&ModificationInfo.DatabaseCreationTime);

    /* Create a random domain SID */
    Status = LsapCreateRandomDomainSid(&AccountDomainSid);
    if (!NT_SUCCESS(Status))
        goto done;

    Status = LsapCreatePolicySd(&PolicySd, &PolicySdSize);
    if (!NT_SUCCESS(Status))
        goto done;

    /* Open the 'Policy' object */
    Status = LsapOpenDbObject(NULL,
                              NULL,
                              L"Policy",
                              LsaDbPolicyObject,
                              0,
                              TRUE,
                              &PolicyObject);
    if (!NT_SUCCESS(Status))
        goto done;

    LsapSetObjectAttribute(PolicyObject,
                           L"PolPrDmN",
                           NULL,
                           0);

    LsapSetObjectAttribute(PolicyObject,
                           L"PolPrDmS",
                           NULL,
                           0);

    LsapSetObjectAttribute(PolicyObject,
                           L"PolAcDmN",
                           NULL,
                           0);

    LsapSetObjectAttribute(PolicyObject,
                           L"PolAcDmS",
                           AccountDomainSid,
                           RtlLengthSid(AccountDomainSid));

    /* Set the default quota limits attribute */
    LsapSetObjectAttribute(PolicyObject,
                           L"DefQuota",
                           &QuotaInfo,
                           sizeof(POLICY_DEFAULT_QUOTA_INFO));

    /* Set the modification attribute */
    LsapSetObjectAttribute(PolicyObject,
                           L"PolMod",
                           &ModificationInfo,
                           sizeof(POLICY_MODIFICATION_INFO));

    /* Set the audit full attribute */
    LsapSetObjectAttribute(PolicyObject,
                           L"PolAdtFl",
                           &AuditFullInfo,
                           sizeof(POLICY_AUDIT_FULL_QUERY_INFO));

    /* Set the audit log attribute */
    LsapSetObjectAttribute(PolicyObject,
                           L"PolAdtLg",
                           &AuditLogInfo,
                           sizeof(POLICY_AUDIT_LOG_INFO));

    /* Set the audit events attribute */
    LsapSetObjectAttribute(PolicyObject,
                           L"PolAdtEv",
                           AuditEventsInfo,
                           AuditEventsSize);

    /* Set the DNS Domain Name attribute */
    LsapSetObjectAttribute(PolicyObject,
                           L"PolDnDDN",
                           NULL,
                           0);

    /* Set the DNS Forest Name attribute */
    LsapSetObjectAttribute(PolicyObject,
                           L"PolDnTrN",
                           NULL,
                           0);

    /* Set the DNS Domain GUID attribute */
    LsapSetObjectAttribute(PolicyObject,
                           L"PolDnDmG",
                           &DnsDomainGuid,
                           sizeof(GUID));

    /* Set the Sceurity Descriptor */
    LsapSetObjectAttribute(PolicyObject,
                           L"SecDesc",
                           PolicySd,
                           PolicySdSize);

done:
    if (AuditEventsInfo != NULL)
        RtlFreeHeap(RtlGetProcessHeap(), 0, AuditEventsInfo);

    if (PolicyObject != NULL)
        LsapCloseDbObject(PolicyObject);

    if (AccountDomainSid != NULL)
        RtlFreeSid(AccountDomainSid);

    if (PolicySd != NULL)
        RtlFreeHeap(RtlGetProcessHeap(), 0, PolicySd);

    return Status;
}