Ejemplo n.º 1
0
Archivo: relay.c Proyecto: AndreRH/wine
/***********************************************************************
 *           RELAY16_InitDebugLists
 *
 * Build the relay include/exclude function lists.
 */
void RELAY16_InitDebugLists(void)
{
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING name;
    char buffer[1024];
    HANDLE root, hkey;
    DWORD count;
    WCHAR *str;
    static const WCHAR configW[] = {'S','o','f','t','w','a','r','e','\\',
                                    'W','i','n','e','\\',
                                    'D','e','b','u','g',0};
    static const WCHAR RelayIncludeW[] = {'R','e','l','a','y','I','n','c','l','u','d','e',0};
    static const WCHAR RelayExcludeW[] = {'R','e','l','a','y','E','x','c','l','u','d','e',0};
    static const WCHAR SnoopIncludeW[] = {'S','n','o','o','p','I','n','c','l','u','d','e',0};
    static const WCHAR SnoopExcludeW[] = {'S','n','o','o','p','E','x','c','l','u','d','e',0};

    RtlOpenCurrentUser( KEY_READ, &root );
    attr.Length = sizeof(attr);
    attr.RootDirectory = root;
    attr.ObjectName = &name;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &name, configW );

    /* @@ Wine registry key: HKCU\Software\Wine\Debug */
    if (NtOpenKey( &hkey, KEY_READ, &attr )) hkey = 0;
    NtClose( root );
    if (!hkey) return;

    str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)buffer)->Data;
    RtlInitUnicodeString( &name, RelayIncludeW );
    if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
    {
        debug_relay_includelist = build_list( str );
    }

    RtlInitUnicodeString( &name, RelayExcludeW );
    if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
    {
        debug_relay_excludelist = build_list( str );
    }

    RtlInitUnicodeString( &name, SnoopIncludeW );
    if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
    {
        debug_snoop_includelist = build_list( str );
    }

    RtlInitUnicodeString( &name, SnoopExcludeW );
    if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
    {
        debug_snoop_excludelist = build_list( str );
    }
    NtClose( hkey );
}
Ejemplo n.º 2
0
/***********************************************************************
 *           get_use_dns_option
 */
static BOOL get_use_dns_option(void)
{
    static const WCHAR NetworkW[] = {'S','o','f','t','w','a','r','e','\\',
                                     'W','i','n','e','\\','N','e','t','w','o','r','k',0};
    static const WCHAR UseDNSW[] = {'U','s','e','D','n','s','C','o','m','p','u','t','e','r','N','a','m','e',0};

    char tmp[80];
    HANDLE root, hkey;
    DWORD dummy;
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;
    BOOL ret = TRUE;

    _init_attr( &attr, &nameW );
    RtlOpenCurrentUser( KEY_READ, &root );
    attr.RootDirectory = root;
    RtlInitUnicodeString( &nameW, NetworkW );

    /* @@ Wine registry key: HKCU\Software\Wine\Network */
    if (!NtOpenKey( &hkey, KEY_READ, &attr ))
    {
        RtlInitUnicodeString( &nameW, UseDNSW );
        if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
        {
            WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
            ret = IS_OPTION_TRUE( str[0] );
        }
        NtClose( hkey );
    }
    NtClose( root );
    return ret;
}
Ejemplo n.º 3
0
static BOOL reg_query_value(HKEY hkey, LPCWSTR name, DWORD type, void *data, DWORD count)
{
    UNICODE_STRING nameW;
    char buf[256];
    KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
    NTSTATUS status;

    if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION))
        return FALSE;

    RtlInitUnicodeString(&nameW, name);

    if ((status = NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation,
                                  buf, sizeof(buf), &count)))
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }

    if (info->Type != type)
    {
        SetLastError( ERROR_DATATYPE_MISMATCH );
        return FALSE;
    }

    memcpy(data, info->Data, info->DataLength);
    return TRUE;
}
Ejemplo n.º 4
0
DWORD CliReadRegistryValue(HANDLE hKey, PCWSTR pName)
{
    BYTE ValueBuffer[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 16 * sizeof(UCHAR)];
    PKEY_VALUE_PARTIAL_INFORMATION pKeyValue;
    UNICODE_STRING      ValueName;
    ULONG ResultLength;
    NTSTATUS Status;

    pKeyValue = (PKEY_VALUE_PARTIAL_INFORMATION)ValueBuffer;

    RtlInitUnicodeString(&ValueName, pName);
    Status = NtQueryValueKey(hKey,
                             &ValueName,
                             KeyValuePartialInformation,
                             pKeyValue,
                             sizeof(ValueBuffer),
                             &ResultLength );

    if (NT_SUCCESS(Status) && pKeyValue->DataLength > 3) {
        //
        // In Win95 registry, these items are written as BYTE data...
        //
        return (DWORD)(MAKEWORD( pKeyValue->Data[0], pKeyValue->Data[1])) |
                 (((DWORD)(MAKEWORD( pKeyValue->Data[2], pKeyValue->Data[3]))) << 16);
    }

    return 0;
}
Ejemplo n.º 5
0
/***********************************************************************
 *              GetComputerNameW         (KERNEL32.@)
 */
BOOL WINAPI GetComputerNameW(LPWSTR name,LPDWORD size)
{
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    HANDLE hkey = INVALID_HANDLE_VALUE, hsubkey = INVALID_HANDLE_VALUE;
    char buf[offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data ) + (MAX_COMPUTERNAME_LENGTH + 1) * sizeof( WCHAR )];
    DWORD len = sizeof( buf );
    LPWSTR theName = (LPWSTR) (buf + offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data ));
    NTSTATUS st = STATUS_INVALID_PARAMETER;

    TRACE ("%p %p\n", name, size);

    _init_attr ( &attr, &nameW );
    RtlInitUnicodeString( &nameW, ComputerW );
    if ( ( st = NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) ) != STATUS_SUCCESS )
        goto out;

    attr.RootDirectory = hkey;
    RtlInitUnicodeString( &nameW, ActiveComputerNameW );
    if ( ( st = NtOpenKey( &hsubkey, KEY_ALL_ACCESS, &attr ) ) != STATUS_SUCCESS )
        goto out;

    RtlInitUnicodeString( &nameW, ComputerNameW );
    if ( ( st = NtQueryValueKey( hsubkey, &nameW, KeyValuePartialInformation, buf, len, &len ) )
            != STATUS_SUCCESS )
        goto out;

    len = (len -offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof (WCHAR) - 1;
    TRACE ("ComputerName is %s (length %u)\n", debugstr_w ( theName ), len);

    if ( *size < len + 1 )
    {
        *size = len + 1;
        st = STATUS_MORE_ENTRIES;
    }
    else
    {
        memcpy ( name, theName, len * sizeof (WCHAR) );
        name[len] = 0;
        *size = len;
        st = STATUS_SUCCESS;
    }

out:
    NtClose ( hsubkey );
    NtClose ( hkey );

    if ( st == STATUS_SUCCESS )
        return TRUE;
    else
    {
        SetLastError ( RtlNtStatusToDosError ( st ) );
        WARN ( "Status %u reading computer name from registry\n", st );
        return FALSE;
    }
}
Ejemplo n.º 6
0
/***************************************************************************
 *	get_registry_value
 *
 * Load the registry loadorder value for a given module.
 */
static enum loadorder get_registry_value( HANDLE hkey, const WCHAR *module )
{
    UNICODE_STRING valueW;
    char buffer[80];
    DWORD count;

    RtlInitUnicodeString( &valueW, module );

    if (!NtQueryValueKey( hkey, &valueW, KeyValuePartialInformation,
                                 buffer, sizeof(buffer), &count ))
    {
        WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)buffer)->Data;
        return parse_load_order( str );
    }
    return LO_INVALID;
}
Ejemplo n.º 7
0
static BOOL reg_query_value(HKEY hkey, LPCWSTR name, DWORD type, void *data, DWORD count)
{
    UNICODE_STRING nameW;
    char buf[256];
    KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;

    if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION))
        return FALSE;

    RtlInitUnicodeString(&nameW, name);

    if (NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation,
                        buf, sizeof(buf), &count))
        return FALSE;

    if (info->Type != type) return FALSE;

    memcpy(data, info->Data, info->DataLength);
    return TRUE;
}
Ejemplo n.º 8
0
VOID
RegReadApcProcedure(
    PVOID RegReadApcContext,
    PIO_STATUS_BLOCK IoStatus
    )
{
    UNICODE_STRING ValueString;
    LONG Status;
    BYTE Buf[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(DWORD)];
    DWORD cbSize;
    ULONG l;

    RtlInitUnicodeString(&ValueString, L"Win32PrioritySeparation");
    Status = NtQueryValueKey(hKeyPriority,
            &ValueString,
            KeyValuePartialInformation,
            (PKEY_VALUE_PARTIAL_INFORMATION)Buf,
            sizeof(Buf),
            &cbSize);
    if (NT_SUCCESS(Status)) {
        l = *((PDWORD)((PKEY_VALUE_PARTIAL_INFORMATION)Buf)->Data);
    } else
        l = 1;  // last resort default

    if ( l <= 2 ) {
        CsrSetForegroundPriority((PCSR_PROCESS)(l));
    }

    NtNotifyChangeKey(
        hKeyPriority,
        NULL,
        (PIO_APC_ROUTINE)RegReadApcProcedure,
        NULL,
        &IoStatusRegChange,
        REG_NOTIFY_CHANGE_LAST_SET,
        FALSE,
        &RegChangeBuffer,
        sizeof(RegChangeBuffer),
        TRUE
        );
}
Ejemplo n.º 9
0
UINT GetRegIntFromID(
    HKEY hKey,
    int KeyID,
    UINT nDefault)
{
    LPWSTR lpszValue;
    BOOL fAllocated;
    UNICODE_STRING Value;
    DWORD cbSize;
    BYTE Buf[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 20 * sizeof(WCHAR)];
    NTSTATUS Status;
    UINT ReturnValue;

    lpszValue = (LPWSTR)RtlLoadStringOrError(hModuleWin,
            KeyID, NULL, &fAllocated, FALSE);

    RtlInitUnicodeString(&Value, lpszValue);
    Status = NtQueryValueKey(hKey,
            &Value,
            KeyValuePartialInformation,
            (PKEY_VALUE_PARTIAL_INFORMATION)Buf,
            sizeof(Buf),
            &cbSize);
    if (NT_SUCCESS(Status)) {

        /*
         * Convert string to int.
         */
        RtlInitUnicodeString(&Value, (LPWSTR)((PKEY_VALUE_PARTIAL_INFORMATION)Buf)->Data);
        RtlUnicodeStringToInteger(&Value, 10, &ReturnValue);
    } else {
        ReturnValue = nDefault;
    }

    LocalFree(lpszValue);

    return(ReturnValue);
}
Ejemplo n.º 10
0
VOID
InstallDevice(
    IN HINF hInf,
    IN HANDLE hEnum,
    IN HANDLE hServices,
    IN LPCWSTR DeviceId)
{
    UNICODE_STRING HardwareIDU = RTL_CONSTANT_STRING(L"HardwareID");
    UNICODE_STRING CompatibleIDsU = RTL_CONSTANT_STRING(L"CompatibleIDs");
    UNICODE_STRING DeviceIdU;
    OBJECT_ATTRIBUTES ObjectAttributes;
    LPCWSTR HardwareID;
    PKEY_VALUE_PARTIAL_INFORMATION pPartialInformation = NULL;
    HANDLE hDeviceKey;
    ULONG ulRequired;
    BOOLEAN bDriverInstalled = FALSE;
    NTSTATUS Status;

    RtlInitUnicodeString(&DeviceIdU, DeviceId);
    InitializeObjectAttributes(&ObjectAttributes, &DeviceIdU, 0, hEnum, NULL);
    Status = NtOpenKey(&hDeviceKey, KEY_QUERY_VALUE | KEY_SET_VALUE, &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("Unable to open subkey '%S'\n", DeviceId);
        return;
    }

    Status = NtQueryValueKey(
        hDeviceKey,
        &HardwareIDU,
        KeyValuePartialInformation,
        NULL,
        0,
        &ulRequired);
    if (Status == STATUS_BUFFER_TOO_SMALL)
    {
        pPartialInformation = (PKEY_VALUE_PARTIAL_INFORMATION)RtlAllocateHeap(ProcessHeap, 0, ulRequired);
        if (!pPartialInformation)
        {
            DPRINT1("RtlAllocateHeap() failed\n");
            NtClose(hDeviceKey);
            return;
        }
        Status = NtQueryValueKey(
            hDeviceKey,
            &HardwareIDU,
            KeyValuePartialInformation,
            pPartialInformation,
            ulRequired,
            &ulRequired);
    }
    if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
    {
        /* Nothing to do */
    }
    else if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtQueryValueKey() failed with status 0x%08x\n", Status);
        if (pPartialInformation)
            RtlFreeHeap(ProcessHeap, 0, pPartialInformation);
        NtClose(hDeviceKey);
        return;
    }
    else if (pPartialInformation)
    {
        for (HardwareID = (LPCWSTR)pPartialInformation->Data;
             (PUCHAR)HardwareID < pPartialInformation->Data + pPartialInformation->DataLength
                 && *HardwareID
                 && !bDriverInstalled;
            HardwareID += wcslen(HardwareID) + 1)
        {
            bDriverInstalled = InstallDriver(hInf, hServices,hDeviceKey, DeviceId, HardwareID);
        }
    }

    if (!bDriverInstalled)
    {
        if (pPartialInformation)
        {
            RtlFreeHeap(ProcessHeap, 0, pPartialInformation);
            pPartialInformation = NULL;
        }
        Status = NtQueryValueKey(
            hDeviceKey,
            &CompatibleIDsU,
            KeyValuePartialInformation,
            NULL,
            0,
            &ulRequired);
        if (Status == STATUS_BUFFER_TOO_SMALL)
        {
            pPartialInformation = (PKEY_VALUE_PARTIAL_INFORMATION)RtlAllocateHeap(ProcessHeap, 0, ulRequired);
            if (!pPartialInformation)
            {
                DPRINT("RtlAllocateHeap() failed\n");
                NtClose(hDeviceKey);
                return;
            }
            Status = NtQueryValueKey(
                hDeviceKey,
                &CompatibleIDsU,
                KeyValuePartialInformation,
                pPartialInformation,
                ulRequired,
                &ulRequired);
        }
        if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
        {
            /* Nothing to do */
        }
        else if (!NT_SUCCESS(Status))
        {
            if (pPartialInformation)
                RtlFreeHeap(ProcessHeap, 0, pPartialInformation);
            NtClose(hDeviceKey);
            DPRINT1("NtQueryValueKey() failed with status 0x%08x\n", Status);
            return;
        }
        else if (pPartialInformation)
        {
            for (HardwareID = (LPCWSTR)pPartialInformation->Data;
                 (PUCHAR)HardwareID < pPartialInformation->Data + pPartialInformation->DataLength
                     && *HardwareID
                     && !bDriverInstalled;
                HardwareID += wcslen(HardwareID) + 1)
            {
                bDriverInstalled = InstallDriver(hInf, hServices,hDeviceKey, DeviceId, HardwareID);
            }
        }
    }
    if (!bDriverInstalled)
        DPRINT("No driver available for %S\n", DeviceId);

    RtlFreeHeap(ProcessHeap, 0, pPartialInformation);
    NtClose(hDeviceKey);
}
Ejemplo n.º 11
0
VOID
DoTest(
    HANDLE  RootKey
    )
{
    NTSTATUS rc;
    STRING String1;
    UCHAR Value1[] = "This string is value 1.";
    UCHAR Value2[] = "Value 2 is represented by this string.";
    HANDLE Handle1;
    HANDLE Handle2;
    ULONG ValueLength;
    ULONG Type;
    LARGE_INTEGER Time;

    //
    // Create parent node
    //

    DbgPrint("Part1\n");
    RtlInitString(&String1,  "Test1");
    rc = NtCreateKey(
	RootKey,
	&String1,
	0,
	NULL,
	GENERIC_READ|GENERIC_WRITE,
	&Handle1
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("1:CreateKey failed rc  = %08lx", rc);
	return;
    }

    //
    // Set data into parent
    //

    DbgPrint("Part2\n");
    rc = NtSetValueKey(
	Handle1,
	1,		// type
	Value1,
	strlen(Value1)
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("2:SetValueKey failed rc  = %08lx", rc);
	return;
    }

    //
    // Query and compare data from parent
    //

    DbgPrint("Part2b\n");
    ValueLength = MAX_VALUE;
    rc = NtQueryValueKey(
	Handle1,
	&Type,
	ValueBuffer,
	&ValueLength,
	&Time
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("2b:QueryValueKey failed rc  = %08lx", rc);
	return;
    }

    if (ValueLength != (ULONG)strlen(Value1)) {
	DbgPrint("2b1:Wrong value length\n");
	return;
    } else if (RtlCompareMemory(
		ValueBuffer, Value1, ValueLength) != ValueLength) {
	DbgPrint("2b2:Wrong value\n");
	return;
    } else if (Type != 1) {
	DbgPrint("2b3:Wrong type\n");
	return;
    }


    //
    // Close parent
    //

    DbgPrint("Part3\n");
    NtCloseKey(Handle1);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("3:CloseKey failed rc  = %08lx", rc);
	return;
    }


    //
    // Reopen parent
    //

    DbgPrint("Part4\n");
    rc = NtOpenKey(
	RootKey,
	&String1,
	0,
	GENERIC_READ|GENERIC_WRITE,
	&Handle1
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("4:OpenKey failed rc  = %08lx", rc);
	return;
    }

    //
    // Create child
    //

    DbgPrint("Part5\n");
    RtlInitString(&String1,  "Test2");
    rc = NtCreateKey(
	Handle1,
	&String1,
	0,
	NULL,
	GENERIC_READ|GENERIC_WRITE,
	&Handle2
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("5:CreateKey failed rc  = %08lx", rc);
	return;
    }


    //
    // Set data into child
    //

    DbgPrint("Part6\n");
    rc = NtSetValueKey(
	Handle2,
	2,		// type
	Value2,
	strlen(Value2)
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("6:SetValueKey failed rc  = %08lx", rc);
	return;
    }


    //
    // Query and compare data from child
    //

    DbgPrint("Part7\n");
    ValueLength = MAX_VALUE;
    rc = NtQueryValueKey(
	Handle2,
	&Type,
	ValueBuffer,
	&ValueLength,
	&Time
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("7:QueryValueKey failed rc  = %08lx", rc);
	return;
    }

    if (ValueLength != (ULONG)strlen(Value2)) {
	DbgPrint("7.1:Wrong value length\n");
	return;
    } else if (RtlCompareMemory(
		ValueBuffer, Value2, ValueLength) != ValueLength) {
	DbgPrint("7.2:Wrong value\n");
	return;
    } else if (Type != 2) {
	DbgPrint("7.3:Wrong type\n");
	return;
    }


    //
    // Query and compare data from parent again
    //

    DbgPrint("Part8\n");
    ValueLength = MAX_VALUE;
    rc = NtQueryValueKey(
	Handle1,
	&Type,
	ValueBuffer,
	&ValueLength,
	&Time
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("8:QueryValueKey failed rc  = %08lx", rc);
	return;
    }

    if (ValueLength != (ULONG)strlen(Value1)) {
	DbgPrint("8.1:Wrong value length\n");
	return;
    } else if (RtlCompareMemory(
		ValueBuffer, Value1, ValueLength) != ValueLength) {
	DbgPrint("8.2:Wrong value\n");
	return;
    } else if (Type != 1) {
	DbgPrint("8.3:Wrong type\n");
	return;
    }


    //
    // Reset parent data
    //

    DbgPrint("Part9\n");
    rc = NtSetValueKey(
	Handle1,
	1,		// type
	Value2,
	strlen(Value2)
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("9:SetValueKey failed rc  = %08lx", rc);
	return;
    }


    //
    // Query and compare reset data
    //

    DbgPrint("Part10\n");
    ValueLength = MAX_VALUE;
    rc = NtQueryValueKey(
	Handle1,
	&Type,
	ValueBuffer,
	&ValueLength,
	&Time
	);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("10:QueryValueKey failed rc  = %08lx", rc);
	return;
    }

    if (ValueLength != (ULONG)strlen(Value2)) {
	DbgPrint("10.1:Wrong value length\n");
	return;
    } else if (RtlCompareMemory(
		ValueBuffer, Value2, ValueLength) != ValueLength) {
	DbgPrint("10.2:Wrong value\n");
	return;
    } else if (Type != 1) {
	DbgPrint("10.3:Wrong type\n");
	return;
    }

    //
    // Close off handles and return
    //

    DbgPrint("Part11\n");
    rc = NtCloseKey(Handle1);

    if (!NT_SUCCESS(rc)) {
	DbgPrint("11:CloseKey failed rc  = %08lx", rc);
	return;
    }

    DbgPrint("Part12\n");
    rc = NtCloseKey(Handle2);
    if (!NT_SUCCESS(rc)) {
	DbgPrint("12:CloseKey failed rc  = %08lx", rc);
	return;
    }

    return;
}
Ejemplo n.º 12
0
Archivo: init.c Proyecto: GYGit/reactos
/*++
 * @name GetDosDevicesProtection
 *
 * The GetDosDevicesProtection creates a security descriptor for the DOS Devices
 * Object Directory.
 *
 * @param DosDevicesSd
 *        Pointer to the Security Descriptor to return.
 *
 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
 *
 * @remarks Depending on the DOS Devices Protection Mode (set in the registry),
 *          regular users may or may not have full access to the directory.
 *
 *--*/
NTSTATUS
NTAPI
GetDosDevicesProtection(OUT PSECURITY_DESCRIPTOR DosDevicesSd)
{
    SID_IDENTIFIER_AUTHORITY WorldAuthority = {SECURITY_WORLD_SID_AUTHORITY};
    SID_IDENTIFIER_AUTHORITY CreatorAuthority = {SECURITY_CREATOR_SID_AUTHORITY};
    SID_IDENTIFIER_AUTHORITY NtSidAuthority = {SECURITY_NT_AUTHORITY};
    PSID WorldSid, CreatorSid, AdminSid, SystemSid;
    UCHAR KeyValueBuffer[0x40];
    PKEY_VALUE_PARTIAL_INFORMATION KeyValuePartialInfo;
    UNICODE_STRING KeyName;
    ULONG ProtectionMode = 0;
    OBJECT_ATTRIBUTES ObjectAttributes;
    PACL Dacl;
    PACCESS_ALLOWED_ACE Ace;
    HANDLE hKey;
    NTSTATUS Status;
    ULONG ResultLength, SidLength, AclLength;

    /* Create the SD */
    Status = RtlCreateSecurityDescriptor(DosDevicesSd, SECURITY_DESCRIPTOR_REVISION);
    ASSERT(NT_SUCCESS(Status));

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

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

    /* Initialize the Admin SID */
    Status = RtlAllocateAndInitializeSid(&NtSidAuthority, 2,
                                         SECURITY_BUILTIN_DOMAIN_RID,
                                         DOMAIN_ALIAS_RID_ADMINS,
                                         0, 0, 0, 0, 0, 0,
                                         &AdminSid);
    ASSERT(NT_SUCCESS(Status));

    /* Initialize the Creator SID */
    Status = RtlAllocateAndInitializeSid(&CreatorAuthority, 1,
                                         SECURITY_CREATOR_OWNER_RID,
                                         0, 0, 0, 0, 0, 0, 0,
                                         &CreatorSid);
    ASSERT(NT_SUCCESS(Status));

    /* 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);
    }

    /* Check the Protection Mode */
    if (ProtectionMode & 3)
    {
        /* Calculate SID Lengths */
        SidLength = RtlLengthSid(CreatorSid) + RtlLengthSid(SystemSid) +
                    RtlLengthSid(AdminSid);
        AclLength = sizeof(ACL) + 3 * sizeof(ACCESS_ALLOWED_ACE) + SidLength;

        /* Allocate memory for the DACL */
        Dacl = RtlAllocateHeap(CsrHeap, HEAP_ZERO_MEMORY, AclLength);
        ASSERT(Dacl != NULL);

        /* Build the ACL and add 3 ACEs */
        Status = RtlCreateAcl(Dacl, AclLength, ACL_REVISION2);
        ASSERT(NT_SUCCESS(Status));
        Status = RtlAddAccessAllowedAce(Dacl, ACL_REVISION, GENERIC_ALL, SystemSid);
        ASSERT(NT_SUCCESS(Status));
        Status = RtlAddAccessAllowedAce(Dacl, ACL_REVISION, GENERIC_ALL, AdminSid);
        ASSERT(NT_SUCCESS(Status));
        Status = RtlAddAccessAllowedAce(Dacl, ACL_REVISION, GENERIC_ALL, CreatorSid);
        ASSERT(NT_SUCCESS(Status));

        /* Edit the ACEs to make them inheritable */
        Status = RtlGetAce(Dacl, 0, (PVOID*)&Ace);
        ASSERT(NT_SUCCESS(Status));
        Ace->Header.AceFlags |= OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE;
        Status = RtlGetAce(Dacl, 1, (PVOID*)&Ace);
        ASSERT(NT_SUCCESS(Status));
        Ace->Header.AceFlags |= OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE;
        Status = RtlGetAce(Dacl, 2, (PVOID*)&Ace);
        ASSERT(NT_SUCCESS(Status));
        Ace->Header.AceFlags |= OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;

        /* Set this DACL with the SD */
        Status = RtlSetDaclSecurityDescriptor(DosDevicesSd, TRUE, Dacl, FALSE);
        ASSERT(NT_SUCCESS(Status));
        goto Quickie;
    }
    else
    {
        /* Calculate SID Lengths */
        SidLength = RtlLengthSid(WorldSid) + RtlLengthSid(SystemSid);
        AclLength = sizeof(ACL) + 3 * sizeof(ACCESS_ALLOWED_ACE) + SidLength;

        /* Allocate memory for the DACL */
        Dacl = RtlAllocateHeap(CsrHeap, HEAP_ZERO_MEMORY, AclLength);
        ASSERT(Dacl != NULL);

        /* Build the ACL and add 3 ACEs */
        Status = RtlCreateAcl(Dacl, AclLength, ACL_REVISION2);
        ASSERT(NT_SUCCESS(Status));
        Status = RtlAddAccessAllowedAce(Dacl, ACL_REVISION, GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE, WorldSid);
        ASSERT(NT_SUCCESS(Status));
        Status = RtlAddAccessAllowedAce(Dacl, ACL_REVISION, GENERIC_ALL, SystemSid);
        ASSERT(NT_SUCCESS(Status));
        Status = RtlAddAccessAllowedAce(Dacl, ACL_REVISION, GENERIC_ALL, WorldSid);
        ASSERT(NT_SUCCESS(Status));

        /* Edit the last ACE to make it inheritable */
        Status = RtlGetAce(Dacl, 2, (PVOID*)&Ace);
        ASSERT(NT_SUCCESS(Status));
        Ace->Header.AceFlags |= OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;

        /* Set this DACL with the SD */
        Status = RtlSetDaclSecurityDescriptor(DosDevicesSd, TRUE, Dacl, FALSE);
        ASSERT(NT_SUCCESS(Status));
        goto Quickie;
    }

/* FIXME: failure cases! Fail: */
    /* Free the memory */
    RtlFreeHeap(CsrHeap, 0, Dacl);

/* FIXME: semi-failure cases! Quickie: */
Quickie:
    /* Free the SIDs */
    RtlFreeSid(CreatorSid);
    RtlFreeSid(AdminSid);
    RtlFreeSid(WorldSid);
    RtlFreeSid(SystemSid);

    /* Return */
    return Status;
}
Ejemplo n.º 13
0
void
_CRTAPI1 main(int, char *)
{
    NTSTATUS status;
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING  KeyName;
    UNICODE_STRING  KeyName2;
    UNICODE_STRING  ClassName;
    UNICODE_STRING  ClassName2;
    UNICODE_STRING  ValueName;
    UNICODE_STRING  ValueName2;
    HANDLE          BaseHandle;
    HANDLE          Testhand1;
    ULONG           Disposition;
    LARGE_INTEGER   CompTime;
    ULONG           buffer[100];
    ULONG           bufsize = sizeof(ULONG) * 100;
    PKEY_NODE_INFORMATION NodeInformation;
    PKEY_VALUE_FULL_INFORMATION KeyValueInformation;
    PKEY_VALUE_BASIC_INFORMATION KeyValueBasic;
    ULONG           ResultLength;
    PUCHAR          datastring = "Some simple ascii data for use as a value";
    PUCHAR          datastring2 = "Some more not so simple data $#";
    ULONG           expected;
    PVOID           tp;


    printf("rtmisc1: starting\n");

    NodeInformation = (PKEY_NODE_INFORMATION)&(buffer[0]);
    KeyValueInformation = (PKEY_VALUE_FULL_INFORMATION)&(buffer[0]);
    KeyValueBasic = (PKEY_VALUE_BASIC_INFORMATION)&(buffer[0]);

    //
    // t0: Perform all operations against a base node, open it here.
    //

    RtlInitUnicodeString(
        &KeyName,
        L"\\REGISTRY\\MACHINE\\TEST"
        );

    InitializeObjectAttributes(
        &ObjectAttributes,
        &KeyName,
        0,
        (HANDLE)NULL,
        NULL
        );
    ObjectAttributes.Attributes |= OBJ_CASE_INSENSITIVE;

    status = NtOpenKey(
                &BaseHandle,
                MAXIMUM_ALLOWED,
                &ObjectAttributes
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t0: %08lx\n", status);
        goto punt;
    }


    //
    // t1: Create a key with class and title index
    //

    RtlInitUnicodeString(
        &ClassName,
        L"t1 Class Name"
        );

    RtlInitUnicodeString(
        &KeyName,
        L"first_test_node"
        );

    InitializeObjectAttributes(
        &ObjectAttributes,
        &KeyName,
        0,
        BaseHandle,
        NULL
        );
    ObjectAttributes.Attributes |= OBJ_CASE_INSENSITIVE;

    NtQuerySystemTime(&CompTime);

//  printf("ClassName@%08lx  KeyName@%08lx\n",
//          ClassName.Buffer, KeyName.Buffer);

    status = NtCreateKey(
                &Testhand1,
                MAXIMUM_ALLOWED,
                &ObjectAttributes,
                TITLE_INDEX_1,
                &ClassName,
                0,
                &Disposition
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t1: %08lx\n", status);
        goto punt;
    }

    if (Disposition != REG_CREATED_NEW_KEY) {
        printf("rtmisc1: t1a: got old key, expected to create new one\n");
        failure++;
    }

    //
    // t2: See if we can get data back, and if it makes sense
    //

    RtlZeroMemory(NodeInformation, bufsize);
    status = NtQueryKey(
                Testhand1,
                KeyNodeInformation,
                NodeInformation,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t2a: %08lx\n", status);
        goto punt;
    }
    if (ResultLength != 80) {
        printf("rtmisc1: t2i: expect 80, ResultLength = %d\n", ResultLength);
        failure++;
    }


    NameClassAndTitle(
        NodeInformation,
        ClassName,
        TITLE_INDEX_1,
        KeyName,
        CompTime,
        FALSE,          // time must be >= CompTime
        "rtmisc1: t2b: "
        );
    CompTime = NodeInformation->LastWriteTime;

    status = NtClose(Testhand1);
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t2c: %08lx\n");
        goto punt;
    }


    //
    // t3: Reopen the key with create, see if data still there.
    //

    status = NtCreateKey(
                &Testhand1,
                MAXIMUM_ALLOWED,
                &ObjectAttributes,
                TITLE_INDEX_1,
                &ClassName,
                0,
                &Disposition
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t3: %08lx\n", status);
        goto punt;
    }

    if (Disposition != REG_OPENED_EXISTING_KEY) {
        printf("rtmisc1: t3a failure\n");
        failure++;
    }

    RtlZeroMemory(NodeInformation, bufsize);
    status = NtQueryKey(
                Testhand1,
                KeyNodeInformation,
                NodeInformation,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t3b: %08lx\n", status);
        goto punt;
    }

    NameClassAndTitle(
        NodeInformation,
        ClassName,
        TITLE_INDEX_1,
        KeyName,
        CompTime,
        FALSE,          // time must be >= CompTime
        "rtmisc1: t3c: "
        );

    status = NtClose(Testhand1);
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t3d: %08lx\n");
        goto punt;
    }


    //
    // t4: Reopen the key with open, see if data still there.
    //

    status = NtOpenKey(
                &Testhand1,
                MAXIMUM_ALLOWED,
                &ObjectAttributes
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t4: %08lx\n", status);
        goto punt;
    }

    RtlZeroMemory(NodeInformation, bufsize);
    status = NtQueryKey(
                Testhand1,
                KeyNodeInformation,
                NodeInformation,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t4a: %08lx\n", status);
        goto punt;
    }

    NameClassAndTitle(
        NodeInformation,
        ClassName,
        TITLE_INDEX_1,
        KeyName,
        CompTime,
        FALSE,          // time must be >= CompTime
        "rtmisc1: t4b: "
        );

//  status = NtClose(Testhand1);
//  if (!NT_SUCCESS(status)) {
//      printf("rtmisc1: t4c: %08lx\n");
//      exit(1);
//  }


    //
    // t5: Create a value
    //

    RtlInitUnicodeString(
        &ValueName,
        L"the very first value stored in the registry"
        );


    status = NtSetValueKey(
                Testhand1,
                &ValueName,
                TITLE_INDEX_2,
                TYPE_1,
                datastring,
                strlen(datastring)+1
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t5: %08lx\n", status);
        failure++;
    }


    //
    // t6: Read the value back
    //

    RtlZeroMemory(KeyValueInformation, bufsize);
    status = NtQueryValueKey(
                Testhand1,
                &ValueName,
                KeyValueFullInformation,
                KeyValueInformation,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t6: %08lx\n", status);
        goto punt;
    }
    expected = FIELD_OFFSET(KEY_VALUE_FULL_INFORMATION, Name) +
                    ValueName.Length + strlen(datastring) + 1;
    if (ResultLength != expected) {
        printf("rtmisc1: t6a: expected = %08lx actual = %08lx",
                expected, ResultLength);
        failure++;
    }

    if ( (KeyValueInformation->TitleIndex != TITLE_INDEX_2)         ||
         (KeyValueInformation->Type != TYPE_1)                      ||
         (KeyValueInformation->NameLength != ValueName.Length)      ||
         (KeyValueInformation->DataLength != strlen(datastring)+1))
    {
        printf("rtmisc1: t6b: wrong description data\n");
        failure++;
    }


    tp = (PWSTR)&(KeyValueInformation->Name[0]);
    if (wcsncmp(ValueName.Buffer, tp, (ValueName.Length/sizeof(WCHAR))) != 0) {
        printf("rtmisc1: t6c: wrong name\n");
        expectstring(
            ValueName.Buffer,
            (ValueName.Length/sizeof(WCHAR)),
            (PWSTR)&(KeyValueInformation->Name[0]),
            (KeyValueInformation->NameLength/sizeof(WCHAR))
            );
        failure++;
    }


    tp = (PUCHAR)KeyValueInformation + KeyValueInformation->DataOffset;
    if (strcmp(tp, datastring) != 0) {
        printf("rtmisc1: t6d: wrong data\n");
        printf("expected '%s', got '%s'\n", datastring, tp);
        failure++;
    }

    //
    // t7: Create a second value
    //

    RtlInitUnicodeString(
        &ValueName2,
        L"the second value stored in the registry"
        );


    status = NtSetValueKey(
                Testhand1,
                &ValueName2,
                TITLE_INDEX_3,
                TYPE_2,
                datastring2,
                strlen(datastring2)+1
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t7: %08lx\n", status);
        failure++;
    }

    //
    // t8: Read the second value back (short form)
    //

    RtlZeroMemory(KeyValueBasic, bufsize);
    status = NtQueryValueKey(
                Testhand1,
                &ValueName2,
                KeyValueBasicInformation,
                KeyValueBasic,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t8: %08lx\n", status);
        goto punt;
    }

    expected = FIELD_OFFSET(KEY_VALUE_BASIC_INFORMATION, Name) +
                    ValueName2.Length;
    if (ResultLength != expected) {
        printf("rtmisc1: t8a: expected = %08lx actual = %08lx",
                expected, ResultLength);
        failure++;
    }

    if ( (KeyValueBasic->TitleIndex != TITLE_INDEX_3)         ||
         (KeyValueBasic->Type != TYPE_2)                      ||
         (KeyValueBasic->NameLength != ValueName2.Length))
    {
        printf("rtmisc1: t8b: wrong description data\n");
        failure++;
    }


    tp = (PWSTR)&(KeyValueBasic->Name[0]);
    if (wcsncmp(ValueName2.Buffer, tp, (ValueName2.Length/sizeof(WCHAR))) != 0) {
        printf("rtmisc1: t8c: wrong name\n");
        expectstring(
            ValueName2.Buffer,
            (ValueName2.Length/sizeof(WCHAR)),
            (PWSTR)&(KeyValueBasic->Name[0]),
            (KeyValueBasic->NameLength/sizeof(WCHAR))
            );
        failure++;
    }


    //
    // t9: Enumerate the values (short form)
    //

    RtlZeroMemory(KeyValueBasic, bufsize);
    status = NtEnumerateValueKey(
                Testhand1,
                0,              // Index
                KeyValueBasicInformation,
                KeyValueBasic,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t9: %08lx\n", status);
        goto punt;
    }

    expected = FIELD_OFFSET(KEY_VALUE_BASIC_INFORMATION, Name) +
                    ValueName.Length;
    if (ResultLength != expected) {
        printf("rtmisc1: t9a: expected = %08lx actual = %08lx",
                expected, ResultLength);
        failure++;
    }

    if (KeyValueBasic->NameLength != ValueName.Length)
    {
        printf("rtmisc1: t9b: wrong description data\n");
        failure++;
    }


    tp = (PWSTR)&(KeyValueBasic->Name[0]);
    if (wcsncmp(ValueName.Buffer, tp, (ValueName.Length/sizeof(WCHAR))) != 0) {
        printf("rtmisc1: t9c: wrong name\n");
        expectstring(
            ValueName.Buffer,
            (ValueName.Length/sizeof(WCHAR)),
            (PWSTR)&(KeyValueBasic->Name[0]),
            (KeyValueBasic->NameLength/sizeof(WCHAR))
            );
        failure++;
    }

    RtlZeroMemory(KeyValueBasic, bufsize);
    status = NtEnumerateValueKey(
                Testhand1,
                1,              // Index
                KeyValueBasicInformation,
                KeyValueBasic,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t9d: %08lx\n", status);
        goto punt;
    }

    expected = FIELD_OFFSET(KEY_VALUE_BASIC_INFORMATION, Name) +
                    ValueName2.Length;
    if (ResultLength != expected) {
        printf("rtmisc1: t9e: expected = %08lx actual = %08lx",
                expected, ResultLength);
        failure++;
    }

    if (KeyValueBasic->NameLength != ValueName2.Length)
    {
        printf("rtmisc1: t9f: wrong description data\n");
        failure++;
    }


    tp = (PWSTR)&(KeyValueBasic->Name[0]);
    if (wcsncmp(ValueName2.Buffer, tp, (ValueName2.Length/sizeof(WCHAR))) != 0) {
        printf("rtmisc1: t9g: wrong name\n");
        expectstring(
            ValueName2.Buffer,
            (ValueName2.Length/sizeof(WCHAR)),
            (PWSTR)&(KeyValueBasic->Name[0]),
            (KeyValueBasic->NameLength/sizeof(WCHAR))
            );
        failure++;
    }

    status = NtEnumerateValueKey(
                Testhand1,
                2,              // Index
                KeyValueBasicInformation,
                KeyValueBasic,
                bufsize,
                &ResultLength
                );
    if (status != STATUS_NO_MORE_ENTRIES) {
        printf("rtmisc1: t9h: %08lx\n", status);
        goto punt;
    }

    //
    // t10: create a second subkey and ennumerate the subkeys
    //

    status = NtClose(Testhand1);
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t10a: %08lx\n", status);
        failure++;
    }

    RtlInitUnicodeString(
        &ClassName2,
        L"t2 Class Name"
        );

    RtlInitUnicodeString(
        &KeyName2,
        L"second_test_node"
        );

    InitializeObjectAttributes(
        &ObjectAttributes,
        &KeyName2,
        0,
        BaseHandle,
        NULL
        );
    ObjectAttributes.Attributes |= OBJ_CASE_INSENSITIVE;

    status = NtCreateKey(
                &Testhand1,
                MAXIMUM_ALLOWED,
                &ObjectAttributes,
                TITLE_INDEX_2,
                &ClassName2,
                0,
                &Disposition
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t10b: %08lx\n", status);
        goto punt;
    }

    if (Disposition != REG_CREATED_NEW_KEY) {
        printf("rtmisc1: t10c: got old key, expected to create new one\n");
        failure++;
    }

    //
    // See if we can get data back, and if it makes sense
    //

    RtlZeroMemory(NodeInformation, bufsize);
    status = NtQueryKey(
                Testhand1,
                KeyNodeInformation,
                NodeInformation,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t10d: %08lx\n", status);
        goto punt;
    }
    CompTime = NodeInformation->LastWriteTime;


    NameClassAndTitle(
        NodeInformation,
        ClassName2,
        TITLE_INDEX_2,
        KeyName2,
        CompTime,
        TRUE,
        "rtmisc1: t10e: "
        );

    status = NtClose(Testhand1);
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t10f: %08lx\n");
        goto punt;
    }


    RtlZeroMemory(NodeInformation, bufsize);
    status = NtEnumerateKey(
                BaseHandle,
                0,
                KeyNodeInformation,
                NodeInformation,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t10g: %08lx\n", status);
        failure++;
    }
    CompTime = NodeInformation->LastWriteTime;

    NameClassAndTitle(
        NodeInformation,
        ClassName,
        TITLE_INDEX_1,
        KeyName,
        CompTime,
        TRUE,
        "rtmisc1: t10h: "
        );


    RtlZeroMemory(NodeInformation, bufsize);
    status = NtEnumerateKey(
                BaseHandle,
                1,
                KeyNodeInformation,
                NodeInformation,
                bufsize,
                &ResultLength
                );
    if (!NT_SUCCESS(status)) {
        printf("rtmisc1: t10i: %08lx\n", status);
        failure++;
    }
    CompTime = NodeInformation->LastWriteTime;

    NameClassAndTitle(
        NodeInformation,
        ClassName2,
        TITLE_INDEX_2,
        KeyName2,
        CompTime,
        TRUE,
        "rtmisc1: t10j: "
        );


    status = NtEnumerateKey(
                BaseHandle,
                2,
                KeyNodeInformation,
                NodeInformation,
                bufsize,
                &ResultLength
                );
    if (status != STATUS_NO_MORE_ENTRIES) {
        printf("rtmisc1: t10k: %08lx\n", status);
        failure++;
    }

    //
    // Summary report
    //

    if (!failure) {
        printf("rtmisc1: success");
        exit(0);
    } else {
        printf("rtmisc1: failed, %d failures\n", failure);
        exit(1);
    }

punt:
    failure++;
    printf("rtmisc1: failed, %d failures\n", failure);
    exit(1);
}
Ejemplo n.º 14
0
BOOLEAN
SepAdtInitializePrivilegeAuditing(
    VOID
    )

/*++

Routine Description:

    Checks to see if there is an entry in the registry telling us to do full privilege auditing
    (which currently means audit everything we normall audit, plus backup and restore privileges).

Arguments:

    None

Return Value:

    BOOLEAN - TRUE if Auditing has been initialized correctly, else FALSE.

--*/

{
    HANDLE KeyHandle;
    NTSTATUS Status;
    NTSTATUS TmpStatus;
    OBJECT_ATTRIBUTES Obja;
    ULONG ResultLength;
    UNICODE_STRING KeyName;
    UNICODE_STRING ValueName;
    CHAR KeyInfo[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(BOOLEAN)];
    PKEY_VALUE_PARTIAL_INFORMATION pKeyInfo;
    BOOLEAN Verbose;

    PAGED_CODE();

    //
    // Query the registry to set up the privilege auditing filter.
    //

    RtlInitUnicodeString( &KeyName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Lsa");

    InitializeObjectAttributes( &Obja,
                                &KeyName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                                );

    Status = NtOpenKey(
                 &KeyHandle,
                 KEY_QUERY_VALUE | KEY_SET_VALUE,
                 &Obja
                 );


    if (!NT_SUCCESS( Status )) {

        if (Status == STATUS_OBJECT_NAME_NOT_FOUND) {

            return ( SepInitializePrivilegeFilter( FALSE ));

        } else {

            return( FALSE );
        }
    }

    RtlInitUnicodeString( &ValueName, FULL_PRIVILEGE_AUDITING );

    Status = NtQueryValueKey(
                 KeyHandle,
                 &ValueName,
                 KeyValuePartialInformation,
                 KeyInfo,
                 sizeof(KeyInfo),
                 &ResultLength
                 );

    TmpStatus = NtClose(KeyHandle);
    ASSERT(NT_SUCCESS(TmpStatus));

    if (!NT_SUCCESS( Status )) {

        Verbose = FALSE;

    } else {

        pKeyInfo = (PKEY_VALUE_PARTIAL_INFORMATION)KeyInfo;
        Verbose = (BOOLEAN) *(pKeyInfo->Data);
    }

    return ( SepInitializePrivilegeFilter( Verbose ));
}
Ejemplo n.º 15
0
BOOLEAN
PiAddPlugPlayBusEnumeratorToList(
    IN     HANDLE ServiceKeyHandle,
    IN     PUNICODE_STRING ServiceName,
    IN OUT PVOID Context
    )

/*++

Routine Description:

    This routine is a callback function for IopApplyFunctionToSubKeys.
    It is called for each service key under
    HKLM\System\CurrentControlSet\Services. Its purpose is to take each
    service entry representing a bus enumerator, and create a corresponding
    bus enumerator entry in the Plug&Play bus enumerator list.

    NOTE: The PnP Bus Enumerator list resource must be held for exclusive
    (write) access before invoking this routine. The PnP device-specific
    registry resource must be held for shared (read) access.

Arguments:

    ServiceKeyHandle - Supplies a handle to a service entry key.

    ServiceName - Supplies the name of this service.

    Context - Not used.

Returns:

    TRUE to continue the enumeration.
    FALSE to abort it.

--*/

{
    UNICODE_STRING ValueName;
    NTSTATUS Status;
    PKEY_VALUE_FULL_INFORMATION KeyValueInformation;
    ULONG RequiredLength;
    BOOLEAN IsBusExtender = FALSE;
    PUNICODE_STRING DeviceIDList;
    ULONG DeviceIDCount;
    PPLUGPLAY_BUS_ENUMERATOR BusEnumerator;

    //
    // First, see if this service is for a bus extender.  (Since we have
    // scratch space, use it, so we don't do memory allocations when checking
    // each service.)
    //
    RtlInitUnicodeString(&ValueName, REGSTR_VALUE_PLUGPLAY_SERVICE_TYPE);
    Status = NtQueryValueKey(ServiceKeyHandle,
                             &ValueName,
                             KeyValueFullInformation,
                             PiScratchBuffer,
                             PNP_LARGE_SCRATCH_BUFFER_SIZE,
                             &RequiredLength
                            );
    if(NT_SUCCESS(Status)) {
        if((((PKEY_VALUE_FULL_INFORMATION)PiScratchBuffer)->Type == REG_DWORD) &&
           (((PKEY_VALUE_FULL_INFORMATION)PiScratchBuffer)->DataLength >= sizeof(ULONG))) {

            IsBusExtender = (PlugPlayServiceBusExtender == (PLUGPLAY_SERVICE_TYPE)
                    (*(PULONG)KEY_VALUE_DATA((PKEY_VALUE_FULL_INFORMATION)PiScratchBuffer)));
        }
    }

    if(!IsBusExtender) {
        return TRUE;
    }

    //
    // We have a bus extender, so allocate a node for it.
    //
    BusEnumerator = (PPLUGPLAY_BUS_ENUMERATOR)ExAllocatePool(PagedPool,
                                                             sizeof(PLUGPLAY_BUS_ENUMERATOR));
    if(!BusEnumerator) {
        return TRUE;
    }

    if(!IopConcatenateUnicodeStrings(&(BusEnumerator->ServiceName),
                                     ServiceName,
                                     NULL
                                    )) {
        ExFreePool(BusEnumerator);
        return TRUE;
    }

    //
    // Now, retrieve the list of compatible device IDs from the service's
    // DeviceIDs REG_MULTI_SZ value entry.
    //
    Status = IopGetRegistryValue(ServiceKeyHandle,
                                 REGSTR_VALUE_DEVICE_IDS,
                                 &KeyValueInformation
                                );
    if(!NT_SUCCESS(Status)) {
        //
        // Since we couldn't retrieve any compatible IDs, assume there are none,
        // and initialize the BusEnumerator structure with a device ID count of zero.
        //
        DeviceIDList = NULL;
        DeviceIDCount = 0;
    } else {

        Status = IopRegMultiSzToUnicodeStrings(KeyValueInformation,
                                               &DeviceIDList,
                                               &DeviceIDCount
                                              );
        ExFreePool(KeyValueInformation);

        if(!NT_SUCCESS(Status)) {
            ExFreePool(BusEnumerator->ServiceName.Buffer);
            ExFreePool(BusEnumerator);
            return TRUE;
        }
    }

    //
    // Finish filling in the bus enumerator node and insert it into the tail of the list.
    //
    InitializeListHead(&(BusEnumerator->BusInstanceListEntry));
    BusEnumerator->PlugPlayIDs = DeviceIDList;
    BusEnumerator->PlugPlayIDCount = DeviceIDCount;
    RtlInitUnicodeString(&(BusEnumerator->DriverName), NULL);
    //BusEnumerator->DriverObject = NULL;

    InsertTailList(&PpBusListHead, &(BusEnumerator->BusEnumeratorListEntry));

    return TRUE;
}
Ejemplo n.º 16
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;
}
Ejemplo n.º 17
0
/******************************************************************
 *		start_debugger
 *
 * Does the effective debugger startup according to 'format'
 */
static BOOL	start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
{
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;
    char *cmdline, *env, *p;
    HANDLE		hDbgConf;
    DWORD		bAuto = TRUE;
    PROCESS_INFORMATION	info;
    STARTUPINFOA	startup;
    char*		format = NULL;
    BOOL		ret = FALSE;
    char buffer[256];

    static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
                                     'S','o','f','t','w','a','r','e','\\',
                                     'M','i','c','r','o','s','o','f','t','\\',
                                     'W','i','n','d','o','w','s',' ','N','T','\\',
                                     'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                     'A','e','D','e','b','u','g',0};
    static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
    static const WCHAR AutoW[] = {'A','u','t','o',0};

    format_exception_msg( epointers, buffer, sizeof(buffer) );
    MESSAGE("wine: %s (thread %04x), starting debugger...\n", buffer, GetCurrentThreadId());

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &nameW, AeDebugW );

    if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
    {
        char buffer[64];
        KEY_VALUE_PARTIAL_INFORMATION *info;
        DWORD format_size = 0;

        RtlInitUnicodeString( &nameW, DebuggerW );
        if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
                             NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
        {
            char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
            NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
                             data, format_size, &format_size );
            info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
            RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
            format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
            RtlUnicodeToMultiByteN( format, format_size, NULL,
                                    (WCHAR *)info->Data, info->DataLength );
            format[format_size] = 0;

            if (info->Type == REG_EXPAND_SZ)
            {
                char* tmp;

                /* Expand environment variable references */
                format_size=ExpandEnvironmentStringsA(format,NULL,0);
                tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
                ExpandEnvironmentStringsA(format,tmp,format_size);
                HeapFree(GetProcessHeap(), 0, format);
                format=tmp;
            }
            HeapFree( GetProcessHeap(), 0, data );
        }

        RtlInitUnicodeString( &nameW, AutoW );
        if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
                              buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
       {
           info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
           if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
           else if (info->Type == REG_SZ)
           {
               WCHAR *str = (WCHAR *)info->Data;
               str[info->DataLength/sizeof(WCHAR)] = 0;
               bAuto = atoiW( str );
           }
       }

       NtClose(hDbgConf);
    }

    if (format)
    {
        cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
        sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
        HeapFree(GetProcessHeap(), 0, format);
    }
    else
    {
        cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
        sprintf(cmdline, "winedbg --auto %d %ld",
                GetCurrentProcessId(), (ULONG_PTR)hEvent);
    }

    if (!bAuto)
    {
	HMODULE			mod = GetModuleHandleA( "user32.dll" );
	MessageBoxA_funcptr	pMessageBoxA = NULL;

	if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
	if (pMessageBoxA)
	{
            static const char msg[] = ".\nDo you wish to debug it?";
	    char buffer[256];

            format_exception_msg( epointers, buffer, sizeof(buffer)-sizeof(msg) );
            strcat( buffer, msg );
	    if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
	    {
		TRACE("Killing process\n");
		goto EXIT;
	    }
	}
    }

    /* make WINEDEBUG empty in the environment */
    env = GetEnvironmentStringsA();
    for (p = env; *p; p += strlen(p) + 1)
    {
        if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
        {
            char *next = p + strlen(p);
            char *end = next + 1;
            while (*end) end += strlen(end) + 1;
            memmove( p + sizeof("WINEDEBUG=") - 1, next, end + 1 - next );
            break;
        }
    }

    TRACE("Starting debugger %s\n", debugstr_a(cmdline));
    memset(&startup, 0, sizeof(startup));
    startup.cb = sizeof(startup);
    startup.dwFlags = STARTF_USESHOWWINDOW;
    startup.wShowWindow = SW_SHOWNORMAL;
    ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
    FreeEnvironmentStringsA( env );

    if (ret)
    {
        /* wait for debugger to come up... */
        HANDLE handles[2];
        CloseHandle(info.hThread);
        handles[0]=hEvent;
        handles[1]=info.hProcess;
        WaitForMultipleObjects(2, handles, FALSE, INFINITE);
        CloseHandle(info.hProcess);
    }
    else ERR("Couldn't start debugger (%s) (%d)\n"
             "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
             debugstr_a(cmdline), GetLastError());
EXIT:
    HeapFree(GetProcessHeap(), 0, cmdline);
    return ret;
}
Ejemplo n.º 18
0
Archivo: move.c Proyecto: RPG-7/reactos
/*
 * @implemented
 */
NTSTATUS
WINAPI
BasepMoveFileDelayed(IN PUNICODE_STRING ExistingPath,
                     IN PUNICODE_STRING NewPath,
                     IN INT KeyId,
                     IN BOOL CreateIfNotFound)
{
#define STRING_LENGTH 0x400
    NTSTATUS Status;
    HANDLE KeyHandle;
    PVOID Buffer, BufferBegin;
    OBJECT_ATTRIBUTES ObjectAttributes;
    PWSTR PendingOperations, BufferWrite;
    ULONG DataSize, BufferLength, StringLength = STRING_LENGTH;
    UNICODE_STRING SessionManagerString, PendingOperationsString;
    /* +6 because a INT shouldn't take more than 6 chars. Especially given the call path */
    WCHAR PendingOperationsBuffer[sizeof(L"PendingFileRenameOperations") / sizeof(WCHAR) + 6];

    RtlInitUnicodeString(&SessionManagerString, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Session Manager");

    /* Select appropriate key for adding our file */
    if (KeyId == 1)
    {
        PendingOperations = L"PendingFileRenameOperations";
    }
    else
    {
        StringCbPrintfW(PendingOperationsBuffer, sizeof(PendingOperationsBuffer), L"PendingFileRenameOperations%d", KeyId);
        PendingOperations = PendingOperationsBuffer;
    }
    RtlInitUnicodeString(&PendingOperationsString, PendingOperations);

    InitializeObjectAttributes(&ObjectAttributes,
                               &SessionManagerString,
                               OBJ_OPENIF | OBJ_CASE_INSENSITIVE,
                               NULL, NULL);

    /* Open parent key */
    Status = NtCreateKey(&KeyHandle,
                         GENERIC_READ | GENERIC_WRITE,
                         &ObjectAttributes, 0, NULL,
                         REG_OPTION_NON_VOLATILE, NULL);
    if (Status == STATUS_ACCESS_DENIED)
    {
        Status = NtCreateKey(&KeyHandle,
                             GENERIC_READ | GENERIC_WRITE,
                             &ObjectAttributes, 0, NULL,
                             REG_OPTION_BACKUP_RESTORE, NULL);
    }

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

    /* Reserve enough to read previous string + to append our with required null chars */
    BufferLength = NewPath->Length + ExistingPath->Length + STRING_LENGTH + 3 * sizeof(WCHAR);
    /* Check we didn't overflow */
    if (BufferLength < STRING_LENGTH)
    {
        NtClose(KeyHandle);
        return STATUS_BUFFER_TOO_SMALL;
    }

    while (TRUE)
    {
        /* Allocate output buffer */
        Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, BufferLength);
        if (Buffer == NULL)
        {
            NtClose(KeyHandle);
            return STATUS_NO_MEMORY;
        }

        Status = NtQueryValueKey(KeyHandle,
                                 &PendingOperationsString,
                                 KeyValuePartialInformation,
                                 Buffer, StringLength, &DataSize);
        if (Status != STATUS_BUFFER_OVERFLOW)
        {
            break;
        }

        /* If buffer was too small, then, reallocate one which is big enough */
        StringLength = DataSize;
        RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
        BufferLength = ExistingPath->Length + StringLength + NewPath->Length + 3 * sizeof(WCHAR);
        if (BufferLength < StringLength)
        {
            NtClose(KeyHandle);
            return STATUS_BUFFER_TOO_SMALL;
        }
    }

    /* Check if it existed - if not, create only IF asked to */
    if (!NT_SUCCESS(Status) && (Status != STATUS_OBJECT_NAME_NOT_FOUND || !CreateIfNotFound))
    {
        NtClose(KeyHandle);
        RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);
        return Status;
    }

    if (!NT_SUCCESS(Status))
    {
        /* We didn't find any - ie, we create, so use complete buffer */
        BufferBegin = Buffer;
        BufferWrite = Buffer;
    }
    else
    {
        PKEY_VALUE_PARTIAL_INFORMATION PartialInfo = (PKEY_VALUE_PARTIAL_INFORMATION)Buffer;

        /* Get data, our buffer begin and then where we should append data (+ null char) */
        BufferBegin = PartialInfo->Data;
        BufferWrite = (PWSTR)((ULONG_PTR)PartialInfo->Data + PartialInfo->DataLength + sizeof(WCHAR));
    }

    /* First copy existing */
    RtlCopyMemory(BufferWrite, ExistingPath->Buffer, ExistingPath->Length);
    BufferWrite += ExistingPath->Length / sizeof(WCHAR);
    /* And append null char */
    *BufferWrite = UNICODE_NULL;
    ++BufferWrite;
    /* Append destination */
    RtlCopyMemory(BufferWrite, NewPath->Buffer, NewPath->Length);
    BufferWrite += NewPath->Length / sizeof(WCHAR);
    /* And append two null char (end of string) */
    *BufferWrite = UNICODE_NULL;
    ++BufferWrite;
    *BufferWrite = UNICODE_NULL;

    /* Set new value */
    Status = NtSetValueKey(KeyHandle,
                           &PendingOperationsString,
                           0, REG_MULTI_SZ, BufferBegin,
                           (ULONG_PTR)BufferWrite - (ULONG_PTR)BufferBegin + sizeof(WCHAR));

    NtClose(KeyHandle);
    RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer);

    return Status;
}
Ejemplo n.º 19
0
/*
* SfuBuildBotPath
*
* Purpose:
*
* Return full path to bot in both variants.
*
*/
BOOL SfuBuildBotPath(
	_Inout_ PZA_BOT_PATH Context
	)
{
	BOOL                           cond = FALSE, bResult = FALSE;
	OBJECT_ATTRIBUTES              obja;
	UNICODE_STRING                 ustr1, ustr2;
	WCHAR                          szRegBuffer[MAX_PATH + 1];
	HANDLE                         ProcessHeap; 
	HANDLE                         hKey = NULL;
	NTSTATUS                       status;
	KEY_VALUE_PARTIAL_INFORMATION *pki = NULL;
	LPWSTR                         lpEnv;
	ULONG                          memIO = 0;
	LPWSTR                         lpLocalBotName, lpPFilesBotName;
	PVOID                          Wow64Information = NULL;

	GUID sfGUID;

	if (Context == NULL)
		return bResult;

	ProcessHeap = RtlGetCurrentPeb()->ProcessHeap;

	RtlSecureZeroMemory(&ustr1, sizeof(ustr1));

	do {

		if (!SfInitMD5())
			break;

		RtlSecureZeroMemory(&sfGUID, sizeof(sfGUID));
		SfuCalcVolumeMD5((BYTE*)&sfGUID);

		status = NtQueryInformationProcess(NtCurrentProcess(), ProcessWow64Information, 
			&Wow64Information, sizeof(PVOID), NULL);
		if (!NT_SUCCESS(status))
			break;

		//query current user registry string
		if (!NT_SUCCESS(RtlFormatCurrentUserKeyPath(&ustr1)))
			break;

		lpLocalBotName = Context->szBotPathLocal;
		lpPFilesBotName = Context->szBotPathPFiles;

		RtlSecureZeroMemory(&szRegBuffer, sizeof(szRegBuffer));
		wsprintf(szRegBuffer, T_SHELL_FOLDERS_KEY, ustr1.Buffer);

		RtlFreeUnicodeString(&ustr1);
		
		//open User Shell Folders key to query Local AppData value
		RtlSecureZeroMemory(&ustr2, sizeof(ustr2));
		RtlInitUnicodeString(&ustr2, szRegBuffer);
		InitializeObjectAttributes(&obja, &ustr2, OBJ_CASE_INSENSITIVE, NULL, NULL);
		status = NtOpenKey(&hKey, KEY_READ, &obja);
		if (!NT_SUCCESS(status))
			break;

		//query value size
		RtlInitUnicodeString(&ustr2, T_LOCAL_APPDATA_VALUE);
		NtQueryValueKey(hKey, &ustr2, KeyValuePartialInformation,
			NULL, 0, &memIO);

		if (memIO == 0)
			break;

		pki = RtlAllocateHeap(ProcessHeap, HEAP_ZERO_MEMORY, memIO);
		if (pki == NULL)
			break;
		
		//query value
		status = NtQueryValueKey(hKey, &ustr2, KeyValuePartialInformation,
			pki, memIO, &memIO);

		if (!NT_SUCCESS(status)) 
			break;

		RtlInitUnicodeString(&ustr2, (WCHAR*)pki->Data);
		memIO = 0;

		//expand environment variable inside value
		RtlSecureZeroMemory(&szRegBuffer, sizeof(szRegBuffer));
		ustr1.Buffer = szRegBuffer;
		ustr1.Length = 0;
		ustr1.MaximumLength = sizeof(szRegBuffer);

		status = RtlExpandEnvironmentStrings_U(NULL, &ustr2, &ustr1, &memIO);
		if (!NT_SUCCESS(status)) {
			ustr1.Buffer = NULL;
			break;
		}

		//build result string
		_strcpy(lpLocalBotName, T_GLOBAL_LINK);
		_strcat(lpLocalBotName, szRegBuffer);
		
		wsprintf(_strend(lpLocalBotName), T_SIREFEF_DIRECTORY,
			sfGUID.Data1, sfGUID.Data2, sfGUID.Data3,
			sfGUID.Data4[0],
			sfGUID.Data4[1],
			sfGUID.Data4[2],
			sfGUID.Data4[3],
			sfGUID.Data4[4],
			sfGUID.Data4[5],
			sfGUID.Data4[6],
			sfGUID.Data4[7]);

		ustr1.Buffer = NULL;

		_strcpy(lpPFilesBotName, T_GLOBAL_LINK);
		
		if (Wow64Information == NULL) {
			lpEnv = L"ProgramFiles=";
		}
		else {
			lpEnv = L"ProgramFiles(x86)=";
		}

		RtlInitUnicodeString(&ustr2, lpEnv);
		lpEnv = SfuQueryEnvironmentVariableOffset(&ustr2);
		if (lpEnv) {
			_strcat(lpPFilesBotName, lpEnv);

			wsprintf(_strend(lpPFilesBotName), T_SIREFEF_DIRECTORY,
				sfGUID.Data1, sfGUID.Data2, sfGUID.Data3,
				sfGUID.Data4[0],
				sfGUID.Data4[1],
				sfGUID.Data4[2],
				sfGUID.Data4[3],
				sfGUID.Data4[4],
				sfGUID.Data4[5],
				sfGUID.Data4[6],
				sfGUID.Data4[7]);
		}

		bResult = TRUE;

	} while (cond);

	if (hKey != NULL) {
		NtClose(hKey);
	}

	if (ustr1.Buffer != NULL) {
		RtlFreeUnicodeString(&ustr1);
	}

	if (pki != NULL) {
		RtlFreeHeap(ProcessHeap, 0, pki);
	}
	return bResult;
}
Ejemplo n.º 20
0
VOID
SepAdtInitializeBounds(
    VOID
    )

/*++

Routine Description:

    Queries the registry for the high and low water mark values for the
    audit log.  If they are not found or are unacceptable, returns without
    modifying the current values, which are statically initialized.

Arguments:

    None.

Return Value:

    None.

--*/

{

    HANDLE KeyHandle;
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING KeyName;
    UNICODE_STRING ValueName;
    NTSTATUS Status;
    PSEP_AUDIT_BOUNDS AuditBounds;
    PKEY_VALUE_PARTIAL_INFORMATION KeyValueInformation;
    ULONG Length;

    PAGED_CODE();

    //
    // Get the high and low water marks out of the registry.
    //

    RtlInitUnicodeString( &KeyName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Lsa");

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

    Status = NtOpenKey(
                 &KeyHandle,
                 KEY_QUERY_VALUE,
                 &ObjectAttributes
                 );

    if (!NT_SUCCESS( Status )) {

        //
        // Didn't work, take the defaults
        //

        return;
    }

    RtlInitUnicodeString( &ValueName, L"Bounds");

    Length = sizeof( KEY_VALUE_PARTIAL_INFORMATION ) - sizeof( UCHAR ) + sizeof( SEP_AUDIT_BOUNDS );

    KeyValueInformation = ExAllocatePool( PagedPool, Length );

    if ( KeyValueInformation == NULL ) {

        NtClose( KeyHandle );
        return;
    }

    Status = NtQueryValueKey(
                 KeyHandle,
                 &ValueName,
                 KeyValuePartialInformation,
                 (PVOID)KeyValueInformation,
                 Length,
                 &Length
                 );

    NtClose( KeyHandle );

    if (!NT_SUCCESS( Status )) {

        ExFreePool( KeyValueInformation );
        return;
    }


    AuditBounds = (PSEP_AUDIT_BOUNDS) &KeyValueInformation->Data;

    //
    // Sanity check what we got back
    //

    if(!SepAdtValidateAuditBounds( AuditBounds->UpperBound, AuditBounds->LowerBound )) {

        //
        // The values we got back are not to our liking.  Use the defaults.
        //

        ExFreePool( KeyValueInformation );
        return;
    }

    //
    // Take what we got from the registry.
    //

    SepAdtMaxListLength = AuditBounds->UpperBound;
    SepAdtMinListLength = AuditBounds->LowerBound;

    ExFreePool( KeyValueInformation );

    return;
}
Ejemplo n.º 21
0
NTSTATUS
SepAdtInitializeCrashOnFail(
    VOID
    )

/*++

Routine Description:

    Reads the registry to see if the user has told us to crash if an audit fails.

Arguments:

    None.

Return Value:

    STATUS_SUCCESS

--*/

{
    HANDLE KeyHandle;
    NTSTATUS Status;
    NTSTATUS TmpStatus;
    OBJECT_ATTRIBUTES Obja;
    ULONG ResultLength;
    UNICODE_STRING KeyName;
    UNICODE_STRING ValueName;
    CHAR KeyInfo[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(BOOLEAN)];
    PKEY_VALUE_PARTIAL_INFORMATION pKeyInfo;

    SepCrashOnAuditFail = FALSE;

    //
    // Check the value of the CrashOnAudit flag in the registry.
    //

    RtlInitUnicodeString( &KeyName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Lsa");

    InitializeObjectAttributes( &Obja,
                                &KeyName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                                );

    Status = NtOpenKey(
                 &KeyHandle,
                 KEY_QUERY_VALUE | KEY_SET_VALUE,
                 &Obja
                 );

    if (Status == STATUS_OBJECT_NAME_NOT_FOUND) {
        return( STATUS_SUCCESS );
    }

    RtlInitUnicodeString( &ValueName, CRASH_ON_AUDIT_FAIL_VALUE );

    Status = NtQueryValueKey(
                 KeyHandle,
                 &ValueName,
                 KeyValuePartialInformation,
                 KeyInfo,
                 sizeof(KeyInfo),
                 &ResultLength
                 );

    TmpStatus = NtClose(KeyHandle);
    ASSERT(NT_SUCCESS(TmpStatus));

    //
    // If the key isn't there, don't turn on CrashOnFail.
    //

    if (NT_SUCCESS( Status )) {

        pKeyInfo = (PKEY_VALUE_PARTIAL_INFORMATION)KeyInfo;
        if ((UCHAR) *(pKeyInfo->Data) == LSAP_CRASH_ON_AUDIT_FAIL) {
            SepCrashOnAuditFail = TRUE;
        }
    }

    return( STATUS_SUCCESS );
}
Ejemplo n.º 22
0
/***********************************************************************
 *           add_boot_rename_entry
 *
 * Adds an entry to the registry that is loaded when windows boots and
 * checks if there are some files to be removed or renamed/moved.
 * <fn1> has to be valid and <fn2> may be NULL. If both pointers are
 * non-NULL then the file is moved, otherwise it is deleted.  The
 * entry of the registrykey is always appended with two zero
 * terminated strings. If <fn2> is NULL then the second entry is
 * simply a single 0-byte. Otherwise the second filename goes
 * there. The entries are prepended with \??\ before the path and the
 * second filename gets also a '!' as the first character if
 * MOVEFILE_REPLACE_EXISTING is set. After the final string another
 * 0-byte follows to indicate the end of the strings.
 * i.e.:
 * \??\D:\test\file1[0]
 * !\??\D:\test\file1_renamed[0]
 * \??\D:\Test|delete[0]
 * [0]                        <- file is to be deleted, second string empty
 * \??\D:\test\file2[0]
 * !\??\D:\test\file2_renamed[0]
 * [0]                        <- indicates end of strings
 *
 * or:
 * \??\D:\test\file1[0]
 * !\??\D:\test\file1_renamed[0]
 * \??\D:\Test|delete[0]
 * [0]                        <- file is to be deleted, second string empty
 * [0]                        <- indicates end of strings
 *
 */
static BOOL add_boot_rename_entry( LPCWSTR source, LPCWSTR dest, DWORD flags )
{
    static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
                                      'F','i','l','e','R','e','n','a','m','e',
                                      'O','p','e','r','a','t','i','o','n','s',0};

    UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\Session Manager");

    static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );

    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING nameW, source_name, dest_name;
    KEY_VALUE_PARTIAL_INFORMATION *info;
    BOOL rc = FALSE;
    HANDLE Reboot = NULL;
    DWORD len1, len2;
    DWORD DestLen = 0;
    DWORD DataSize = 0;
    BYTE *Buffer = NULL;
    WCHAR *p;
    NTSTATUS Status;

    TRACE("add_boot_rename_entry( %S, %S, %d ) \n", source, dest, flags);

    if(dest)
        DestLen = wcslen(dest);

    if (!RtlDosPathNameToNtPathName_U( source, &source_name, NULL, NULL ))
    {
        SetLastError( ERROR_PATH_NOT_FOUND );
        return FALSE;
    }
    dest_name.Buffer = NULL;
    if (DestLen && !RtlDosPathNameToNtPathName_U( dest, &dest_name, NULL, NULL ))
    {
        RtlFreeHeap( RtlGetProcessHeap(), 0, source_name.Buffer );
        SetLastError( ERROR_PATH_NOT_FOUND );
        return FALSE;
    }

    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_OPENIF | OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

     Status = NtCreateKey(&Reboot, 
                          KEY_QUERY_VALUE | KEY_SET_VALUE,
                          &ObjectAttributes,
                          0,
                          NULL,
                          REG_OPTION_NON_VOLATILE,
                          NULL);

     if (Status == STATUS_ACCESS_DENIED)
     {
         Status = NtCreateKey(
             &Reboot, 
             KEY_QUERY_VALUE | KEY_SET_VALUE,
             &ObjectAttributes,
             0,
             NULL,
             REG_OPTION_BACKUP_RESTORE,
             NULL);
     }

    if (!NT_SUCCESS(Status))
    {
        WARN("NtCreateKey() failed (Status 0x%lx)\n", Status);
        if (source_name.Buffer)
            RtlFreeHeap(RtlGetProcessHeap(), 0, source_name.Buffer);
        if (dest_name.Buffer)
            RtlFreeHeap(RtlGetProcessHeap(), 0, dest_name.Buffer);
        return FALSE;
    }

    len1 = source_name.Length + sizeof(WCHAR);
    if (DestLen)
    {
        len2 = dest_name.Length + sizeof(WCHAR);
        if (flags & MOVEFILE_REPLACE_EXISTING)
            len2 += sizeof(WCHAR); /* Plus 1 because of the leading '!' */
    }
    else
    {
        len2 = sizeof(WCHAR); /* minimum is the 0 characters for the empty second string */
    }

    RtlInitUnicodeString( &nameW, ValueName );

    /* First we check if the key exists and if so how many bytes it already contains. */
    Status = NtQueryValueKey(
        Reboot,
        &nameW,
        KeyValuePartialInformation,
        NULL,
        0, 
        &DataSize );
    if ((Status == STATUS_BUFFER_OVERFLOW) ||
        (Status == STATUS_BUFFER_TOO_SMALL))
    {
        if (!(Buffer = HeapAlloc(GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR))))
            goto Quit;
        Status = NtQueryValueKey(Reboot, &nameW, KeyValuePartialInformation,
            Buffer, DataSize, &DataSize);
        if(!NT_SUCCESS(Status))
            goto Quit;
        info = (KEY_VALUE_PARTIAL_INFORMATION *)Buffer;
        if (info->Type != REG_MULTI_SZ) goto Quit;
        if (DataSize > sizeof(info)) DataSize -= sizeof(WCHAR);  /* remove terminating null (will be added back later) */
    }
    else
    {
        DataSize = info_size;
        if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
            goto Quit;
    }

    memcpy( Buffer + DataSize, source_name.Buffer, len1 );
    DataSize += len1;
    p = (WCHAR *)(Buffer + DataSize);
    if (DestLen)
    {
        if (flags & MOVEFILE_REPLACE_EXISTING)
            *p++ = '!';
        memcpy( p, dest_name.Buffer, len2 );
        DataSize += len2;
    }
    else
    {
        *p = 0;
        DataSize += sizeof(WCHAR);
    }

    /* add final null */
    p = (WCHAR *)(Buffer + DataSize);
    *p = 0;
    DataSize += sizeof(WCHAR);

    rc = NT_SUCCESS(NtSetValueKey(Reboot, &nameW, 0, REG_MULTI_SZ, Buffer + info_size, DataSize - info_size));

 Quit:
    RtlFreeHeap(RtlGetProcessHeap(), 0, source_name.Buffer);
    if (dest_name.Buffer)
        RtlFreeHeap(RtlGetProcessHeap(), 0, dest_name.Buffer);
    NtClose(Reboot);
    if(Buffer)
        HeapFree(GetProcessHeap(), 0, Buffer);
    return(rc);
}
Ejemplo n.º 23
0
/*********************************************************************** 
 *                      COMPUTERNAME_Init    (INTERNAL)
 */
void COMPUTERNAME_Init (void)
{
    HANDLE hkey = INVALID_HANDLE_VALUE, hsubkey = INVALID_HANDLE_VALUE;
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;
    char buf[offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data ) + (MAX_COMPUTERNAME_LENGTH + 1) * sizeof( WCHAR )];
    DWORD len = sizeof( buf );
    LPWSTR computer_name = (LPWSTR) (buf + offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data ));
    NTSTATUS st = STATUS_INTERNAL_ERROR;

    TRACE("(void)\n");
    _init_attr ( &attr, &nameW );
    
    RtlInitUnicodeString( &nameW, ComputerW );
    if ( ( st = NtCreateKey( &hkey, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) ) != STATUS_SUCCESS )
        goto out;
    
    attr.RootDirectory = hkey;
    RtlInitUnicodeString( &nameW, ComputerNameW );
    if ( (st = NtCreateKey( &hsubkey, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) ) != STATUS_SUCCESS )
        goto out;
    
    st = NtQueryValueKey( hsubkey, &nameW, KeyValuePartialInformation, buf, len, &len );

    if ( st != STATUS_SUCCESS || get_use_dns_option() )
    {
        char hbuf[256];
        int hlen = sizeof (hbuf);
        char *dot;
        TRACE( "retrieving Unix host name\n" );
        if ( gethostname ( hbuf, hlen ) )
        {
            strcpy ( hbuf, default_ComputerName );
            WARN( "gethostname() error: %d, using host name %s\n", errno, hbuf );
        }
        hbuf[MAX_COMPUTERNAME_LENGTH] = 0;
        dot = strchr ( hbuf, '.' );
        if ( dot ) *dot = 0;
        hlen = strlen ( hbuf );
        len = MultiByteToWideChar( CP_UNIXCP, 0, hbuf, hlen + 1, computer_name, MAX_COMPUTERNAME_LENGTH + 1 )
            * sizeof( WCHAR );
        if ( NtSetValueKey( hsubkey, &nameW, 0, REG_SZ, computer_name, len ) != STATUS_SUCCESS )
            WARN ( "failed to set ComputerName\n" );
    }
    else
    {
        len = (len - offsetof( KEY_VALUE_PARTIAL_INFORMATION, Data ));
        TRACE( "found in registry\n" );
    }

    NtClose( hsubkey );
    TRACE(" ComputerName: %s (%u)\n", debugstr_w (computer_name), len);

    RtlInitUnicodeString( &nameW, ActiveComputerNameW );
    if ( ( st = NtCreateKey( &hsubkey, KEY_ALL_ACCESS, &attr, 0, NULL, REG_OPTION_VOLATILE, NULL ) )
         != STATUS_SUCCESS )
        goto out;
    
    RtlInitUnicodeString( &nameW, ComputerNameW );
    st = NtSetValueKey( hsubkey, &nameW, 0, REG_SZ, computer_name, len );

out:
    NtClose( hsubkey );
    NtClose( hkey );

    if ( st == STATUS_SUCCESS )
        TRACE( "success\n" );
    else
    {
        WARN( "status trying to set ComputerName: %x\n", st );
        SetLastError ( RtlNtStatusToDosError ( st ) );
    }
}
Ejemplo n.º 24
0
PPH_STRING NvGpuQueryDriverSettings(VOID)
{
    if (NvAPI_GetDisplayDriverRegistryPath)
    {
        NvAPI_LongString nvKeyPathAnsiString = "";

        if (NvAPI_GetDisplayDriverRegistryPath(NvGpuDisplayHandleList->Items[0], nvKeyPathAnsiString) == NVAPI_OK)
        {
            HANDLE keyHandle;
            PPH_STRING keyPath;

            keyPath = PhConvertMultiByteToUtf16(nvKeyPathAnsiString);

            if (NT_SUCCESS(PhOpenKey(
                &keyHandle,
                KEY_READ,
                PH_KEY_LOCAL_MACHINE,
                &keyPath->sr,
                0
                )))
            {
                PPH_STRING driverDateString = NULL;// PhQueryRegistryString(keyHandle, L"DriverDate");
                PPH_STRING driverVersionString = PhQueryRegistryString(keyHandle, L"DriverVersion");

                UNICODE_STRING valueName;
                PKEY_VALUE_PARTIAL_INFORMATION buffer = NULL;
                ULONG bufferSize;

                RtlInitUnicodeString(&valueName, L"DriverDateData");

                if (NtQueryValueKey(
                    keyHandle,
                    &valueName,
                    KeyValuePartialInformation,
                    NULL,
                    0,
                    &bufferSize
                    ) == STATUS_BUFFER_TOO_SMALL)
                {
                    buffer = PhAllocate(bufferSize);

                    if (NT_SUCCESS(NtQueryValueKey(
                        keyHandle,
                        &valueName,
                        KeyValuePartialInformation,
                        buffer,
                        bufferSize,
                        &bufferSize
                        )))
                    {
                        if (buffer->Type == REG_BINARY && buffer->DataLength == sizeof(FILETIME))
                        {
                            SYSTEMTIME systemTime;
                            SYSTEMTIME localTime;

                            FileTimeToSystemTime((CONST FILETIME*)buffer->Data, &systemTime);
                            SystemTimeToTzSpecificLocalTime(NULL, &systemTime, &localTime);

                            driverDateString = PhFormatDate(&localTime, NULL);
                        }
                    }

                    PhFree(buffer);
                }
                
                NtClose(keyHandle);
                PhDereferenceObject(keyPath);
                PhAutoDereferenceObject(driverVersionString);

                if (driverDateString)
                {
                    PhAutoDereferenceObject(driverDateString);
                    return PhFormatString(L"%s [%s]", driverVersionString->Buffer, driverDateString->Buffer);
                }
                else
                {
                    return PhFormatString(L"%s", driverVersionString->Buffer);
                }
            }

            PhDereferenceObject(keyPath);
        }
    }

    return PhCreateString(L"N/A");
}
Ejemplo n.º 25
0
/**********************************************************************
 *         get_nt_registry_version
 *
 * Fetch the version information from the NT-style registry keys.
 */
static BOOL get_nt_registry_version( RTL_OSVERSIONINFOEXW *version )
{
    static const WCHAR version_keyW[] = {'M','a','c','h','i','n','e','\\',
                                         'S','o','f','t','w','a','r','e','\\',
                                         'M','i','c','r','o','s','o','f','t','\\',
                                         'W','i','n','d','o','w','s',' ','N','T','\\',
                                         'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
    static const WCHAR service_pack_keyW[] = {'M','a','c','h','i','n','e','\\',
                                              'S','y','s','t','e','m','\\',
                                              'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
                                              'C','o','n','t','r','o','l','\\',
                                              'W','i','n','d','o','w','s',0};
    static const WCHAR product_keyW[] = {'M','a','c','h','i','n','e','\\',
                                         'S','y','s','t','e','m','\\',
                                         'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
                                         'C','o','n','t','r','o','l','\\',
                                         'P','r','o','d','u','c','t','O','p','t','i','o','n','s',0};
    static const WCHAR CurrentBuildNumberW[] = {'C','u','r','r','e','n','t','B','u','i','l','d','N','u','m','b','e','r',0};
    static const WCHAR CSDVersionW[] = {'C','S','D','V','e','r','s','i','o','n',0};
    static const WCHAR CurrentVersionW[] = {'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
    static const WCHAR ProductTypeW[] = {'P','r','o','d','u','c','t','T','y','p','e',0};
    static const WCHAR WinNTW[]    = {'W','i','n','N','T',0};
    static const WCHAR ServerNTW[] = {'S','e','r','v','e','r','N','T',0};
    static const WCHAR LanmanNTW[] = {'L','a','n','m','a','n','N','T',0};

    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW, valueW;
    HANDLE hkey, hkey2;
    char tmp[64];
    DWORD count;
    BOOL ret = FALSE;
    KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)tmp;

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &nameW, version_keyW );

    if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr )) return FALSE;

    memset( version, 0, sizeof(*version) );

    RtlInitUnicodeString( &valueW, CurrentVersionW );
    if (!NtQueryValueKey( hkey, &valueW, KeyValuePartialInformation, tmp, sizeof(tmp)-1, &count ))
    {
        WCHAR *p, *str = (WCHAR *)info->Data;
        str[info->DataLength / sizeof(WCHAR)] = 0;
        p = strchrW( str, '.' );
        if (p)
        {
            *p++ = 0;
            version->dwMinorVersion = atoiW( p );
        }
        version->dwMajorVersion = atoiW( str );
    }

    if (version->dwMajorVersion)   /* we got the main version, now fetch the other fields */
    {
        ret = TRUE;
        version->dwPlatformId = VER_PLATFORM_WIN32_NT;

        /* get build number */

        RtlInitUnicodeString( &valueW, CurrentBuildNumberW );
        if (!NtQueryValueKey( hkey, &valueW, KeyValuePartialInformation, tmp, sizeof(tmp)-1, &count ))
        {
            WCHAR *str = (WCHAR *)info->Data;
            str[info->DataLength / sizeof(WCHAR)] = 0;
            version->dwBuildNumber = atoiW( str );
        }

        /* get version description */

        RtlInitUnicodeString( &valueW, CSDVersionW );
        if (!NtQueryValueKey( hkey, &valueW, KeyValuePartialInformation, tmp, sizeof(tmp)-1, &count ))
        {
            DWORD len = min( info->DataLength, sizeof(version->szCSDVersion) - sizeof(WCHAR) );
            memcpy( version->szCSDVersion, info->Data, len );
            version->szCSDVersion[len / sizeof(WCHAR)] = 0;
        }

        /* get service pack version */

        RtlInitUnicodeString( &nameW, service_pack_keyW );
        if (!NtOpenKey( &hkey2, KEY_ALL_ACCESS, &attr ))
        {
            RtlInitUnicodeString( &valueW, CSDVersionW );
            if (!NtQueryValueKey( hkey2, &valueW, KeyValuePartialInformation, tmp, sizeof(tmp), &count ))
            {
                if (info->DataLength >= sizeof(DWORD))
                {
                    DWORD dw = *(DWORD *)info->Data;
                    version->wServicePackMajor = LOWORD(dw) >> 8;
                    version->wServicePackMinor = LOWORD(dw) & 0xff;
                }
            }
Ejemplo n.º 26
0
/* registry link create test */
void test6(void)
{
  HANDLE hKey;
  OBJECT_ATTRIBUTES ObjectAttributes;
  UNICODE_STRING KeyName,ValueName;
  NTSTATUS Status;
  KEY_VALUE_FULL_INFORMATION KeyValueInformation[5];
  ULONG Length,i;

  dprintf("Create target key\n");
  dprintf("  Key: \\Registry\\Machine\\SOFTWARE\\Reactos\n");
  RtlRosInitUnicodeStringFromLiteral(&KeyName, L"\\Registry\\Machine\\SOFTWARE\\Reactos");
  InitializeObjectAttributes(&ObjectAttributes, &KeyName, OBJ_CASE_INSENSITIVE
				, NULL, NULL);
  Status = NtCreateKey(&hKey, KEY_ALL_ACCESS , &ObjectAttributes
		,0,NULL, REG_OPTION_VOLATILE,NULL);
  dprintf("  NtCreateKey() called (Status %lx)\n",Status);
  if (!NT_SUCCESS(Status))
    return;

  dprintf("Create target value\n");
  dprintf("  Value: TestValue = 'Test String'\n");
  RtlRosInitUnicodeStringFromLiteral(&ValueName, L"TestValue");
  Status=NtSetValueKey(hKey,&ValueName,0,REG_SZ,(PVOID)L"TestString",22);
  dprintf("  NtSetValueKey() called (Status %lx)\n",Status);
  if (!NT_SUCCESS(Status))
    return;

  dprintf("Close target key\n");
  NtClose(hKey);


  dprintf("Create link key\n");
  dprintf("  Key: \\Registry\\Machine\\SOFTWARE\\Test\n");
  RtlRosInitUnicodeStringFromLiteral(&KeyName, L"\\Registry\\Machine\\SOFTWARE\\Test");
  InitializeObjectAttributes(&ObjectAttributes,
			     &KeyName,
			     OBJ_CASE_INSENSITIVE | OBJ_OPENLINK,
			     NULL,
			     NULL);
  Status = NtCreateKey(&hKey,
		       KEY_ALL_ACCESS | KEY_CREATE_LINK,
		       &ObjectAttributes,
		       0,
		       NULL,
		       REG_OPTION_VOLATILE | REG_OPTION_CREATE_LINK,
		       NULL);
  dprintf("  NtCreateKey() called (Status %lx)\n",Status);
  if (!NT_SUCCESS(Status))
    return;

  dprintf("Create link value\n");
  dprintf("  Value: SymbolicLinkValue = '\\Registry\\Machine\\SOFTWARE\\Reactos'\n");
  RtlRosInitUnicodeStringFromLiteral(&ValueName, L"SymbolicLinkValue");
  Status=NtSetValueKey(hKey,&ValueName,0,REG_LINK,(PVOID)L"\\Registry\\Machine\\SOFTWARE\\Reactos",68);
  dprintf("  NtSetValueKey() called (Status %lx)\n",Status);
  if (!NT_SUCCESS(Status))
    {
      dprintf("Creating link value failed! Test failed!\n");
      NtClose(hKey);
      return;
    }

  dprintf("Close link key\n");
  NtClose(hKey);

  dprintf("Open link key\n");
  dprintf("  Key: \\Registry\\Machine\\SOFTWARE\\Test\n");
  RtlRosInitUnicodeStringFromLiteral(&KeyName, L"\\Registry\\Machine\\SOFTWARE\\Test");
  InitializeObjectAttributes(&ObjectAttributes, &KeyName, OBJ_CASE_INSENSITIVE | OBJ_OPENIF
				, NULL, NULL);
  Status = NtCreateKey(&hKey, KEY_ALL_ACCESS , &ObjectAttributes
		,0,NULL, REG_OPTION_VOLATILE, NULL);
  dprintf("  NtCreateKey() called (Status %lx)\n",Status);
  if (!NT_SUCCESS(Status))
    return;

  dprintf("Query value\n");
  dprintf("  Value: TestValue\n");
  RtlRosInitUnicodeStringFromLiteral(&ValueName, L"TestValue");
  Status=NtQueryValueKey(hKey,
			 &ValueName,
			 KeyValueFullInformation,
			 &KeyValueInformation[0],
			 sizeof(KeyValueInformation),
			 &Length);
  dprintf("  NtQueryValueKey() called (Status %lx)\n",Status);
  if (Status == STATUS_SUCCESS)
    {
      dprintf("  Value: Type %d  DataLength %d NameLength %d  Name '",
	      KeyValueInformation[0].Type,
	      KeyValueInformation[0].DataLength,
	      KeyValueInformation[0].NameLength);
      for (i=0; i < KeyValueInformation[0].NameLength / sizeof(WCHAR); i++)
	dprintf("%C",KeyValueInformation[0].Name[i]);
      dprintf("'\n");
      if (KeyValueInformation[0].Type == REG_SZ)
	dprintf("  Value '%S'\n",
		KeyValueInformation[0].Name+1
		+KeyValueInformation[0].NameLength/2);
    }

  dprintf("Close link key\n");
  NtClose(hKey);

  dprintf("Test successful!\n");
}
Ejemplo n.º 27
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;
}
Ejemplo n.º 28
0
void test9(void)
{
    HANDLE hKey = NULL, hKey1;
    OBJECT_ATTRIBUTES ObjectAttributes;
    NTSTATUS Status;
    UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\\Registry");
    ULONG Index,Length,i;
    KEY_BASIC_INFORMATION KeyInformation[5];
    KEY_VALUE_FULL_INFORMATION KeyValueInformation[5];

    dprintf("NtOpenKey \\Registry : ");
    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);
    Status=NtOpenKey( &hKey1, MAXIMUM_ALLOWED, &ObjectAttributes);
    dprintf("\t\t\t\tStatus =%x\n",Status);
    if (Status == 0) {
        dprintf("NtQueryKey : ");
        Status = NtQueryKey(hKey1, KeyBasicInformation, &KeyInformation[0], sizeof(KeyInformation), &Length);
        dprintf("\t\t\t\t\tStatus =%x\n",Status);
        if (Status == STATUS_SUCCESS) {
            dprintf("\tKey Name = ");
	        for (i=0;i<KeyInformation[0].NameLength/2;i++)
		        dprintf("%C",KeyInformation[0].Name[i]);
            dprintf("\n");
		}

        dprintf("NtEnumerateKey : \n");
        Index = 0;
        while (Status == STATUS_SUCCESS) {
            Status = NtEnumerateKey(hKey1,Index++,KeyBasicInformation,&KeyInformation[0], sizeof(KeyInformation),&Length);
            if (Status == STATUS_SUCCESS) {
                dprintf("\tSubKey Name = ");
                for (i = 0; i < KeyInformation[0].NameLength / 2; i++)
                    dprintf("%C",KeyInformation[0].Name[i]);
                dprintf("\n");
			}
		}
        dprintf("NtClose : ");
        Status = NtClose( hKey1 );
        dprintf("\t\t\t\t\tStatus =%x\n",Status);
	}
    NtClose(hKey); // RobD - hKey unused so-far, should this have been hKey1 ???

    dprintf("NtOpenKey \\Registry\\Machine : ");
    RtlRosInitUnicodeStringFromLiteral(&KeyName, L"\\Registry\\Machine");
    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);
    Status = NtOpenKey(&hKey1, MAXIMUM_ALLOWED, &ObjectAttributes);
    dprintf("\t\t\tStatus =%x\n",Status);

//Status of c0000001 opening \Registry\Machine\System\CurrentControlSet\Services\Tcpip\Linkage

//    dprintf("NtOpenKey System\\CurrentControlSet\\Services\\Tcpip : ");
//    RtlRosInitUnicodeStringFromLiteral(&KeyName, L"System\\CurrentControlSet\\Services\\Tcpip");
#if 1
    dprintf("NtOpenKey System\\ControlSet001\\Services\\Tcpip\\Parameters : ");
    RtlRosInitUnicodeStringFromLiteral(&KeyName, L"System\\ControlSet001\\Services\\Tcpip\\Parameters");
#else
    dprintf("NtOpenKey System\\CurrentControlSet\\Services\\Tcpip : ");
    RtlRosInitUnicodeStringFromLiteral(&KeyName, L"System\\CurrentControlSet\\Services\\Tcpip");
#endif
    InitializeObjectAttributes(&ObjectAttributes, &KeyName, OBJ_CASE_INSENSITIVE, hKey1 , NULL);
    Status = NtOpenKey(&hKey, KEY_READ , &ObjectAttributes);
    dprintf("\t\t\tStatus =%x\n",Status);
    if (Status == 0) {
        dprintf("NtQueryValueKey : ");
        RtlRosInitUnicodeStringFromLiteral(&KeyName, L"NameServer");
        Status = NtQueryValueKey(hKey, &KeyName, KeyValueFullInformation, &KeyValueInformation[0], sizeof(KeyValueInformation), &Length);
        dprintf("\t\t\t\tStatus =%x\n",Status);
        if (Status == STATUS_SUCCESS) {
            dprintf("\tValue:DO=%d, DL=%d, NL=%d, Name = "
                ,KeyValueInformation[0].DataOffset
                ,KeyValueInformation[0].DataLength
                ,KeyValueInformation[0].NameLength);
            for (i = 0; i < 10 && i < KeyValueInformation[0].NameLength / 2; i++)
                dprintf("%C", KeyValueInformation[0].Name[i]);
            dprintf("\n");
            dprintf("\t\tType = %d\n", KeyValueInformation[0].Type);
            if (KeyValueInformation[0].Type == REG_SZ)
                //dprintf("\t\tValue = %S\n", KeyValueInformation[0].Name + 1 + KeyValueInformation[0].NameLength / 2);
                dprintf("\t\tValue = %S\n", KeyValueInformation[0].Name + KeyValueInformation[0].NameLength / 2);
        }
        dprintf("NtEnumerateValueKey : \n");
        Index = 0;
        while (Status == STATUS_SUCCESS) {
            Status = NtEnumerateValueKey(hKey, Index++, KeyValueFullInformation, &KeyValueInformation[0], sizeof(KeyValueInformation), &Length);
            if (Status == STATUS_SUCCESS) {
                dprintf("\tValue:DO=%d, DL=%d, NL=%d, Name = "
                    ,KeyValueInformation[0].DataOffset
                    ,KeyValueInformation[0].DataLength
                    ,KeyValueInformation[0].NameLength);
                for (i = 0; i < KeyValueInformation[0].NameLength / 2; i++)
                    dprintf("%C", KeyValueInformation[0].Name[i]);
                dprintf(", Type = %d\n", KeyValueInformation[0].Type);
                if (KeyValueInformation[0].Type == REG_SZ)
                    dprintf("\t\tValue = %S\n", ((char*)&KeyValueInformation[0]+KeyValueInformation[0].DataOffset));
                if (KeyValueInformation[0].Type == REG_DWORD)
                    dprintf("\t\tValue = %X\n", *((DWORD*)((char*)&KeyValueInformation[0]+KeyValueInformation[0].DataOffset)));
            }
        }
        dprintf("NtClose : ");
        Status = NtClose(hKey);
        dprintf("\t\t\t\t\tStatus =%x\n", Status);
    }
    NtClose(hKey1);
}
Ejemplo n.º 29
0
NTSTATUS
BasepMoveFileDelayed(
    IN PUNICODE_STRING OldFileName,
    IN PUNICODE_STRING NewFileName
    )

/*++

Routine Description:

    Appends the given delayed move file operation to the registry
    value that contains the list of move file operations to be
    performed on the next boot.

Arguments:

    OldFileName - Supplies the old file name

    NewFileName - Supplies the new file name

Return Value:

    NTSTATUS

--*/

{
    OBJECT_ATTRIBUTES Obja;
    UNICODE_STRING KeyName;
    UNICODE_STRING ValueName;
    HANDLE KeyHandle;
    PWSTR ValueData, s;
    PKEY_VALUE_PARTIAL_INFORMATION ValueInfo;
    ULONG ValueLength = 1024;
    ULONG ReturnedLength;
    NTSTATUS Status;

    RtlInitUnicodeString( &KeyName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
    RtlInitUnicodeString( &ValueName, L"PendingFileRenameOperations" );
    InitializeObjectAttributes(
        &Obja,
        &KeyName,
        OBJ_OPENIF | OBJ_CASE_INSENSITIVE,
        NULL,
        NULL
        );

    Status = NtCreateKey( &KeyHandle,
                          GENERIC_READ | GENERIC_WRITE,
                          &Obja,
                          0,
                          NULL,
                          0,
                          NULL
                        );
    if ( Status == STATUS_ACCESS_DENIED ) {
        Status = NtCreateKey( &KeyHandle,
                              GENERIC_READ | GENERIC_WRITE,
                              &Obja,
                              0,
                              NULL,
                              REG_OPTION_BACKUP_RESTORE,
                              NULL
                            );
    }

    if (NT_SUCCESS( Status )) {

retry:
        ValueInfo = RtlAllocateHeap(RtlProcessHeap(),
                                    MAKE_TAG(TMP_TAG),
                                    ValueLength + OldFileName->Length + sizeof(WCHAR) +
                                                  NewFileName->Length + 2*sizeof(WCHAR));
        if (ValueInfo == NULL) {
            NtClose(KeyHandle);
            return(STATUS_NO_MEMORY);
        }

        //
        // File rename operations are stored in the registry in a
        // single MULTI_SZ value. This allows the renames to be
        // performed in the same order that they were originally
        // requested. Each rename operation consists of a pair of
        // NULL-terminated strings.
        //

        Status = NtQueryValueKey(KeyHandle,
                                 &ValueName,
                                 KeyValuePartialInformation,
                                 ValueInfo,
                                 ValueLength,
                                 &ReturnedLength);
        if (Status == STATUS_BUFFER_OVERFLOW) {
            //
            // The existing value is too large for our buffer.
            // Retry with a larger buffer.
            //
            ValueLength = ReturnedLength;
            RtlFreeHeap(RtlProcessHeap(), 0, ValueInfo);
            goto retry;
        }

        if (Status == STATUS_OBJECT_NAME_NOT_FOUND) {
            //
            // The value does not currently exist. Create the
            // value with our data.
            //
            s = ValueData = (PWSTR)ValueInfo;
        } else if (NT_SUCCESS(Status)) {
            //
            // A value already exists, append our two strings to the
            // MULTI_SZ.
            //
            ValueData = (PWSTR)(&ValueInfo->Data);
            s = (PWSTR)((PCHAR)ValueData + ValueInfo->DataLength) - 1;
        } else {
            NtClose(KeyHandle);
            RtlFreeHeap(RtlProcessHeap(), 0, ValueInfo);
            return(Status);
        }

        CopyMemory(s, OldFileName->Buffer, OldFileName->Length);
        s += (OldFileName->Length/sizeof(WCHAR));
        *s++ = L'\0';

        CopyMemory(s, NewFileName->Buffer, NewFileName->Length);
        s += (NewFileName->Length/sizeof(WCHAR));
        *s++ = L'\0';
        *s++ = L'\0';

        Status = NtSetValueKey(KeyHandle,
                               &ValueName,
                               0,
                               REG_MULTI_SZ,
                               ValueData,
                               (s-ValueData)*sizeof(WCHAR));
        NtClose(KeyHandle);
        RtlFreeHeap(RtlProcessHeap(), 0, ValueInfo);
    }

    return(Status);
}
Ejemplo n.º 30
0
NTSTATUS
LsapAdtInitializeCrashOnFail(
    VOID
    )

/*++

Routine Description:

    Reads the registry to see if the user has told us to crash if an audit fails.

Arguments:

    None.

Return Value:

    STATUS_SUCCESS

--*/

{
    HANDLE KeyHandle;
    NTSTATUS Status;
    NTSTATUS TmpStatus;
    OBJECT_ATTRIBUTES Obja;
    ULONG ResultLength;
    UNICODE_STRING KeyName;
    UNICODE_STRING ValueName;
    CHAR KeyInfo[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(BOOLEAN)];
    PKEY_VALUE_PARTIAL_INFORMATION pKeyInfo;

    //
    // Check the value of the CrashOnAudit key.
    //

    RtlInitUnicodeString( &KeyName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Lsa");

    InitializeObjectAttributes( &Obja,
                                &KeyName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                                );

    Status = NtOpenKey(
                 &KeyHandle,
                 KEY_QUERY_VALUE | KEY_SET_VALUE,
                 &Obja
                 );


    if (Status == STATUS_OBJECT_NAME_NOT_FOUND) {
        LsapCrashOnAuditFail = FALSE;
        return( STATUS_SUCCESS );
    }

    RtlInitUnicodeString( &ValueName, CRASH_ON_AUDIT_FAIL_VALUE );

    Status = NtQueryValueKey(
                 KeyHandle,
                 &ValueName,
                 KeyValuePartialInformation,
                 KeyInfo,
                 sizeof(KeyInfo),
                 &ResultLength
                 );

    TmpStatus = NtClose(KeyHandle);
    ASSERT(NT_SUCCESS(TmpStatus));

    //
    // If it's not found, don't enable CrashOnFail.
    //

    if (!NT_SUCCESS( Status )) {

        LsapCrashOnAuditFail = FALSE;

    } else {

        //
        // Check the value of the CrashOnFail value. If it is 1, we
        // crash on audit fail. If it is two, we only allow admins to
        // logon.
        //

        pKeyInfo = (PKEY_VALUE_PARTIAL_INFORMATION)KeyInfo;
        if (*(pKeyInfo->Data) == LSAP_CRASH_ON_AUDIT_FAIL) {
            LsapCrashOnAuditFail = TRUE;
        } else if (*(pKeyInfo->Data) == LSAP_ALLOW_ADIMIN_LOGONS_ONLY) {
            LsapAllowAdminLogonsOnly = TRUE;
        }

    }

    if ( LsapCrashOnAuditFail ) {

        BOOLEAN WasEnabled;

        Status = RtlAdjustPrivilege(
                     SE_SHUTDOWN_PRIVILEGE,
                     TRUE,
                     FALSE,
                     &WasEnabled
                     );

        //
        // This had better work.
        //

        ASSERT(NT_SUCCESS(Status));

        return( Status );

    }

    return( STATUS_SUCCESS );
}