예제 #1
0
bool GetCommandLine(DWORD dwPid, LPWSTR lpwstr)
{
	bool fSuccess = false;
	HANDLE hProcess = NULL;

	hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPid);
	if (NULL != hProcess)
	{
		PROCESS_BASIC_INFORMATION pbi = { 0 };

		NTSTATUS status = NtQueryInformationProcess(
			hProcess,
			ProcessBasicInformation,
			&pbi,
			sizeof(pbi),
			NULL
			);
		if (NT_SUCCESS(status) && NULL != pbi.PebBaseAddress)
		{
			PEB_ peb = { 0 };
			if (::ReadProcessMemory(
				hProcess,
				pbi.PebBaseAddress,
				&peb,
				sizeof(peb),
				NULL
				))
			{
				RTL_USER_PROCESS_PARAMETERS params = { 0 };
				if (::ReadProcessMemory(
					hProcess,
					peb.ProcessParameters,
					&params,
					sizeof(params),
					NULL
					)
					&& params.CommandLine.Length > 0
					)
				{
					if (params.CommandLine.Length > MAX_COMMANDLINE_LENGTH)
						printf("CommandLine Length : %d > MAX_COMMANDLINE_LENGTH(%d)\n", params.CommandLine.Length, MAX_COMMANDLINE_LENGTH);

					if (::ReadProcessMemory(
						hProcess,
						params.CommandLine.Buffer,
						lpwstr,
						MAX_COMMANDLINE_LENGTH,
						NULL
						))
					{
						fSuccess = true;
					}
				}
			}
		}

		::CloseHandle(hProcess);
	}

	return fSuccess;
}
예제 #2
0
PGRAPHICS_DEVICE
NTAPI
InitDisplayDriver(
    IN PWSTR pwszDeviceName,
    IN PWSTR pwszRegKey)
{
    PGRAPHICS_DEVICE pGraphicsDevice;
    UNICODE_STRING ustrDeviceName, ustrDisplayDrivers, ustrDescription;
    NTSTATUS Status;
    WCHAR awcBuffer[128];
    ULONG cbSize;
    HKEY hkey;
    DEVMODEW dmDefault;

    ERR("InitDisplayDriver(%S, %S);\n",
            pwszDeviceName, pwszRegKey);

    /* Open the driver's registry key */
    Status = RegOpenKey(pwszRegKey, &hkey);
    if (!NT_SUCCESS(Status))
    {
        ERR("Failed to open registry key: %ls\n", pwszRegKey);
        return NULL;
    }

    /* Query the diplay drivers */
    cbSize = sizeof(awcBuffer) - 10;
    Status = RegQueryValue(hkey,
                           L"InstalledDisplayDrivers",
                           REG_MULTI_SZ,
                           awcBuffer,
                           &cbSize);
    if (!NT_SUCCESS(Status))
    {
        ERR("Didn't find 'InstalledDisplayDrivers', status = 0x%lx\n", Status);
        ZwClose(hkey);
        return NULL;
    }

    /* Initialize the UNICODE_STRING */
    ustrDisplayDrivers.Buffer = awcBuffer;
    ustrDisplayDrivers.MaximumLength = cbSize;
    ustrDisplayDrivers.Length = cbSize;

    /* Set Buffer for description and size of remaining buffer */
    ustrDescription.Buffer = awcBuffer + (cbSize / sizeof(WCHAR));
    cbSize = sizeof(awcBuffer) - cbSize;

    /* Query the device string */
    Status = RegQueryValue(hkey,
                           L"Device Description",
                           REG_SZ,
                           ustrDescription.Buffer,
                           &cbSize);
    if (NT_SUCCESS(Status))
    {
        ustrDescription.MaximumLength = cbSize;
        ustrDescription.Length = cbSize;
    }
    else
    {
        RtlInitUnicodeString(&ustrDescription, L"<unknown>");
    }

    /* Query the default settings */
    RegReadDisplaySettings(hkey, &dmDefault);

    /* Close the registry key */
    ZwClose(hkey);

    /* Register the device with GDI */
    RtlInitUnicodeString(&ustrDeviceName, pwszDeviceName);
    pGraphicsDevice = EngpRegisterGraphicsDevice(&ustrDeviceName,
                                                 &ustrDisplayDrivers,
                                                 &ustrDescription,
                                                 &dmDefault);

    return pGraphicsDevice;
}
예제 #3
0
NTSTATUS
DriverEntry(
    IN PDRIVER_OBJECT   pDriverObject,
    IN PUNICODE_STRING  pRegistryPath
    )
/*++

Routine Description:

    Called on loading. We create a device object to handle user-mode requests
    on, and register ourselves as a protocol with NDIS.

Arguments:

    pDriverObject - Pointer to driver object created by system.

    pRegistryPath - Pointer to the Unicode name of the registry path
        for this driver.

Return Value:

    NT Status code
    
--*/
{
    NDIS_PROTOCOL_DRIVER_CHARACTERISTICS   protocolChar = {0};
    NTSTATUS                        status = STATUS_SUCCESS;
    NDIS_STRING                     protoName = NDIS_STRING_CONST("NDISPROT");     
    UNICODE_STRING                  ntDeviceName;
    UNICODE_STRING                  win32DeviceName;
    BOOLEAN                         fSymbolicLink = FALSE;
    PDEVICE_OBJECT                  deviceObject = NULL;
    NDIS_HANDLE  ProtocolDriverContext={0};

    UNREFERENCED_PARAMETER(pRegistryPath);
	
    DEBUGP(DL_LOUD, ("DriverEntry\n"));

    Globals.pDriverObject = pDriverObject;
    Globals.EthType = NPROT_ETH_TYPE;
    NPROT_INIT_EVENT(&Globals.BindsComplete);

    do
    {
        //
        // Create our device object using which an application can
        // access NDIS devices.
        //
        RtlInitUnicodeString(&ntDeviceName, NT_DEVICE_NAME);

        status = IoCreateDevice (pDriverObject,
                                 0,
                                 &ntDeviceName,
                                 FILE_DEVICE_NETWORK,
                                 FILE_DEVICE_SECURE_OPEN,
                                 FALSE,
                                 &deviceObject);
    
        if (!NT_SUCCESS (status))
        {
            //
            // Either not enough memory to create a deviceobject or another
            // deviceobject with the same name exits. This could happen
            // if you install another instance of this device.
            //
            break;
        }

        RtlInitUnicodeString(&win32DeviceName, DOS_DEVICE_NAME);

        status = IoCreateSymbolicLink(&win32DeviceName, &ntDeviceName);

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

        fSymbolicLink = TRUE;
    
        deviceObject->Flags |= DO_DIRECT_IO;
        Globals.ControlDeviceObject = deviceObject;

        NPROT_INIT_LIST_HEAD(&Globals.OpenList);
        NPROT_INIT_LOCK(&Globals.GlobalLock);

        //
        // Initialize the protocol characterstic structure
        //     
#if (NDIS_SUPPORT_NDIS630)
        {C_ASSERT(sizeof(protocolChar) >= NDIS_SIZEOF_PROTOCOL_DRIVER_CHARACTERISTICS_REVISION_2);}
        protocolChar.Header.Type        = NDIS_OBJECT_TYPE_PROTOCOL_DRIVER_CHARACTERISTICS,
        protocolChar.Header.Size        = NDIS_SIZEOF_PROTOCOL_DRIVER_CHARACTERISTICS_REVISION_2;
        protocolChar.Header.Revision    = NDIS_PROTOCOL_DRIVER_CHARACTERISTICS_REVISION_2;
#elif (NDIS_SUPPORT_NDIS6)
        {C_ASSERT(sizeof(protocolChar) >= NDIS_SIZEOF_PROTOCOL_DRIVER_CHARACTERISTICS_REVISION_1);}
        protocolChar.Header.Type        = NDIS_OBJECT_TYPE_PROTOCOL_DRIVER_CHARACTERISTICS,
        protocolChar.Header.Size        = NDIS_SIZEOF_PROTOCOL_DRIVER_CHARACTERISTICS_REVISION_1;
        protocolChar.Header.Revision    = NDIS_PROTOCOL_DRIVER_CHARACTERISTICS_REVISION_1;
#endif // NDIS MINIPORT VERSION

        protocolChar.MajorNdisVersion            = NDIS_PROT_MAJOR_VERSION;
        protocolChar.MinorNdisVersion            = NDIS_PROT_MINOR_VERSION;
        protocolChar.MajorDriverVersion          = MAJOR_DRIVER_VERSION;
        protocolChar.MinorDriverVersion          = MINOR_DRIVER_VERISON;
        protocolChar.Name                        = protoName;
        protocolChar.SetOptionsHandler           = NULL;
        protocolChar.OpenAdapterCompleteHandlerEx  = NdisprotOpenAdapterComplete;
        protocolChar.CloseAdapterCompleteHandlerEx = NdisprotCloseAdapterComplete;
        protocolChar.SendNetBufferListsCompleteHandler = NdisprotSendComplete;
        protocolChar.OidRequestCompleteHandler   = NdisprotRequestComplete;
        protocolChar.StatusHandlerEx             = NdisprotStatus;
        protocolChar.UninstallHandler            = NULL;
        protocolChar.ReceiveNetBufferListsHandler = NdisprotReceiveNetBufferLists;
        protocolChar.NetPnPEventHandler          = NdisprotPnPEventHandler;
        protocolChar.BindAdapterHandlerEx        = NdisprotBindAdapter;
        protocolChar.UnbindAdapterHandlerEx      = NdisprotUnbindAdapter;

        //
        // Register as a protocol driver
        //
    
        status = NdisRegisterProtocolDriver(ProtocolDriverContext,           // driver context
                                            &protocolChar,
                                            &Globals.NdisProtocolHandle);

        if (status != NDIS_STATUS_SUCCESS)
        {
            DEBUGP(DL_WARN, ("Failed to register protocol with NDIS\n"));
            status = STATUS_UNSUCCESSFUL;
            break;
        }

        Globals.PartialCancelId = NdisGeneratePartialCancelId();
        Globals.PartialCancelId <<= ((sizeof(PVOID) - 1) * 8);
        DEBUGP(DL_LOUD, ("DriverEntry: CancelId %lx\n", Globals.PartialCancelId));

        //
        // Now set only the dispatch points we would like to handle.
        //

        pDriverObject->MajorFunction[IRP_MJ_CREATE] = NdisprotOpen;

        pDriverObject->MajorFunction[IRP_MJ_CLOSE]  = NdisprotClose;

        pDriverObject->MajorFunction[IRP_MJ_READ]   = NdisprotRead;

        pDriverObject->MajorFunction[IRP_MJ_WRITE]  = NdisprotWrite;

        pDriverObject->MajorFunction[IRP_MJ_CLEANUP]  = NdisprotCleanup;

        pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL]  = NdisprotIoControl;
        

        pDriverObject->DriverUnload = NdisprotUnload;

        status = STATUS_SUCCESS;

        
    }
    while (FALSE);
       

    if (!NT_SUCCESS(status))
    {
        if (deviceObject)
        {
            KeEnterCriticalRegion();
            IoDeleteDevice(deviceObject);
            KeLeaveCriticalRegion();
            Globals.ControlDeviceObject = NULL;
        }

        if (fSymbolicLink)
        {
            IoDeleteSymbolicLink(&win32DeviceName);
            fSymbolicLink = FALSE;
        }
        
        if (Globals.NdisProtocolHandle)
        {
            NdisDeregisterProtocolDriver(Globals.NdisProtocolHandle);
            Globals.NdisProtocolHandle = NULL;
        }        
    }
    
    return status;
}
예제 #4
0
파일: smsbapi.c 프로젝트: RareHare/reactos
NTSTATUS
NTAPI
SmpSbCreateSession(IN PVOID Reserved,
                   IN PSMP_SUBSYSTEM OtherSubsystem,
                   IN PRTL_USER_PROCESS_INFORMATION ProcessInformation,
                   IN ULONG MuSessionId,
                   IN PCLIENT_ID DbgClientId)
{
    NTSTATUS Status;
    PSMP_SUBSYSTEM KnownSubsys;
    SB_API_MSG SbApiMsg;
    ULONG SessionId;
    PSB_CREATE_SESSION_MSG CreateSessionMsg;

    /* Write out the create session message including its initial process */
    CreateSessionMsg = &SbApiMsg.CreateSession;
    CreateSessionMsg->ProcessInfo = *ProcessInformation;
    CreateSessionMsg->MuSessionId = MuSessionId;
    if (DbgClientId)
    {
        CreateSessionMsg->ClientId = *DbgClientId;
    }
    else
    {
        CreateSessionMsg->ClientId.UniqueThread = NULL;
        CreateSessionMsg->ClientId.UniqueProcess = NULL;
    }

    /* Find a subsystem responsible for this session */
    SmpGetProcessMuSessionId(ProcessInformation->ProcessHandle, &MuSessionId);
    if (!SmpCheckDuplicateMuSessionId(MuSessionId))
    {
        NtClose(ProcessInformation->ProcessHandle);
        NtClose(ProcessInformation->ThreadHandle);
        DPRINT1("SMSS: CreateSession status=%x\n", STATUS_OBJECT_NAME_NOT_FOUND);
        return STATUS_OBJECT_NAME_NOT_FOUND;
    }

    /* Find the subsystem we have for this initial process */
    KnownSubsys = SmpLocateKnownSubSysByType(MuSessionId,
                                             ProcessInformation->
                                             ImageInformation.SubSystemType);
    if (KnownSubsys)
    {
        /* Duplicate the process handle into the message */
        Status = NtDuplicateObject(NtCurrentProcess(),
                                   ProcessInformation->ProcessHandle,
                                   KnownSubsys->ProcessHandle,
                                   &CreateSessionMsg->ProcessInfo.ProcessHandle,
                                   PROCESS_ALL_ACCESS,
                                   0,
                                   0);
        if (NT_SUCCESS(Status))
        {
            /* Duplicate the thread handle into the message */
            Status = NtDuplicateObject(NtCurrentProcess(),
                                       ProcessInformation->ThreadHandle,
                                       KnownSubsys->ProcessHandle,
                                       &CreateSessionMsg->ProcessInfo.ThreadHandle,
                                       THREAD_ALL_ACCESS,
                                       0,
                                       0);
            if (!NT_SUCCESS(Status))
            {
                /* Close everything on failure */
                NtClose(ProcessInformation->ProcessHandle);
                NtClose(ProcessInformation->ThreadHandle);
                SmpDereferenceSubsystem(KnownSubsys);
                DbgPrint("SmpSbCreateSession: NtDuplicateObject (Thread) Failed %lx\n", Status);
                return Status;
            }

            /* Close the original handles as they are no longer needed */
            NtClose(ProcessInformation->ProcessHandle);
            NtClose(ProcessInformation->ThreadHandle);

            /* Finally, allocate a new SMSS session ID for this session */
            SessionId = SmpAllocateSessionId(KnownSubsys, OtherSubsystem);
            CreateSessionMsg->SessionId = SessionId;

            /* Fill out the LPC message header and send it to the client! */
            SbApiMsg.ApiNumber = SbpCreateSession;
            SbApiMsg.h.u2.ZeroInit = 0;
            SbApiMsg.h.u1.s1.DataLength = sizeof(SB_CREATE_SESSION_MSG) + 8;
            SbApiMsg.h.u1.s1.TotalLength = sizeof(SbApiMsg);
            Status = NtRequestWaitReplyPort(KnownSubsys->SbApiPort,
                                            &SbApiMsg.h,
                                            &SbApiMsg.h);
            if (!NT_SUCCESS(Status))
            {
                /* Bail out */
                DPRINT1("SmpSbCreateSession: NtRequestWaitReply Failed %lx\n", Status);
            }
            else
            {
                /* If the API succeeded, get the result value from the LPC */
                Status = SbApiMsg.ReturnValue;
            }

            /* Delete the session on any kind of failure */
            if (!NT_SUCCESS(Status)) SmpDeleteSession(SessionId);
        }
        else
        {
            /* Close the handles on failure */
            DPRINT1("SmpSbCreateSession: NtDuplicateObject (Process) Failed %lx\n", Status);
            NtClose(ProcessInformation->ProcessHandle);
            NtClose(ProcessInformation->ThreadHandle);
        }

        /* Dereference the subsystem and return the status of the LPC call */
        SmpDereferenceSubsystem(KnownSubsys);
        return Status;
    }

    /* If we don't yet have a subsystem, only native images can be launched */
    if (ProcessInformation->ImageInformation.SubSystemType != IMAGE_SUBSYSTEM_NATIVE)
    {
        /* Fail */
        DPRINT1("SMSS: %s SubSystem has not been started.\n",
                SmpSubSystemNames[ProcessInformation->ImageInformation.SubSystemType]);
        Status = STATUS_UNSUCCESSFUL;
        NtClose(ProcessInformation->ProcessHandle);
        NtClose(ProcessInformation->ThreadHandle);
        return Status;
    }

#if 0
    /* This code handles debug applications, but it seems vestigial... */
    if ((*(ULONGLONG)&CreateSessionMsg.ClientId) && (SmpDbgSsLoaded))
    {
        Process = RtlAllocateHeap(SmpHeap, SmBaseTag, sizeof(SMP_PROCESS));
        if (!Process)
        {
            DPRINT1("Unable to initialize debugging for Native App %lx.%lx -- out of memory\n",
                    ProcessInformation->ClientId.UniqueProcess,
                    ProcessInformation->ClientId.UniqueThread);
            NtClose(ProcessInformation->ProcessHandle);
            NtClose(ProcessInformation->ThreadHandle);
            return STATUS_NO_MEMORY;
        }

        Process->DbgClientId = CreateSessionMsg->ClientId;
        Process->ClientId = ProcessInformation->ClientId;
        InsertHeadList(&NativeProcessList, &Process->Entry);
        DPRINT1("Native Debug App %lx.%lx\n", Process->ClientId.UniqueProcess, Process->ClientId.UniqueThread);

        Status = NtSetInformationProcess(ProcessInformation->ProcessHandle, 7, &SmpDebugPort, 4);
        ASSERT(NT_SUCCESS(Status));
    }
#endif

    /* This is a native application being started as the initial command */
    DPRINT1("Subsystem active, starting thread\n");
    NtClose(ProcessInformation->ProcessHandle);
    NtResumeThread(ProcessInformation->ThreadHandle, NULL);
    NtClose(ProcessInformation->ThreadHandle);
    return STATUS_SUCCESS;
}
예제 #5
0
//NTSTATUS
BOOL
NTAPI
NtUserEnumDisplayDevices(
    PUNICODE_STRING pustrDevice,
    DWORD iDevNum,
    PDISPLAY_DEVICEW pDisplayDevice,
    DWORD dwFlags)
{
    UNICODE_STRING ustrDevice;
    WCHAR awcDevice[CCHDEVICENAME];
    DISPLAY_DEVICEW dispdev;
    NTSTATUS Status;

    TRACE("Enter NtUserEnumDisplayDevices(%wZ, %ld)\n",
           pustrDevice, iDevNum);

    // FIXME: HACK, desk.cpl passes broken crap
    if (pustrDevice && iDevNum != 0)
        return FALSE;

    dispdev.cb = sizeof(dispdev);

    if (pustrDevice)
    {
        /* Initialize destination string */
        RtlInitEmptyUnicodeString(&ustrDevice, awcDevice, sizeof(awcDevice));

        _SEH2_TRY
        {
            /* Probe the UNICODE_STRING and the buffer */
            ProbeForRead(pustrDevice, sizeof(UNICODE_STRING), 1);
            ProbeForRead(pustrDevice->Buffer, pustrDevice->Length, 1);

            /* Copy the string */
            RtlCopyUnicodeString(&ustrDevice, pustrDevice);
        }
        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
        {
//            _SEH2_YIELD(return _SEH2_GetExceptionCode());
            _SEH2_YIELD(return NT_SUCCESS(_SEH2_GetExceptionCode()));
        }
        _SEH2_END

        if (ustrDevice.Length > 0)
            pustrDevice = &ustrDevice;
        else
            pustrDevice = NULL;
   }

    /* Acquire global USER lock */
    UserEnterExclusive();

    /* Call the internal function */
    Status = UserEnumDisplayDevices(pustrDevice, iDevNum, &dispdev, dwFlags);

    /* Release lock */
    UserLeave();

    /* On success copy data to caller */
    if (NT_SUCCESS(Status))
    {
        /* Enter SEH */
        _SEH2_TRY
        {
            /* First probe the cb field */
            ProbeForWrite(&pDisplayDevice->cb, sizeof(DWORD), 1);

            /* Check the buffer size */
            if (pDisplayDevice->cb)
            {
                /* Probe the output buffer */
                pDisplayDevice->cb = min(pDisplayDevice->cb, sizeof(dispdev));
                ProbeForWrite(pDisplayDevice, pDisplayDevice->cb, 1);

                /* Copy as much as the given buffer allows */
                RtlCopyMemory(pDisplayDevice, &dispdev, pDisplayDevice->cb);
            }
        }
        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
        {
            Status = _SEH2_GetExceptionCode();
        }
        _SEH2_END
    }

    ERR("Leave NtUserEnumDisplayDevices, Status = 0x%lx\n", Status);
    /* Return the result */
//    return Status;
    return NT_SUCCESS(Status); // FIXME
}
예제 #6
0
/*
 * @unimplemented
 */
NTSTATUS
NTAPI
LsaApLogonUser(IN PLSA_CLIENT_REQUEST ClientRequest,
               IN SECURITY_LOGON_TYPE LogonType,
               IN PVOID AuthenticationInformation,
               IN PVOID ClientAuthenticationBase,
               IN ULONG AuthenticationInformationLength,
               OUT PVOID *ProfileBuffer,
               OUT PULONG ProfileBufferLength,
               OUT PLUID LogonId,
               OUT PNTSTATUS SubStatus,
               OUT PLSA_TOKEN_INFORMATION_TYPE TokenInformationType,
               OUT PVOID *TokenInformation,
               OUT PLSA_UNICODE_STRING *AccountName,
               OUT PLSA_UNICODE_STRING *AuthenticatingAuthority)
{
    PMSV1_0_INTERACTIVE_LOGON LogonInfo;

    SAMPR_HANDLE ServerHandle = NULL;
    SAMPR_HANDLE DomainHandle = NULL;
    SAMPR_HANDLE UserHandle = NULL;
    PRPC_SID AccountDomainSid = NULL;
    RPC_UNICODE_STRING Names[1];
    SAMPR_ULONG_ARRAY RelativeIds = {0, NULL};
    SAMPR_ULONG_ARRAY Use = {0, NULL};
    PSAMPR_USER_INFO_BUFFER UserInfo = NULL;
    UNICODE_STRING LogonServer;
    BOOLEAN SessionCreated = FALSE;
    NTSTATUS Status;

    TRACE("()\n");

    TRACE("LogonType: %lu\n", LogonType);
    TRACE("AuthenticationInformation: %p\n", AuthenticationInformation);
    TRACE("AuthenticationInformationLength: %lu\n", AuthenticationInformationLength);

    *ProfileBuffer = NULL;
    *ProfileBufferLength = 0;
    *SubStatus = STATUS_SUCCESS;

    if (LogonType == Interactive ||
        LogonType == Batch ||
        LogonType == Service)
    {
        ULONG_PTR PtrOffset;

        LogonInfo = (PMSV1_0_INTERACTIVE_LOGON)AuthenticationInformation;

        /* Fix-up pointers in the authentication info */
        PtrOffset = (ULONG_PTR)AuthenticationInformation - (ULONG_PTR)ClientAuthenticationBase;

        LogonInfo->LogonDomainName.Buffer = FIXUP_POINTER(LogonInfo->LogonDomainName.Buffer, PtrOffset);
        LogonInfo->UserName.Buffer = FIXUP_POINTER(LogonInfo->UserName.Buffer, PtrOffset);
        LogonInfo->Password.Buffer = FIXUP_POINTER(LogonInfo->Password.Buffer, PtrOffset);

        TRACE("Domain: %S\n", LogonInfo->LogonDomainName.Buffer);
        TRACE("User: %S\n", LogonInfo->UserName.Buffer);
        TRACE("Password: %S\n", LogonInfo->Password.Buffer);

        RtlInitUnicodeString(&LogonServer, L"Testserver");
    }
    else
    {
        FIXME("LogonType %lu is not supported yet!\n", LogonType);
        return STATUS_NOT_IMPLEMENTED;
    }

    Status = GetDomainSid(&AccountDomainSid);
    if (!NT_SUCCESS(Status))
    {
        TRACE("GetDomainSid() failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    /* Connect to the SAM server */
    Status = SamIConnect(NULL,
                         &ServerHandle,
                         SAM_SERVER_CONNECT | SAM_SERVER_LOOKUP_DOMAIN,
                         TRUE);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamIConnect() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    /* Open the account domain */
    Status = SamrOpenDomain(ServerHandle,
                            DOMAIN_LOOKUP,
                            AccountDomainSid,
                            &DomainHandle);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrOpenDomain failed (Status %08lx)\n", Status);
        goto done;
    }

    Names[0].Length = LogonInfo->UserName.Length;
    Names[0].MaximumLength = LogonInfo->UserName.MaximumLength;
    Names[0].Buffer = LogonInfo->UserName.Buffer;

    /* Try to get the RID for the user name */
    Status = SamrLookupNamesInDomain(DomainHandle,
                                     1,
                                     Names,
                                     &RelativeIds,
                                     &Use);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrLookupNamesInDomain failed (Status %08lx)\n", Status);
        Status = STATUS_NO_SUCH_USER;
        goto done;
    }

    /* Fail, if it is not a user account */
    if (Use.Element[0] != SidTypeUser)
    {
        TRACE("Account is not a user account!\n");
        Status = STATUS_NO_SUCH_USER;
        goto done;
    }

    /* Open the user object */
    Status = SamrOpenUser(DomainHandle,
                          USER_READ_GENERAL | USER_READ_LOGON |
                          USER_READ_ACCOUNT | USER_READ_PREFERENCES, /* FIXME */
                          RelativeIds.Element[0],
                          &UserHandle);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrOpenUser failed (Status %08lx)\n", Status);
        goto done;
    }

    Status = SamrQueryInformationUser(UserHandle,
                                      UserAllInformation,
                                      &UserInfo);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrQueryInformationUser failed (Status %08lx)\n", Status);
        goto done;
    }


    TRACE("UserName: %S\n", UserInfo->All.UserName.Buffer);

    /* FIXME: Check restrictions */

    /* Check the password */
    if ((UserInfo->All.UserAccountControl & USER_PASSWORD_NOT_REQUIRED) == 0)
    {
        Status = MsvpCheckPassword(&(LogonInfo->Password),
                                   UserInfo);
        if (!NT_SUCCESS(Status))
        {
            TRACE("MsvpCheckPassword failed (Status %08lx)\n", Status);
            goto done;
        }
    }

    /* Return logon information */

    /* Create and return a new logon id */
    Status = NtAllocateLocallyUniqueId(LogonId);
    if (!NT_SUCCESS(Status))
    {
        TRACE("NtAllocateLocallyUniqueId failed (Status %08lx)\n", Status);
        goto done;
    }

    /* Create the logon session */
    Status = DispatchTable.CreateLogonSession(LogonId);
    if (!NT_SUCCESS(Status))
    {
        TRACE("CreateLogonSession failed (Status %08lx)\n", Status);
        goto done;
    }

    SessionCreated = TRUE;

    /* Build and fill the interactve profile buffer */
    Status = BuildInteractiveProfileBuffer(ClientRequest,
                                           UserInfo,
                                           &LogonServer,
                                           (PMSV1_0_INTERACTIVE_PROFILE*)ProfileBuffer,
                                           ProfileBufferLength);
    if (!NT_SUCCESS(Status))
    {
        TRACE("BuildInteractiveProfileBuffer failed (Status %08lx)\n", Status);
        goto done;
    }

    /* Return the token information type */
    *TokenInformationType = LsaTokenInformationV1;

    /* Build and fill the token information buffer */
    Status = BuildTokenInformationBuffer((PLSA_TOKEN_INFORMATION_V1*)TokenInformation,
                                         AccountDomainSid,
                                         UserInfo);
    if (!NT_SUCCESS(Status))
    {
        TRACE("BuildTokenInformationBuffer failed (Status %08lx)\n", Status);
        goto done;
    }

done:
    /* Return the account name */
    *AccountName = DispatchTable.AllocateLsaHeap(sizeof(UNICODE_STRING));
    if (*AccountName != NULL)
    {
        (*AccountName)->Buffer = DispatchTable.AllocateLsaHeap(LogonInfo->UserName.Length +
                                                               sizeof(UNICODE_NULL));
        if ((*AccountName)->Buffer != NULL)
        {
            (*AccountName)->MaximumLength = LogonInfo->UserName.Length +
                                            sizeof(UNICODE_NULL);
            RtlCopyUnicodeString(*AccountName, &LogonInfo->UserName);
        }
    }

    if (!NT_SUCCESS(Status))
    {
        if (SessionCreated == TRUE)
            DispatchTable.DeleteLogonSession(LogonId);

        if (*ProfileBuffer != NULL)
        {
            DispatchTable.FreeClientBuffer(ClientRequest,
                                           *ProfileBuffer);
            *ProfileBuffer = NULL;
        }
    }

    if (UserHandle != NULL)
        SamrCloseHandle(&UserHandle);

    SamIFree_SAMPR_USER_INFO_BUFFER(UserInfo,
                                    UserAllInformation);
    SamIFree_SAMPR_ULONG_ARRAY(&RelativeIds);
    SamIFree_SAMPR_ULONG_ARRAY(&Use);

    if (DomainHandle != NULL)
        SamrCloseHandle(&DomainHandle);

    if (ServerHandle != NULL)
        SamrCloseHandle(&ServerHandle);

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

    if (Status == STATUS_NO_SUCH_USER ||
        Status == STATUS_WRONG_PASSWORD)
    {
        *SubStatus = Status;
        Status = STATUS_LOGON_FAILURE;
    }

    TRACE("LsaApLogonUser done (Status %08lx)\n", Status);

    return Status;
}
예제 #7
0
INT_PTR CALLBACK PhpEventPairPageProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
)
{
    PCOMMON_PAGE_CONTEXT pageContext;

    pageContext = PhpCommonPageHeader(hwndDlg, uMsg, wParam, lParam);

    if (!pageContext)
        return FALSE;

    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        // Nothing
    }
    break;
    case WM_COMMAND:
    {
        switch (LOWORD(wParam))
        {
        case IDC_SETLOW:
        case IDC_SETHIGH:
        {
            NTSTATUS status;
            HANDLE eventPairHandle;

            if (NT_SUCCESS(status = pageContext->OpenObject(
                                        &eventPairHandle,
                                        EVENT_PAIR_ALL_ACCESS,
                                        pageContext->Context
                                    )))
            {
                switch (LOWORD(wParam))
                {
                case IDC_SETLOW:
                    NtSetLowEventPair(eventPairHandle);
                    break;
                case IDC_SETHIGH:
                    NtSetHighEventPair(eventPairHandle);
                    break;
                }

                NtClose(eventPairHandle);
            }

            if (!NT_SUCCESS(status))
                PhShowStatus(hwndDlg, L"Unable to open the event pair", status, 0);
        }
        break;
        }
    }
    break;
    }

    return FALSE;
}
예제 #8
0
NTSTATUS
CmiAddValueKey(
	IN PCMHIVE RegistryHive,
	IN PCM_KEY_NODE KeyCell,
	IN HCELL_INDEX KeyCellOffset,
	IN PCUNICODE_STRING ValueName,
	OUT PCM_KEY_VALUE *pValueCell,
	OUT HCELL_INDEX *pValueCellOffset)
{
	PVALUE_LIST_CELL ValueListCell;
	PCM_KEY_VALUE NewValueCell;
	HCELL_INDEX ValueListCellOffset;
	HCELL_INDEX NewValueCellOffset;
	ULONG CellSize;
	HSTORAGE_TYPE Storage;
	NTSTATUS Status;

	Storage = (KeyCell->Flags & KEY_IS_VOLATILE) ? Volatile : Stable;
	if (KeyCell->ValueList.List == HCELL_NIL)
	{
		/* Allocate some room for the value list */
		CellSize = sizeof(VALUE_LIST_CELL) + (3 * sizeof(HCELL_INDEX));
		ValueListCellOffset = HvAllocateCell(&RegistryHive->Hive, CellSize, Storage, HCELL_NIL);
		if (ValueListCellOffset == HCELL_NIL)
			return STATUS_INSUFFICIENT_RESOURCES;

		ValueListCell = (PVALUE_LIST_CELL)HvGetCell(&RegistryHive->Hive, ValueListCellOffset);
		if (!ValueListCell)
			return STATUS_UNSUCCESSFUL;
		KeyCell->ValueList.List = ValueListCellOffset;
		HvMarkCellDirty(&RegistryHive->Hive, KeyCellOffset, FALSE);
	}
	else
	{
		ValueListCell = (PVALUE_LIST_CELL)HvGetCell(&RegistryHive->Hive, KeyCell->ValueList.List);
		if (!ValueListCell)
			return STATUS_UNSUCCESSFUL;
		CellSize = ABS_VALUE(HvGetCellSize(&RegistryHive->Hive, ValueListCell));

		if (KeyCell->ValueList.Count >= CellSize / sizeof(HCELL_INDEX))
		{
			CellSize *= 2;
			ValueListCellOffset = HvReallocateCell(&RegistryHive->Hive, KeyCell->ValueList.List, CellSize);
			if (ValueListCellOffset == HCELL_NIL)
				return STATUS_INSUFFICIENT_RESOURCES;

			ValueListCell = (PVALUE_LIST_CELL)HvGetCell(&RegistryHive->Hive, ValueListCellOffset);
			if (!ValueListCell)
				return STATUS_UNSUCCESSFUL;
			KeyCell->ValueList.List = ValueListCellOffset;
			HvMarkCellDirty(&RegistryHive->Hive, KeyCellOffset, FALSE);
        }
	}

	Status = CmiAllocateValueCell(
		RegistryHive,
		&NewValueCell,
		&NewValueCellOffset,
		ValueName,
		Storage);
	if (!NT_SUCCESS(Status))
		return Status;

	ValueListCell->ValueOffset[KeyCell->ValueList.Count] = NewValueCellOffset;
	KeyCell->ValueList.Count++;

	HvMarkCellDirty(&RegistryHive->Hive, KeyCellOffset, FALSE);
	HvMarkCellDirty(&RegistryHive->Hive, KeyCell->ValueList.List, FALSE);
	HvMarkCellDirty(&RegistryHive->Hive, NewValueCellOffset, FALSE);

	*pValueCell = NewValueCell;
	*pValueCellOffset = NewValueCellOffset;

	return STATUS_SUCCESS;
}
예제 #9
0
파일: dirctl.c 프로젝트: hoangduit/reactos
NTSTATUS
NtfsQueryDirectory(PNTFS_IRP_CONTEXT IrpContext)
{
    PIRP Irp;
    PDEVICE_OBJECT DeviceObject;
    PDEVICE_EXTENSION DeviceExtension;
    LONG BufferLength = 0;
    PUNICODE_STRING SearchPattern = NULL;
    FILE_INFORMATION_CLASS FileInformationClass;
    ULONG FileIndex = 0;
    PUCHAR Buffer = NULL;
    PFILE_NAMES_INFORMATION Buffer0 = NULL;
    PNTFS_FCB Fcb;
    PNTFS_CCB Ccb;
    BOOLEAN First = FALSE;
    PIO_STACK_LOCATION Stack;
    PFILE_OBJECT FileObject;
    NTSTATUS Status = STATUS_SUCCESS;
    PFILE_RECORD_HEADER FileRecord;
    PNTFS_ATTR_CONTEXT DataContext;
    ULONGLONG MFTRecord, OldMFTRecord = 0;
    UNICODE_STRING Pattern;

    DPRINT1("NtfsQueryDirectory() called\n");

    ASSERT(IrpContext);
    Irp = IrpContext->Irp;
    DeviceObject = IrpContext->DeviceObject;

    DeviceExtension = DeviceObject->DeviceExtension;
    Stack = IoGetCurrentIrpStackLocation(Irp);
    FileObject = Stack->FileObject;

    Ccb = (PNTFS_CCB)FileObject->FsContext2;
    Fcb = (PNTFS_FCB)FileObject->FsContext;

    /* Obtain the callers parameters */
    BufferLength = Stack->Parameters.QueryDirectory.Length;
    SearchPattern = Stack->Parameters.QueryDirectory.FileName;
    FileInformationClass = Stack->Parameters.QueryDirectory.FileInformationClass;
    FileIndex = Stack->Parameters.QueryDirectory.FileIndex;

    if (SearchPattern != NULL)
    {
        if (!Ccb->DirectorySearchPattern)
        {
            First = TRUE;
            Pattern.Length = 0;
            Pattern.MaximumLength = SearchPattern->Length + sizeof(WCHAR);
            Ccb->DirectorySearchPattern = Pattern.Buffer =
                ExAllocatePoolWithTag(NonPagedPool, Pattern.MaximumLength, TAG_NTFS);
            if (!Ccb->DirectorySearchPattern)
            {
                return STATUS_INSUFFICIENT_RESOURCES;
            }

            memcpy(Ccb->DirectorySearchPattern, SearchPattern->Buffer, SearchPattern->Length);
            Ccb->DirectorySearchPattern[SearchPattern->Length / sizeof(WCHAR)] = 0;
        }
    }
    else if (!Ccb->DirectorySearchPattern)
    {
        First = TRUE;
        Ccb->DirectorySearchPattern = ExAllocatePoolWithTag(NonPagedPool, 2 * sizeof(WCHAR), TAG_NTFS);
        if (!Ccb->DirectorySearchPattern)
        {
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        Ccb->DirectorySearchPattern[0] = L'*';
        Ccb->DirectorySearchPattern[1] = 0;
    }

    RtlInitUnicodeString(&Pattern, Ccb->DirectorySearchPattern);
    DPRINT("Search pattern '%S'\n", Ccb->DirectorySearchPattern);
    DPRINT("In: '%S'\n", Fcb->PathName);

    /* Determine directory index */
    if (Stack->Flags & SL_INDEX_SPECIFIED)
    {
        Ccb->Entry = Ccb->CurrentByteOffset.u.LowPart;
    }
    else if (First || (Stack->Flags & SL_RESTART_SCAN))
    {
        Ccb->Entry = 0;
    }

    /* Determine Buffer for result */
    if (Irp->MdlAddress)
    {
        Buffer = MmGetSystemAddressForMdl(Irp->MdlAddress);
    }
    else
    {
        Buffer = Irp->UserBuffer;
    }

    DPRINT("Buffer=%p tofind=%S\n", Buffer, Ccb->DirectorySearchPattern);

    while (Status == STATUS_SUCCESS && BufferLength > 0)
    {
        Status = NtfsFindFileAt(DeviceExtension,
                                &Pattern,
                                &Ccb->Entry,
                                &FileRecord,
                                &DataContext,
                                &MFTRecord,
                                Fcb->MFTIndex);

        if (NT_SUCCESS(Status))
        {
            /* HACK: files with both a short name and a long name are present twice in the index.
             * Ignore the second entry, if it is immediately following the first one.
             */
            if (MFTRecord == OldMFTRecord)
            {
                DPRINT("Ignoring duplicate MFT entry 0x%x\n", MFTRecord);
                Ccb->Entry++;
                ExFreePoolWithTag(FileRecord, TAG_NTFS);
                continue;
            }
            OldMFTRecord = MFTRecord;

            switch (FileInformationClass)
            {
                case FileNameInformation:
                    Status = NtfsGetNameInformation(DeviceExtension,
                                                    FileRecord,
                                                    DataContext,
                                                    (PFILE_NAMES_INFORMATION)Buffer,
                                                    BufferLength);
                    break;

                case FileDirectoryInformation:
                    Status = NtfsGetDirectoryInformation(DeviceExtension,
                                                         FileRecord,
                                                         DataContext,
                                                         (PFILE_DIRECTORY_INFORMATION)Buffer,
                                                         BufferLength);
                    break;

                case FileFullDirectoryInformation:
                    Status = NtfsGetFullDirectoryInformation(DeviceExtension,
                                                             FileRecord,
                                                             DataContext,
                                                             MFTRecord,
                                                             (PFILE_FULL_DIRECTORY_INFORMATION)Buffer,
                                                             BufferLength);
                    break;

                case FileBothDirectoryInformation:
                    Status = NtfsGetBothDirectoryInformation(DeviceExtension,
                                                             FileRecord,
                                                             DataContext,
                                                             MFTRecord,
                                                             (PFILE_BOTH_DIR_INFORMATION)Buffer,
                                                             BufferLength);
                    break;

                default:
                    Status = STATUS_INVALID_INFO_CLASS;
            }

            if (Status == STATUS_BUFFER_OVERFLOW)
            {
                if (Buffer0)
                {
                    Buffer0->NextEntryOffset = 0;
                }
                break;
            }
        }
        else
        {
            if (Buffer0)
            {
                Buffer0->NextEntryOffset = 0;
            }

            if (First)
            {
                Status = STATUS_NO_SUCH_FILE;
            }
            else
            {
                Status = STATUS_NO_MORE_FILES;
            }
            break;
        }

        Buffer0 = (PFILE_NAMES_INFORMATION)Buffer;
        Buffer0->FileIndex = FileIndex++;
        Ccb->Entry++;

        if (Stack->Flags & SL_RETURN_SINGLE_ENTRY)
        {
            break;
        }
        BufferLength -= Buffer0->NextEntryOffset;
        Buffer += Buffer0->NextEntryOffset;
        ExFreePoolWithTag(FileRecord, TAG_NTFS);
    }

    if (Buffer0)
    {
        Buffer0->NextEntryOffset = 0;
    }

    if (FileIndex > 0)
    {
        Status = STATUS_SUCCESS;
    }

    return Status;
}
예제 #10
0
파일: power.c 프로젝트: RareHare/reactos
/*++////////////////////////////////////////////////////////////////////////////

ClasspPowerDownCompletion()

Routine Description:

    This routine is used for intermediate completion of a power up request.
    PowerUp requires four requests to be sent to the lower driver in sequence.

        * The queue is "power locked" to ensure that the class driver power-up
          work can be done before request processing resumes.

        * The power irp is sent down the stack for any filter drivers and the
          port driver to return power and resume command processing for the
          device.  Since the queue is locked, no queued irps will be sent
          immediately.

        * A start unit command is issued to the device with appropriate flags
          to override the "power locked" queue.

        * The queue is "power unlocked" to start processing requests again.

    This routine uses the function in the srb which just completed to determine
    which state it is in.

Arguments:

    DeviceObject - the device object being powered up

    Irp - the IO_REQUEST_PACKET containing the power request

    Srb - the SRB used to perform port/class operations.

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED or
    STATUS_SUCCESS

--*/
NTSTATUS
NTAPI
ClasspPowerDownCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PCLASS_POWER_CONTEXT Context
    )
{
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
    PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;

    PIO_STACK_LOCATION currentStack = IoGetCurrentIrpStackLocation(Irp);
    PIO_STACK_LOCATION nextStack = IoGetNextIrpStackLocation(Irp);

    NTSTATUS status = STATUS_MORE_PROCESSING_REQUIRED;

    DebugPrint((1, "ClasspPowerDownCompletion: Device Object %p, "
                   "Irp %p, Context %p\n",
                DeviceObject, Irp, Context));

    ASSERT(!TEST_FLAG(Context->Srb.SrbFlags, SRB_FLAGS_FREE_SENSE_BUFFER));
    ASSERT(!TEST_FLAG(Context->Srb.SrbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE));
    ASSERT(Context->Options.PowerDown == TRUE);
    ASSERT(Context->Options.HandleSpinDown);

    if(Irp->PendingReturned) {
        IoMarkIrpPending(Irp);
    }

    Context->PowerChangeState.PowerDown2++;

    switch(Context->PowerChangeState.PowerDown2) {

        case PowerDownDeviceLocked2: {

            PCDB cdb;

            DebugPrint((1, "(%p)\tPreviously sent power lock\n", Irp));

            if((Context->Options.LockQueue == TRUE) &&
               (!NT_SUCCESS(Irp->IoStatus.Status))) {

                DebugPrint((1, "(%p)\tIrp status was %lx\n",
                            Irp,
                            Irp->IoStatus.Status));
                DebugPrint((1, "(%p)\tSrb status was %lx\n",
                            Irp,
                            Context->Srb.SrbStatus));

                Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;

                //
                // Lock was not successful - throw down the power IRP
                // by itself and don't try to spin down the drive or unlock
                // the queue.
                //

                Context->InUse = FALSE;
                Context = NULL;

                //
                // Set the new power state
                //

                fdoExtension->DevicePowerState =
                    currentStack->Parameters.Power.State.DeviceState;

                //
                // Indicate to Po that we've been successfully powered down
                // so it can do it's notification stuff.
                //

                IoCopyCurrentIrpStackLocationToNext(Irp);
                IoSetCompletionRoutine(Irp,
                                       ClasspStartNextPowerIrpCompletion,
                                       NULL,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                PoSetPowerState(DeviceObject,
                                currentStack->Parameters.Power.Type,
                                currentStack->Parameters.Power.State);

                fdoExtension->PowerDownInProgress = FALSE;

                PoCallDriver(commonExtension->LowerDeviceObject, Irp);

                ClassReleaseRemoveLock(commonExtension->DeviceObject,
                                       Irp);

                return STATUS_MORE_PROCESSING_REQUIRED;

            } else {
                Context->QueueLocked = (UCHAR) Context->Options.LockQueue;
            }

            if (!TEST_FLAG(fdoExtension->PrivateFdoData->HackFlags,
                           FDO_HACK_NO_SYNC_CACHE)) {

                //
                // send SCSIOP_SYNCHRONIZE_CACHE
                //
    
                Context->Srb.Length = sizeof(SCSI_REQUEST_BLOCK);
                Context->Srb.Function = SRB_FUNCTION_EXECUTE_SCSI;
    
                Context->Srb.TimeOutValue = fdoExtension->TimeOutValue;
    
                Context->Srb.SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER |
                                        SRB_FLAGS_DISABLE_AUTOSENSE |
                                        SRB_FLAGS_DISABLE_SYNCH_TRANSFER |
                                        SRB_FLAGS_NO_QUEUE_FREEZE |
                                        SRB_FLAGS_BYPASS_LOCKED_QUEUE;
    
                Context->Srb.SrbStatus = Context->Srb.ScsiStatus = 0;
                Context->Srb.DataTransferLength = 0;
    
                Context->Srb.CdbLength = 10;
    
                cdb = (PCDB) Context->Srb.Cdb;
                
                RtlZeroMemory(cdb, sizeof(CDB));
                cdb->SYNCHRONIZE_CACHE10.OperationCode = SCSIOP_SYNCHRONIZE_CACHE;
    
                IoSetCompletionRoutine(Irp,
                                       ClasspPowerDownCompletion,
                                       Context,
                                       TRUE,
                                       TRUE,
                                       TRUE);
    
                nextStack->Parameters.Scsi.Srb = &(Context->Srb);
                nextStack->MajorFunction = IRP_MJ_SCSI;
    
                status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
    
                DebugPrint((1, "(%p)\tIoCallDriver returned %lx\n", Irp, status));
                break;
            
            } else {
               
                DebugPrint((1, "(%p)\tPower Down: not sending SYNCH_CACHE\n",
                            DeviceObject));
                Context->PowerChangeState.PowerDown2++;
                Context->Srb.SrbStatus = SRB_STATUS_SUCCESS;
                // and fall through....
            }
            // no break in case the device doesn't like synch_cache commands

        }
         
        case PowerDownDeviceFlushed2: {

            PCDB cdb;

            DebugPrint((1, "(%p)\tPreviously send SCSIOP_SYNCHRONIZE_CACHE\n",
                        Irp));

            //
            // SCSIOP_SYNCHRONIZE_CACHE was sent
            //

            if(SRB_STATUS(Context->Srb.SrbStatus) != SRB_STATUS_SUCCESS) {

                BOOLEAN retry;

                DebugPrint((1, "(%p)\tError occured when issuing "
                            "SYNCHRONIZE_CACHE command to device. "
                            "Srb %p, Status %lx\n",
                            Irp,
                            &Context->Srb,
                            Context->Srb.SrbStatus));

                ASSERT(!(TEST_FLAG(Context->Srb.SrbStatus,
                                   SRB_STATUS_QUEUE_FROZEN)));
                ASSERT(Context->Srb.Function == SRB_FUNCTION_EXECUTE_SCSI);

                Context->RetryInterval = 0;
                retry = ClassInterpretSenseInfo(
                            commonExtension->DeviceObject,
                            &Context->Srb,
                            IRP_MJ_SCSI,
                            IRP_MJ_POWER,
                            MAXIMUM_RETRIES - Context->RetryCount,
                            &status,
                            &Context->RetryInterval);

                if((retry == TRUE) && (Context->RetryCount-- != 0)) {

                        DebugPrint((1, "(%p)\tRetrying failed request\n", Irp));

                        //
                        // decrement the state so we come back through here
                        // the next time.
                        //

                        Context->PowerChangeState.PowerDown2--;
                        RetryPowerRequest(commonExtension->DeviceObject,
                                          Irp,
                                          Context);
                        break;
                }

                DebugPrint((1, "(%p)\tSYNCHRONIZE_CACHE not retried\n", Irp));
                Context->RetryCount = MAXIMUM_RETRIES;

            } // end !SRB_STATUS_SUCCESS

            //
            // note: we are purposefully ignoring any errors.  if the drive
            //       doesn't support a synch_cache, then we're up a creek
            //       anyways.
            //

            DebugPrint((1, "(%p)\tSending stop unit to device\n", Irp));

            //
            // Issue the start unit command to the device.
            //

            Context->Srb.Length = sizeof(SCSI_REQUEST_BLOCK);
            Context->Srb.Function = SRB_FUNCTION_EXECUTE_SCSI;

            Context->Srb.TimeOutValue = START_UNIT_TIMEOUT;

            Context->Srb.SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER |
                                    SRB_FLAGS_DISABLE_AUTOSENSE |
                                    SRB_FLAGS_DISABLE_SYNCH_TRANSFER |
                                    SRB_FLAGS_NO_QUEUE_FREEZE |
                                    SRB_FLAGS_BYPASS_LOCKED_QUEUE;

            Context->Srb.SrbStatus = Context->Srb.ScsiStatus = 0;
            Context->Srb.DataTransferLength = 0;

            Context->Srb.CdbLength = 6;

            cdb = (PCDB) Context->Srb.Cdb;
            RtlZeroMemory(cdb, sizeof(CDB));

            cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT;
            cdb->START_STOP.Start = 0;
            cdb->START_STOP.Immediate = 1;

            IoSetCompletionRoutine(Irp,
                                   ClasspPowerDownCompletion,
                                   Context,
                                   TRUE,
                                   TRUE,
                                   TRUE);

            nextStack->Parameters.Scsi.Srb = &(Context->Srb);
            nextStack->MajorFunction = IRP_MJ_SCSI;

            status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);

            DebugPrint((1, "(%p)\tIoCallDriver returned %lx\n", Irp, status));
            break;

        }

        case PowerDownDeviceStopped2: {

            BOOLEAN ignoreError = TRUE;

            //
            // stop was sent
            //

            if(SRB_STATUS(Context->Srb.SrbStatus) != SRB_STATUS_SUCCESS) {

                BOOLEAN retry;

                DebugPrint((1, "(%p)\tError occured when issueing STOP_UNIT "
                            "command to device. Srb %p, Status %lx\n",
                            Irp,
                            &Context->Srb,
                            Context->Srb.SrbStatus));

                ASSERT(!(TEST_FLAG(Context->Srb.SrbStatus,
                                   SRB_STATUS_QUEUE_FROZEN)));
                ASSERT(Context->Srb.Function == SRB_FUNCTION_EXECUTE_SCSI);

                Context->RetryInterval = 0;
                retry = ClassInterpretSenseInfo(
                            commonExtension->DeviceObject,
                            &Context->Srb,
                            IRP_MJ_SCSI,
                            IRP_MJ_POWER,
                            MAXIMUM_RETRIES - Context->RetryCount,
                            &status,
                            &Context->RetryInterval);

                if((retry == TRUE) && (Context->RetryCount-- != 0)) {

                        DebugPrint((1, "(%p)\tRetrying failed request\n", Irp));

                        //
                        // decrement the state so we come back through here
                        // the next time.
                        //

                        Context->PowerChangeState.PowerDown2--;
                        RetryPowerRequest(commonExtension->DeviceObject,
                                          Irp,
                                          Context);
                        break;
                }

                DebugPrint((1, "(%p)\tSTOP_UNIT not retried\n", Irp));
                Context->RetryCount = MAXIMUM_RETRIES;

            } // end !SRB_STATUS_SUCCESS


            DebugPrint((1, "(%p)\tPreviously sent stop unit\n", Irp));

            //
            // some operations, such as a physical format in progress,
            // should not be ignored and should fail the power operation.
            //

            if (!NT_SUCCESS(status)) {
                
                PSENSE_DATA senseBuffer = Context->Srb.SenseInfoBuffer;
                
                if (TEST_FLAG(Context->Srb.SrbStatus,
                              SRB_STATUS_AUTOSENSE_VALID) &&
                    ((senseBuffer->SenseKey & 0xf) == SCSI_SENSE_NOT_READY) &&
                    (senseBuffer->AdditionalSenseCode == SCSI_ADSENSE_LUN_NOT_READY) &&
                    (senseBuffer->AdditionalSenseCodeQualifier == SCSI_SENSEQ_FORMAT_IN_PROGRESS)
                    ) {
                    ignoreError = FALSE;
                    Context->FinalStatus = STATUS_DEVICE_BUSY;
                    status = Context->FinalStatus;
                }

            }

            if (NT_SUCCESS(status) || ignoreError) {

                //
                // Issue the actual power request to the lower driver.
                //

                Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;

                IoCopyCurrentIrpStackLocationToNext(Irp);

                IoSetCompletionRoutine(Irp,
                                       ClasspPowerDownCompletion,
                                       Context,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                status = PoCallDriver(commonExtension->LowerDeviceObject, Irp);

                DebugPrint((1, "(%p)\tPoCallDriver returned %lx\n", Irp, status));
                break;
            }
            
            // else fall through w/o sending the power irp, since the device
            // is reporting an error that would be "really bad" to power down
            // during.

        }

        case PowerDownDeviceOff2: {

            //
            // SpinDown request completed ... whether it succeeded or not is
            // another matter entirely.
            //

            DebugPrint((1, "(%p)\tPreviously sent power irp\n", Irp));

            if (Context->QueueLocked) {

                DebugPrint((1, "(%p)\tUnlocking queue\n", Irp));
                
                Context->Srb.Length = sizeof(SCSI_REQUEST_BLOCK);

                Context->Srb.SrbStatus = Context->Srb.ScsiStatus = 0;
                Context->Srb.DataTransferLength = 0;

                Context->Srb.Function = SRB_FUNCTION_UNLOCK_QUEUE;
                Context->Srb.SrbFlags = SRB_FLAGS_BYPASS_LOCKED_QUEUE;
                nextStack->Parameters.Scsi.Srb = &(Context->Srb);
                nextStack->MajorFunction = IRP_MJ_SCSI;

                IoSetCompletionRoutine(Irp,
                                       ClasspPowerDownCompletion,
                                       Context,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
                DebugPrint((1, "(%p)\tIoCallDriver returned %lx\n",
                            Irp,
                            status));
                break;
            }

        }

        case PowerDownDeviceUnlocked2: {

            //
            // This is the end of the dance.  Free the srb and complete the
            // request finally.  We're ignoring possible intermediate
            // error conditions ....
            //

            if (Context->QueueLocked == FALSE) {
                DebugPrint((1, "(%p)\tFall through (queue not locked)\n", Irp));
            } else {
                DebugPrint((1, "(%p)\tPreviously unlocked queue\n", Irp));
                ASSERT(NT_SUCCESS(Irp->IoStatus.Status));
                ASSERT(Context->Srb.SrbStatus == SRB_STATUS_SUCCESS);
            }

            DebugPrint((1, "(%p)\tFreeing srb and completing\n", Irp));
            Context->InUse = FALSE;
            status = Context->FinalStatus; // allow failure to propogate
            Context = NULL;

            if(Irp->PendingReturned) {
                IoMarkIrpPending(Irp);
            }

            Irp->IoStatus.Status = status;
            Irp->IoStatus.Information = 0;

            if (NT_SUCCESS(status)) {
                
                //
                // Set the new power state
                //

                fdoExtension->DevicePowerState =
                    currentStack->Parameters.Power.State.DeviceState;

            }


            DebugPrint((1, "(%p)\tStarting next power irp\n", Irp));

            ClassReleaseRemoveLock(DeviceObject, Irp);
            PoStartNextPowerIrp(Irp);
            fdoExtension->PowerDownInProgress = FALSE;

            return status;
        }
    }

    return STATUS_MORE_PROCESSING_REQUIRED;
} // end ClasspPowerDownCompletion()
예제 #11
0
NTSTATUS
CmiAddSubKey(
	IN PCMHIVE RegistryHive,
	IN PCM_KEY_NODE ParentKeyCell,
	IN HCELL_INDEX ParentKeyCellOffset,
	IN PCUNICODE_STRING SubKeyName,
	IN ULONG CreateOptions,
	OUT PCM_KEY_NODE *pSubKeyCell,
	OUT HCELL_INDEX *pBlockOffset)
{
	PCM_KEY_FAST_INDEX HashBlock;
	HCELL_INDEX NKBOffset;
	PCM_KEY_NODE NewKeyCell;
	ULONG NewBlockSize;
	NTSTATUS Status;
	USHORT NameLength;
	PWSTR NamePtr;
	BOOLEAN Packable;
	HSTORAGE_TYPE Storage;
	ULONG i;

	VERIFY_KEY_CELL(ParentKeyCell);

	/* Skip leading backslash */
	if (SubKeyName->Buffer[0] == L'\\')
	{
		NamePtr = &SubKeyName->Buffer[1];
		NameLength = SubKeyName->Length - sizeof(WCHAR);
	}
	else
	{
		NamePtr = SubKeyName->Buffer;
		NameLength = SubKeyName->Length;
	}

	/* Check whether key name can be packed */
	Packable = TRUE;
	for (i = 0; i < NameLength / sizeof(WCHAR); i++)
	{
		if (NamePtr[i] & 0xFF00)
		{
			Packable = FALSE;
			break;
		}
	}

	/* Adjust name size */
	if (Packable)
	{
		NameLength = NameLength / sizeof(WCHAR);
	}

	Status = STATUS_SUCCESS;

	Storage = (CreateOptions & REG_OPTION_VOLATILE) ? Volatile : Stable;
	NewBlockSize = FIELD_OFFSET(CM_KEY_NODE, Name) + NameLength;
	NKBOffset = HvAllocateCell(&RegistryHive->Hive, NewBlockSize, Storage, HCELL_NIL);
	if (NKBOffset == HCELL_NIL)
	{
		Status = STATUS_INSUFFICIENT_RESOURCES;
	}
	else
	{
		NewKeyCell = (PCM_KEY_NODE)HvGetCell (&RegistryHive->Hive, NKBOffset);
		NewKeyCell->Signature = CM_KEY_NODE_SIGNATURE;
		if (CreateOptions & REG_OPTION_VOLATILE)
		{
			NewKeyCell->Flags = KEY_IS_VOLATILE;
		}
		else
		{
			NewKeyCell->Flags = 0;
		}
		KeQuerySystemTime(&NewKeyCell->LastWriteTime);
		NewKeyCell->Parent = HCELL_NIL;
		NewKeyCell->SubKeyCounts[Stable] = 0;
		NewKeyCell->SubKeyCounts[Volatile] = 0;
		NewKeyCell->SubKeyLists[Stable] = HCELL_NIL;
		NewKeyCell->SubKeyLists[Volatile] = HCELL_NIL;
		NewKeyCell->ValueList.Count = 0;
		NewKeyCell->ValueList.List = HCELL_NIL;
		NewKeyCell->Security = HCELL_NIL;
		NewKeyCell->Class = HCELL_NIL;

		/* Pack the key name */
		NewKeyCell->NameLength = NameLength;
		if (Packable)
		{
			NewKeyCell->Flags |= KEY_COMP_NAME;
			for (i = 0; i < NameLength; i++)
			{
				((PCHAR)NewKeyCell->Name)[i] = (CHAR)(NamePtr[i] & 0x00FF);
			}
		}
		else
		{
			RtlCopyMemory(
				NewKeyCell->Name,
				NamePtr,
				NameLength);
		}

		VERIFY_KEY_CELL(NewKeyCell);
	}

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

	if (ParentKeyCell->SubKeyLists[Storage] == HCELL_NIL)
	{
		Status = CmiAllocateHashTableCell (
			RegistryHive,
			&HashBlock,
			&ParentKeyCell->SubKeyLists[Storage],
			REG_INIT_HASH_TABLE_SIZE,
			Storage);
		if (!NT_SUCCESS(Status))
		{
			return(Status);
		}
	}
	else
	{
		HashBlock = (PCM_KEY_FAST_INDEX)HvGetCell (
			&RegistryHive->Hive,
			ParentKeyCell->SubKeyLists[Storage]);
		ASSERT(HashBlock->Signature == CM_KEY_FAST_LEAF);

		if (HashBlock->Count ==
		    ((HvGetCellSize(&RegistryHive->Hive, HashBlock) - FIELD_OFFSET(CM_KEY_FAST_INDEX, List)) / sizeof(CM_INDEX)))
		{
			PCM_KEY_FAST_INDEX NewHashBlock;
			HCELL_INDEX HTOffset;

			/* Reallocate the hash table cell */
			Status = CmiAllocateHashTableCell (
				RegistryHive,
				&NewHashBlock,
				&HTOffset,
				HashBlock->Count +
				REG_EXTEND_HASH_TABLE_SIZE,
				Storage);
			if (!NT_SUCCESS(Status))
			{
				return Status;
			}
			RtlCopyMemory(
				&NewHashBlock->List[0],
				&HashBlock->List[0],
				sizeof(NewHashBlock->List[0]) * HashBlock->Count);
         NewHashBlock->Count = HashBlock->Count;
			HvFreeCell (&RegistryHive->Hive, ParentKeyCell->SubKeyLists[Storage]);
			ParentKeyCell->SubKeyLists[Storage] = HTOffset;
			HashBlock = NewHashBlock;
		}
	}

	Status = CmiAddKeyToHashTable(
		RegistryHive,
		HashBlock,
      ParentKeyCell->SubKeyLists[Storage],
		NewKeyCell,
		NKBOffset);
	if (NT_SUCCESS(Status))
	{
		ParentKeyCell->SubKeyCounts[Storage]++;
		*pSubKeyCell = NewKeyCell;
		*pBlockOffset = NKBOffset;
	}

	KeQuerySystemTime(&ParentKeyCell->LastWriteTime);
	HvMarkCellDirty(&RegistryHive->Hive, ParentKeyCellOffset, FALSE);

	return Status;
}
예제 #12
0
파일: power.c 프로젝트: RareHare/reactos
/*++////////////////////////////////////////////////////////////////////////////

ClasspPowerUpCompletion()

Routine Description:

    This routine is used for intermediate completion of a power up request.
    PowerUp requires four requests to be sent to the lower driver in sequence.

        * The queue is "power locked" to ensure that the class driver power-up
          work can be done before request processing resumes.

        * The power irp is sent down the stack for any filter drivers and the
          port driver to return power and resume command processing for the
          device.  Since the queue is locked, no queued irps will be sent
          immediately.

        * A start unit command is issued to the device with appropriate flags
          to override the "power locked" queue.

        * The queue is "power unlocked" to start processing requests again.

    This routine uses the function in the srb which just completed to determine
    which state it is in.

Arguments:

    DeviceObject - the device object being powered up

    Irp - the IO_REQUEST_PACKET containing the power request

    Srb - the SRB used to perform port/class operations.

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED or
    STATUS_SUCCESS
    
--*/
NTSTATUS
NTAPI
ClasspPowerUpCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PCLASS_POWER_CONTEXT Context
    )
{
    PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;

    PIO_STACK_LOCATION currentStack = IoGetCurrentIrpStackLocation(Irp);
    PIO_STACK_LOCATION nextStack = IoGetNextIrpStackLocation(Irp);


    NTSTATUS status = STATUS_MORE_PROCESSING_REQUIRED;

    DebugPrint((1, "ClasspPowerUpCompletion: Device Object %p, Irp %p, "
                   "Context %p\n",
                DeviceObject, Irp, Context));

    ASSERT(!TEST_FLAG(Context->Srb.SrbFlags, SRB_FLAGS_FREE_SENSE_BUFFER));
    ASSERT(!TEST_FLAG(Context->Srb.SrbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE));
    ASSERT(Context->Options.PowerDown == FALSE);
    ASSERT(Context->Options.HandleSpinUp);

    if(Irp->PendingReturned) {
        IoMarkIrpPending(Irp);
    }

    Context->PowerChangeState.PowerUp++;

    switch(Context->PowerChangeState.PowerUp) {

        case PowerUpDeviceLocked: {

            DebugPrint((1, "(%p)\tPreviously sent power lock\n", Irp));

            //
            // Issue the actual power request to the lower driver.
            //

            IoCopyCurrentIrpStackLocationToNext(Irp);

            //
            // If the lock wasn't successful then just bail out on the power
            // request unless we can ignore failed locks
            //

            if((Context->Options.LockQueue == TRUE) &&
               (!NT_SUCCESS(Irp->IoStatus.Status))) {

                DebugPrint((1, "(%p)\tIrp status was %lx\n",
                            Irp, Irp->IoStatus.Status));
                DebugPrint((1, "(%p)\tSrb status was %lx\n",
                            Irp, Context->Srb.SrbStatus));

                //
                // Lock was not successful - throw down the power IRP
                // by itself and don't try to spin up the drive or unlock
                // the queue.
                //

                Context->InUse = FALSE;
                Context = NULL;

                //
                // Set the new power state
                //

                fdoExtension->DevicePowerState =
                    currentStack->Parameters.Power.State.DeviceState;

                Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;

                IoCopyCurrentIrpStackLocationToNext(Irp);

                IoSetCompletionRoutine(Irp,
                                       ClasspStartNextPowerIrpCompletion,
                                       NULL,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                //
                // Indicate to Po that we've been successfully powered up so
                // it can do it's notification stuff.
                //

                PoSetPowerState(DeviceObject,
                                currentStack->Parameters.Power.Type,
                                currentStack->Parameters.Power.State);

                PoCallDriver(commonExtension->LowerDeviceObject, Irp);

                ClassReleaseRemoveLock(commonExtension->DeviceObject,
                                       Irp);

                return STATUS_MORE_PROCESSING_REQUIRED;

            } else {
                Context->QueueLocked = (UCHAR) Context->Options.LockQueue;
            }

            Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;

            Context->PowerChangeState.PowerUp = PowerUpDeviceLocked;

            IoSetCompletionRoutine(Irp,
                                   ClasspPowerUpCompletion,
                                   Context,
                                   TRUE,
                                   TRUE,
                                   TRUE);

            status = PoCallDriver(commonExtension->LowerDeviceObject, Irp);

            DebugPrint((2, "(%p)\tPoCallDriver returned %lx\n", Irp, status));
            break;
        }

        case PowerUpDeviceOn: {

            PCDB cdb;

            if(NT_SUCCESS(Irp->IoStatus.Status)) {

                DebugPrint((1, "(%p)\tSending start unit to device\n", Irp));

                //
                // Issue the start unit command to the device.
                //

                Context->Srb.Length = sizeof(SCSI_REQUEST_BLOCK);
                Context->Srb.Function = SRB_FUNCTION_EXECUTE_SCSI;

                Context->Srb.SrbStatus = Context->Srb.ScsiStatus = 0;
                Context->Srb.DataTransferLength = 0;

                Context->Srb.TimeOutValue = START_UNIT_TIMEOUT;

                Context->Srb.SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER |
                                        SRB_FLAGS_DISABLE_AUTOSENSE |
                                        SRB_FLAGS_DISABLE_SYNCH_TRANSFER |
                                        SRB_FLAGS_NO_QUEUE_FREEZE;

                if(Context->Options.LockQueue) {
                    SET_FLAG(Context->Srb.SrbFlags, SRB_FLAGS_BYPASS_LOCKED_QUEUE);
                }

                Context->Srb.CdbLength = 6;

                cdb = (PCDB) (Context->Srb.Cdb);
                RtlZeroMemory(cdb, sizeof(CDB));


                cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT;
                cdb->START_STOP.Start = 1;

                Context->PowerChangeState.PowerUp = PowerUpDeviceOn;

                IoSetCompletionRoutine(Irp,
                                       ClasspPowerUpCompletion,
                                       Context,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                nextStack->Parameters.Scsi.Srb = &(Context->Srb);
                nextStack->MajorFunction = IRP_MJ_SCSI;

                status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);

                DebugPrint((2, "(%p)\tIoCallDriver returned %lx\n", Irp, status));

            } else {

                //
                // we're done.
                //

                Context->FinalStatus = Irp->IoStatus.Status;
                goto ClasspPowerUpCompletionFailure;
            }

            break;
        }

        case PowerUpDeviceStarted: { // 3

            //
            // First deal with an error if one occurred.
            //

            if(SRB_STATUS(Context->Srb.SrbStatus) != SRB_STATUS_SUCCESS) {

                BOOLEAN retry;

                DebugPrint((1, "%p\tError occured when issuing START_UNIT "
                            "command to device. Srb %p, Status %x\n",
                            Irp,
                            &Context->Srb,
                            Context->Srb.SrbStatus));

                ASSERT(!(TEST_FLAG(Context->Srb.SrbStatus,
                                   SRB_STATUS_QUEUE_FROZEN)));
                ASSERT(Context->Srb.Function == SRB_FUNCTION_EXECUTE_SCSI);

                Context->RetryInterval = 0;

                retry = ClassInterpretSenseInfo(
                            commonExtension->DeviceObject,
                            &Context->Srb,
                            IRP_MJ_SCSI,
                            IRP_MJ_POWER,
                            MAXIMUM_RETRIES - Context->RetryCount,
                            &status,
                            &Context->RetryInterval);

                if((retry == TRUE) && (Context->RetryCount-- != 0)) {

                    DebugPrint((1, "(%p)\tRetrying failed request\n", Irp));

                    //
                    // Decrement the state so we come back through here the
                    // next time.
                    //

                    Context->PowerChangeState.PowerUp--;

                    RetryPowerRequest(commonExtension->DeviceObject,
                                      Irp,
                                      Context);

                    break;

                }
                
                // reset retries
                Context->RetryCount = MAXIMUM_RETRIES;

            }

ClasspPowerUpCompletionFailure:

            DebugPrint((1, "(%p)\tPreviously spun device up\n", Irp));

            if (Context->QueueLocked) {
                DebugPrint((1, "(%p)\tUnlocking queue\n", Irp));

                Context->Srb.Function = SRB_FUNCTION_UNLOCK_QUEUE;
                Context->Srb.SrbFlags = SRB_FLAGS_BYPASS_LOCKED_QUEUE;
                Context->Srb.SrbStatus = Context->Srb.ScsiStatus = 0;
                Context->Srb.DataTransferLength = 0;
                
                nextStack->Parameters.Scsi.Srb = &(Context->Srb);
                nextStack->MajorFunction = IRP_MJ_SCSI;

                Context->PowerChangeState.PowerUp = PowerUpDeviceStarted;

                IoSetCompletionRoutine(Irp,
                                       ClasspPowerUpCompletion,
                                       Context,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
                DebugPrint((1, "(%p)\tIoCallDriver returned %lx\n",
                            Irp, status));
                break;
            }

            // Fall-through to next case...

        }

        case PowerUpDeviceUnlocked: {

            //
            // This is the end of the dance.  Free the srb and complete the
            // request finally.  We're ignoring possible intermediate
            // error conditions ....
            //

            if (Context->QueueLocked) {
                DebugPrint((1, "(%p)\tPreviously unlocked queue\n", Irp));
                ASSERT(NT_SUCCESS(Irp->IoStatus.Status));
                ASSERT(Context->Srb.SrbStatus == SRB_STATUS_SUCCESS);
            } else {
                DebugPrint((1, "(%p)\tFall-through (queue not locked)\n", Irp));
            }

            DebugPrint((1, "(%p)\tFreeing srb and completing\n", Irp));
            Context->InUse = FALSE;

            status = Context->FinalStatus;
            Irp->IoStatus.Status = status;

            Context = NULL;

            //
            // Set the new power state
            //

            if(NT_SUCCESS(status)) {
                fdoExtension->DevicePowerState =
                    currentStack->Parameters.Power.State.DeviceState;
            }

            //
            // Indicate to Po that we've been successfully powered up so
            // it can do it's notification stuff.
            //
            
            PoSetPowerState(DeviceObject,
                            currentStack->Parameters.Power.Type,
                            currentStack->Parameters.Power.State);

            DebugPrint((1, "(%p)\tStarting next power irp\n", Irp));
            ClassReleaseRemoveLock(DeviceObject, Irp);
            PoStartNextPowerIrp(Irp);

            return status;
        }
    }

    return STATUS_MORE_PROCESSING_REQUIRED;
} // end ClasspPowerUpCompletion()
NTSTATUS
GetVolumeInformation (
	IN PPRIMARY_SESSION	PrimarySession,
	IN PUNICODE_STRING	VolumeName
	)
{
	HANDLE					volumeHandle = NULL;
    ACCESS_MASK				desiredAccess;
	ULONG					attributes;
	OBJECT_ATTRIBUTES		objectAttributes;
	IO_STATUS_BLOCK			ioStatusBlock;
	LARGE_INTEGER			allocationSize;
	ULONG					fileAttributes;
    ULONG					shareAccess;
    ULONG					createDisposition;
	ULONG					createOptions;
    PVOID					eaBuffer;
	ULONG					eaLength;

	NTSTATUS				createStatus;
	NTSTATUS				fsControlStatus;

	NTFS_VOLUME_DATA_BUFFER	ntfsVolumeDataBuffer;
	
#if DBG
#else
	UNREFERENCED_PARAMETER( PrimarySession );
#endif

	desiredAccess = SYNCHRONIZE | READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | FILE_WRITE_EA 
					| FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_EA;

	ASSERT( desiredAccess == 0x0012019F );

	attributes  = OBJ_KERNEL_HANDLE;
	attributes |= OBJ_CASE_INSENSITIVE;

	InitializeObjectAttributes( &objectAttributes,
								VolumeName,
								attributes,
								NULL,
								NULL );
		
	allocationSize.LowPart  = 0;
	allocationSize.HighPart = 0;

	fileAttributes	  = 0;		
	shareAccess		  = FILE_SHARE_READ | FILE_SHARE_WRITE;
	createDisposition = FILE_OPEN;
	createOptions     = FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE;
	eaBuffer		  = NULL;
	eaLength		  = 0;
	

	RtlZeroMemory(&ioStatusBlock, sizeof(ioStatusBlock));

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("GetVolumeInformation: PrimarySession = %p\n", PrimarySession) );

	createStatus = ZwCreateFile( &volumeHandle,
								 desiredAccess,
								 &objectAttributes,
								 &ioStatusBlock,
								 &allocationSize,
								 fileAttributes,
								 shareAccess,
								 createDisposition,
								 createOptions,
								 eaBuffer,
								 eaLength );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("GetVolumeInformation: PrimarySession = %p ZwCreateFile volumeHandle =%p, createStatus = %X, ioStatusBlock = %X\n",
					PrimarySession, volumeHandle, createStatus, ioStatusBlock.Information) );

	if (!(createStatus == STATUS_SUCCESS)) {

		return STATUS_UNSUCCESSFUL;
	
	} else {

		ASSERT( ioStatusBlock.Information == FILE_OPENED );
	}

	RtlZeroMemory( &ioStatusBlock, sizeof(ioStatusBlock) );

	fsControlStatus = ZwFsControlFile( volumeHandle,
									   NULL,
									   NULL,
									   NULL,
									   &ioStatusBlock,
									   FSCTL_GET_NTFS_VOLUME_DATA,
									   NULL,
									   0,
									   &ntfsVolumeDataBuffer,
									   sizeof(ntfsVolumeDataBuffer) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("GetFileRecordSegmentHeader: FSCTL_GET_NTFS_VOLUME_DATA: volumeHandle %p, fsControlStatus = %x, ioStatusBlock.Status = %x, ioStatusBlock.Information = %d\n",
					volumeHandle, fsControlStatus, ioStatusBlock.Status, ioStatusBlock.Information) );
		
	if (NT_SUCCESS(fsControlStatus)) {

		ASSERT( fsControlStatus == STATUS_SUCCESS );	
		ASSERT( fsControlStatus == ioStatusBlock.Status );
	}

	if (fsControlStatus == STATUS_BUFFER_OVERFLOW)
		ASSERT( ioStatusBlock.Information == sizeof(ntfsVolumeDataBuffer) );
		
	if (!(fsControlStatus == STATUS_SUCCESS || fsControlStatus == STATUS_BUFFER_OVERFLOW)) {

		ioStatusBlock.Information = 0;
		ASSERT(ioStatusBlock.Information == 0);
	}	

	if (!NT_SUCCESS(fsControlStatus)) {

		PrimarySession->Thread.BytesPerFileRecordSegment	= 0;
		PrimarySession->Thread.BytesPerSector				= 0;
		PrimarySession->Thread.BytesPerCluster				= 0;
		
		ZwClose(volumeHandle);
		return STATUS_SUCCESS;
	}
	
	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->VolumeSerialNumber.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.VolumeSerialNumber.QuadPart) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->NumberSectors.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.NumberSectors.QuadPart) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->TotalClusters.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.TotalClusters.QuadPart) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->FreeClusters.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.FreeClusters.QuadPart) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->TotalReserved.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.TotalReserved.QuadPart) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->BytesPerSector = %u\n", 
					ntfsVolumeDataBuffer.BytesPerSector) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->BytesPerCluster = %u\n", 
					ntfsVolumeDataBuffer.BytesPerCluster) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->BytesPerFileRecordSegment = %u\n", 
					ntfsVolumeDataBuffer.BytesPerFileRecordSegment) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->ClustersPerFileRecordSegment = %u\n", 
					ntfsVolumeDataBuffer.ClustersPerFileRecordSegment) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->MftValidDataLength.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.MftValidDataLength.QuadPart) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->MftStartLcn.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.MftStartLcn.QuadPart) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->MftZoneStart.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.MftZoneStart.QuadPart) );

	SPY_LOG_PRINT( LFS_DEBUG_PRIMARY_TRACE,
				   ("ntfsVolumeDataBuffer->MftZoneEnd.QuadPart = %I64u\n", 
					ntfsVolumeDataBuffer.MftZoneEnd.QuadPart) );

	PrimarySession->Thread.BytesPerFileRecordSegment	= ntfsVolumeDataBuffer.BytesPerFileRecordSegment;
	PrimarySession->Thread.BytesPerSector				= ntfsVolumeDataBuffer.BytesPerSector;
	PrimarySession->Thread.BytesPerCluster				= ntfsVolumeDataBuffer.BytesPerCluster;

	ZwClose( volumeHandle );
	
	return STATUS_SUCCESS;
}
예제 #14
0
/************************************************
 * Return PID using ZwQuerySystemInformation(). *
 ************************************************/
DWORD GetPIDFromNameZwQuerySystemInformation(char *szProcessName)
{
	// Some definitions from NTDDK and other sources

	typedef LONG	NTSTATUS;
	typedef LONG	KPRIORITY;

	#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
	#define STATUS_INFO_LENGTH_MISMATCH      ((NTSTATUS)0xC0000004L)
	#define SystemProcessesAndThreadsInformation	5

	typedef struct _CLIENT_ID {
		DWORD	    UniqueProcess;
		DWORD	    UniqueThread;
	} CLIENT_ID;

	typedef struct _UNICODE_STRING {
		USHORT	    Length;
		USHORT	    MaximumLength;
		PWSTR	    Buffer;
	} UNICODE_STRING;

	typedef struct _VM_COUNTERS {
		SIZE_T	    PeakVirtualSize;
		SIZE_T	    VirtualSize;
		ULONG	    PageFaultCount;
		SIZE_T	    PeakWorkingSetSize;
		SIZE_T	    WorkingSetSize;
		SIZE_T	    QuotaPeakPagedPoolUsage;
		SIZE_T	    QuotaPagedPoolUsage;
		SIZE_T	    QuotaPeakNonPagedPoolUsage;
		SIZE_T	    QuotaNonPagedPoolUsage;
		SIZE_T	    PagefileUsage;
		SIZE_T	    PeakPagefileUsage;
	} VM_COUNTERS;

	typedef struct _SYSTEM_THREADS {
		LARGE_INTEGER   KernelTime;
		LARGE_INTEGER   UserTime;
		LARGE_INTEGER   CreateTime;
		ULONG			WaitTime;
		PVOID			StartAddress;
		CLIENT_ID	    ClientId;
		KPRIORITY	    Priority;
		KPRIORITY	    BasePriority;
		ULONG			ContextSwitchCount;
		LONG			State;
		LONG			WaitReason;
	} SYSTEM_THREADS, * PSYSTEM_THREADS;

	// NOTE: SYSTEM_PROCESSES structure is different on NT 4 and Win2K
	typedef struct _SYSTEM_PROCESSES {
		ULONG			NextEntryDelta;
		ULONG			ThreadCount;
		ULONG			Reserved1[6];
		LARGE_INTEGER   CreateTime;
		LARGE_INTEGER   UserTime;
		LARGE_INTEGER   KernelTime;
		UNICODE_STRING  ProcessName;
		KPRIORITY	    BasePriority;
		ULONG			ProcessId;
		ULONG			InheritedFromProcessId;
		ULONG			HandleCount;
		ULONG			Reserved2[2];
		VM_COUNTERS	    VmCounters;
	#if _WIN32_WINNT >= 0x500
		IO_COUNTERS	    IoCounters;
	#endif
		SYSTEM_THREADS  Threads[1];
	} SYSTEM_PROCESSES, * PSYSTEM_PROCESSES;

	typedef LONG (WINAPI *ZWQUERYSYSTEMINFORMATION)(UINT SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength);

	ZWQUERYSYSTEMINFORMATION    ZwQuerySystemInformation;
	PSYSTEM_PROCESSES           pInfo;
    HINSTANCE					hNTDll;
	WCHAR						wcProcessName[MAX_PATH+2];
	PCWSTR						pszProcessName;
	DWORD						dwPID;
	ULONG						BufferLen = 0x8000;
	LPVOID						pBuffer = NULL;
	LONG						Status;

	// Check szProcessName
	if (!szProcessName)
		return -1;

	// Convert szProcessName to Unicode
	if (!MultiByteToWideChar(CP_ACP, 0, szProcessName, -1, wcProcessName, sizeof(wcProcessName) / sizeof(WCHAR)))
		return -1;

    // Get NTDLL handle
    if (!(hNTDll = LoadLibrary("NTDLL.DLL")))
        return -1;

    // Load ZwQuerySystemInformation() dynamically
    if (!(ZwQuerySystemInformation = (ZWQUERYSYSTEMINFORMATION)GetProcAddress(hNTDll, "ZwQuerySystemInformation")))
	{
		FreeLibrary(hNTDll);
		SetLastError(ERROR_PROC_NOT_FOUND);
        return -1;
	}

    // Find needed buffer length
    do
    {
		if (!(pBuffer = malloc(BufferLen)))
		{
			FreeLibrary(hNTDll);
			SetLastError(ERROR_NOT_ENOUGH_MEMORY);
	        return -1;
		}

		Status = ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
					                      pBuffer, BufferLen, NULL);

		if (Status == STATUS_INFO_LENGTH_MISMATCH)
		{
			free(pBuffer);
			BufferLen *= 2;
		}
		else if (!NT_SUCCESS(Status))
		{
			free(pBuffer);
			FreeLibrary(hNTDll);
			return -1;
		}
    }
    while (Status == STATUS_INFO_LENGTH_MISMATCH);

	pInfo = (PSYSTEM_PROCESSES)pBuffer;
    for (;;)
    {
		pszProcessName = pInfo->ProcessName.Buffer;
		if (pszProcessName == NULL)
			pszProcessName = L"Idle";

        // Process found ?
        if (wcsicmp(pszProcessName, wcProcessName) == 0)
        {
			dwPID = pInfo->ProcessId;
			free(pBuffer);
			FreeLibrary(hNTDll);
			return dwPID;
        }

		if (pInfo->NextEntryDelta == 0)
			break;

		// Find the address of the next process structure
		pInfo = (PSYSTEM_PROCESSES)(((PUCHAR)pInfo) + pInfo->NextEntryDelta);
    }

    free(pBuffer);
	FreeLibrary(hNTDll);
    return -1;
}
예제 #15
0
static
NTSTATUS
MsvpCheckPassword(PUNICODE_STRING UserPassword,
                  PSAMPR_USER_INFO_BUFFER UserInfo)
{
    ENCRYPTED_NT_OWF_PASSWORD UserNtPassword;
    ENCRYPTED_LM_OWF_PASSWORD UserLmPassword;
    BOOLEAN UserLmPasswordPresent = FALSE;
    BOOLEAN UserNtPasswordPresent = FALSE;
    OEM_STRING LmPwdString;
    CHAR LmPwdBuffer[15];
    NTSTATUS Status;

    TRACE("(%p %p)\n", UserPassword, UserInfo);

    /* Calculate the LM password and hash for the users password */
    LmPwdString.Length = 15;
    LmPwdString.MaximumLength = 15;
    LmPwdString.Buffer = LmPwdBuffer;
    ZeroMemory(LmPwdString.Buffer, LmPwdString.MaximumLength);

    Status = RtlUpcaseUnicodeStringToOemString(&LmPwdString,
                                               UserPassword,
                                               FALSE);
    if (NT_SUCCESS(Status))
    {
        /* Calculate the LM hash value of the users password */
        Status = SystemFunction006(LmPwdString.Buffer,
                                   (LPSTR)&UserLmPassword);
        if (NT_SUCCESS(Status))
        {
            UserLmPasswordPresent = TRUE;
        }
    }

    /* Calculate the NT hash of the users password */
    Status = SystemFunction007(UserPassword,
                               (LPBYTE)&UserNtPassword);
    if (NT_SUCCESS(Status))
    {
        UserNtPasswordPresent = TRUE;
    }

    Status = STATUS_WRONG_PASSWORD;

    /* Succeed, if no password has been set */
    if (UserInfo->All.NtPasswordPresent == FALSE &&
        UserInfo->All.LmPasswordPresent == FALSE)
    {
        TRACE("No password check!\n");
        Status = STATUS_SUCCESS;
        goto done;
    }

    /* Succeed, if NT password matches */
    if (UserNtPasswordPresent && UserInfo->All.NtPasswordPresent)
    {
        TRACE("Check NT password hashes:\n");
        if (RtlEqualMemory(&UserNtPassword,
                           UserInfo->All.NtOwfPassword.Buffer,
                           sizeof(ENCRYPTED_NT_OWF_PASSWORD)))
        {
            TRACE("  success!\n");
            Status = STATUS_SUCCESS;
            goto done;
        }

        TRACE("  failed!\n");
    }

    /* Succeed, if LM password matches */
    if (UserLmPasswordPresent && UserInfo->All.LmPasswordPresent)
    {
        TRACE("Check LM password hashes:\n");
        if (RtlEqualMemory(&UserLmPassword,
                           UserInfo->All.LmOwfPassword.Buffer,
                           sizeof(ENCRYPTED_LM_OWF_PASSWORD)))
        {
            TRACE("  success!\n");
            Status = STATUS_SUCCESS;
            goto done;
        }
        TRACE("  failed!\n");
    }

done:
    return Status;
}
예제 #16
0
파일: pview.c 프로젝트: mingpen/OpenNT
VOID
SetProcessFields(
    PSYSTEM_PROCESS_INFORMATION ProcessInfo,
    HWND hwnd
    )
{

    TIME_FIELDS UserTime;
    TIME_FIELDS KernelTime;
    TIME_FIELDS RunTime;
    LARGE_INTEGER Time;
    CHAR TimeString[15];
    CHAR szTempField[MAXTASKNAMELEN];
    CHAR szTemp[80];
    HANDLE hProcess;
    HWND ThreadList,ProcessList;
    int i, nIndex;
    PSYSTEM_THREAD_INFORMATION ThreadInfo;
    PCHAR p;
    ANSI_STRING pname;

    pname.Buffer = NULL;
    hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,(DWORD)ProcessInfo->UniqueProcessId);

    //
    // Set process name and process id
    //

    if ( ProcessInfo->ImageName.Buffer ) {
        RtlUnicodeStringToAnsiString(&pname,(PUNICODE_STRING)&ProcessInfo->ImageName,TRUE);
        p = strrchr(pname.Buffer,'\\');
        if ( p ) {
            p++;
            }
        else {
            p = pname.Buffer;
            }
        }
    else {
        p = "System Process";
        }
    SetDlgItemText(
        hwnd,
        PXPLODE_IMAGENAME,
        p
        );

    SetDlgItemInt(
        hwnd,
        PXPLODE_PROCESS_ID,
        (int)ProcessInfo->UniqueProcessId,
        FALSE
        );

    if ( pname.Buffer ) {
        RtlFreeAnsiString(&pname);
        }

    //
    // Set process priority
    //

    if ( ProcessInfo->BasePriority < 7 ) {
        CheckRadioButton(hwnd,PXPLODE_PRIORITY_IDL,PXPLODE_PRIORITY_HIGH,PXPLODE_PRIORITY_IDL);
        }
    else if ( ProcessInfo->BasePriority < 10 ) {
        CheckRadioButton(hwnd,PXPLODE_PRIORITY_IDL,PXPLODE_PRIORITY_HIGH,PXPLODE_PRIORITY_NORMAL);
        }
    else {
        CheckRadioButton(hwnd,PXPLODE_PRIORITY_IDL,PXPLODE_PRIORITY_HIGH,PXPLODE_PRIORITY_HIGH);
        }

    //
    // Compute address space utilization
    //

    ComputeVaSpace(hwnd,hProcess);

    //
    // Compute runtimes
    //

    RtlTimeToTimeFields ( &ProcessInfo->UserTime, &UserTime);
    RtlTimeToTimeFields ( &ProcessInfo->KernelTime, &KernelTime);

    RtlTimeToTimeFields ( &ProcessInfo->UserTime, &UserTime);
    RtlTimeToTimeFields ( &ProcessInfo->KernelTime, &KernelTime);
    Time.QuadPart = RefreshTimeOfDayInfo.CurrentTime.QuadPart - ProcessInfo->CreateTime.QuadPart;
    RtlTimeToTimeFields ( &Time, &RunTime);
    wsprintf(TimeString,"%3ld:%02ld:%02ld.%03ld",
                RunTime.Hour,
                RunTime.Minute,
                RunTime.Second,
                RunTime.Milliseconds
                );
    SetDlgItemText(
        hwnd,
        PXPLODE_ELAPSED_TIME,
        TimeString
        );

    wsprintf(TimeString,"%3ld:%02ld:%02ld.%03ld",
                UserTime.Hour,
                UserTime.Minute,
                UserTime.Second,
                UserTime.Milliseconds
                );
    SetDlgItemText(
        hwnd,
        PXPLODE_USER_TIME,
        TimeString
        );

    wsprintf(TimeString,"%3ld:%02ld:%02ld.%03ld",
                KernelTime.Hour,
                KernelTime.Minute,
                KernelTime.Second,
                KernelTime.Milliseconds
                );
    SetDlgItemText(
        hwnd,
        PXPLODE_KERNEL_TIME,
        TimeString
        );

    //
    // Set I/O Counts
    //
#if 0
    SetDlgItemInt(
        hwnd,
        PXPLODE_READ_XFER,
        ProcessInfo->ReadTransferCount.LowPart,
        FALSE
        );
    SetDlgItemInt(
        hwnd,
        PXPLODE_WRITE_XFER,
        ProcessInfo->WriteTransferCount.LowPart,
        FALSE
        );
    SetDlgItemInt(
        hwnd,
        PXPLODE_OTHER_XFER,
        ProcessInfo->OtherTransferCount.LowPart,
        FALSE
        );
    SetDlgItemInt(
        hwnd,
        PXPLODE_READ_OPS,
        ProcessInfo->ReadOperationCount,
        FALSE
        );
    SetDlgItemInt(
        hwnd,
        PXPLODE_WRITE_OPS,
        ProcessInfo->WriteOperationCount,
        FALSE
        );
    SetDlgItemInt(
        hwnd,
        PXPLODE_OTHER_OPS,
        ProcessInfo->OtherOperationCount,
        FALSE
        );
#endif
    //
    // Set memory management stats
    //

    wsprintf(szTemp,"%d Kb",ProcessInfo->PeakVirtualSize/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PEAK_VSIZE,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",ProcessInfo->VirtualSize/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_VSIZE,
        szTemp
        );

    SetDlgItemInt(
        hwnd,
        PXPLODE_PFCOUNT,
        ProcessInfo->PageFaultCount,
        FALSE
        );

    wsprintf(szTemp,"%d Kb",(ProcessInfo->PeakWorkingSetSize)/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PEAK_WS,
        szTemp
        );

    wsprintf(szTemp,"%d Kb",(ProcessInfo->WorkingSetSize)/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_WS,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",(ProcessInfo->PeakPagefileUsage)/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PEAK_PF,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",(ProcessInfo->PagefileUsage)/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PF,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",(ProcessInfo->PrivatePageCount)/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PRIVATE_PAGE,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",ProcessInfo->QuotaPeakPagedPoolUsage/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PEAK_PAGED,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",ProcessInfo->QuotaPagedPoolUsage/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PAGED,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",ProcessInfo->QuotaPeakNonPagedPoolUsage/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PEAK_NONPAGED,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",ProcessInfo->QuotaNonPagedPoolUsage/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_NONPAGED,
        szTemp
        );
    wsprintf(szTemp,"%d Kb",ProcessInfo->QuotaPeakPagedPoolUsage/1024);
    SetDlgItemText(
        hwnd,
        PXPLODE_PEAK_PAGED,
        szTemp
        );

    //
    // Get the usage and limits
    //

    {
        NTSTATUS Status;
        POOLED_USAGE_AND_LIMITS PooledInfo;

            Status = NtQueryInformationProcess(
                        hProcess,
                        ProcessPooledUsageAndLimits,
                        &PooledInfo,
                        sizeof(PooledInfo),
                        NULL
                        );
            if ( !NT_SUCCESS(Status) ) {
                RtlZeroMemory(&PooledInfo,sizeof(PooledInfo));
                }
            //
            // non paged
            //

            wsprintf(szTempField,"%d Kb",
                PooledInfo.PeakNonPagedPoolUsage/1024
                );
            SetDlgItemText(
                hwnd,
                PXPLODE_QNONPEAK,
                szTempField
                );


            wsprintf(szTempField,"%d Kb",
                PooledInfo.NonPagedPoolUsage/1024
                );
            SetDlgItemText(
                hwnd,
                PXPLODE_QNONCUR,
                szTempField
                );

            if (PooledInfo.NonPagedPoolLimit != 0xffffffff ) {
                wsprintf(szTempField,"%d Kb",
                    PooledInfo.NonPagedPoolLimit/1024
                    );
                }
            else {
                strcpy(szTempField,"Unlimited");
                }
            SetDlgItemText(
                hwnd,
                PXPLODE_QNONLIM,
                szTempField
                );


            //
            // paged
            //

            wsprintf(szTempField,"%d Kb",
                PooledInfo.PeakPagedPoolUsage/1024
                );
            SetDlgItemText(
                hwnd,
                PXPLODE_QPGPEAK,
                szTempField
                );

            wsprintf(szTempField,"%d Kb",
                PooledInfo.PagedPoolUsage/1024
                );
            SetDlgItemText(
                hwnd,
                PXPLODE_QPGCUR,
                szTempField
                );

            if (PooledInfo.PagedPoolLimit != 0xffffffff) {
                wsprintf(szTempField,"%d Kb",
                    PooledInfo.PagedPoolLimit/1024
                    );
                }
            else {
                strcpy(szTempField,"Unlimited");
                }
            SetDlgItemText(
                hwnd,
                PXPLODE_QPGLIM,
                szTempField
                );

            //
            // page file
            //

            wsprintf(szTempField,"%d Kb",
                PooledInfo.PeakPagefileUsage*4
                );
            SetDlgItemText(
                hwnd,
                PXPLODE_QPFPEAK,
                szTempField
                );

            wsprintf(szTempField,"%d Kb",
                PooledInfo.PagefileUsage*4
                );
            SetDlgItemText(
                hwnd,
                PXPLODE_QPFCUR,
                szTempField
                );

            if (PooledInfo.PagefileLimit != 0xffffffff) {
                wsprintf(szTempField,"%d Kb",
                    PooledInfo.PagefileLimit*4
                    );
                }
            else {
                strcpy(szTempField,"Unlimited");
                }
            SetDlgItemText(
                hwnd,
                PXPLODE_QPFLIM,
                szTempField
                );
    }
    //
    // Locate the thread list box
    // and clear it
    //

    i = 0;
    ThreadList = GetDlgItem(hwnd, PXPLODE_THREAD_LIST);

//    SendMessage(ThreadList, WM_SETREDRAW, FALSE, 0);
    SendMessage(ThreadList, LB_RESETCONTENT, 0, 0);
    SendMessage(ThreadList, LB_SETITEMDATA, 0L, 0L);

    ThreadInfo = (PSYSTEM_THREAD_INFORMATION)(ProcessInfo + 1);
    while (i < (int)ProcessInfo->NumberOfThreads) {

        wsprintf(szTempField,"%d",
            ThreadInfo->ClientId.UniqueThread
            );

        nIndex = (int)SendMessage(
                        ThreadList,
                        LB_ADDSTRING,
                        0,
                        (DWORD)(LPSTR)szTempField
                        );
        SendMessage(
            ThreadList,
            LB_SETITEMDATA,
            nIndex,
            (DWORD)ThreadInfo
            );

        if ( i == 0 ) {
            SetThreadFields(ThreadInfo,hwnd);
            }
        ThreadInfo += 1;
        i += 1;
        }
    SendMessage(ThreadList, LB_SETCURSEL, 0, 0);

    SetDlgItemInt(
        hwnd,
        PXPLODE_THREAD_COUNT,
        ProcessInfo->NumberOfThreads,
        FALSE
        );

    // Redraw the list now that all items have been inserted.

//    SendMessage(ThreadList, WM_SETREDRAW, TRUE, 0);
//    InvalidateRect(ThreadList, NULL, TRUE);

    ProcessList = GetDlgItem(hwnd, PXPLODE_PROCESS_LIST);
    SetFocus(ProcessList);
    if ( hProcess ) {
        CloseHandle(hProcess);
        }

    //
    // If we can't get at the process (maybe it's process 0?)
    // then don't let people try and edit the security on it or it's token.
    //

    hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,(DWORD)ProcessInfo->UniqueProcessId);
    EnableWindow(GetDlgItem(hwnd, PXPLODE_PROCESS_ACL), hProcess != NULL);
    EnableWindow(GetDlgItem(hwnd, PXPLODE_PROCESS_TOKEN), hProcess != NULL);
    EnableWindow(GetDlgItem(hwnd, PXPLODE_PROCESS_TOKEN_ACL), hProcess != NULL);
    if (hProcess) {
        CloseHandle(hProcess);
    }


}
예제 #17
0
static
NTSTATUS
BuildInteractiveProfileBuffer(IN PLSA_CLIENT_REQUEST ClientRequest,
                              IN PSAMPR_USER_INFO_BUFFER UserInfo,
                              IN PUNICODE_STRING LogonServer,
                              OUT PMSV1_0_INTERACTIVE_PROFILE *ProfileBuffer,
                              OUT PULONG ProfileBufferLength)
{
    PMSV1_0_INTERACTIVE_PROFILE LocalBuffer = NULL;
    PVOID ClientBaseAddress = NULL;
    LPWSTR Ptr;
    ULONG BufferLength;
    NTSTATUS Status = STATUS_SUCCESS;

    *ProfileBuffer = NULL;
    *ProfileBufferLength = 0;

    BufferLength = sizeof(MSV1_0_INTERACTIVE_PROFILE) +
                   UserInfo->All.FullName.Length + sizeof(WCHAR) +
                   UserInfo->All.HomeDirectory.Length + sizeof(WCHAR) +
                   UserInfo->All.HomeDirectoryDrive.Length + sizeof(WCHAR) +
                   UserInfo->All.ScriptPath.Length + sizeof(WCHAR) +
                   UserInfo->All.ProfilePath.Length + sizeof(WCHAR) +
                   LogonServer->Length + sizeof(WCHAR);

    LocalBuffer = DispatchTable.AllocateLsaHeap(BufferLength);
    if (LocalBuffer == NULL)
    {
        TRACE("Failed to allocate the local buffer!\n");
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto done;
    }

    Status = DispatchTable.AllocateClientBuffer(ClientRequest,
                                                BufferLength,
                                                &ClientBaseAddress);
    if (!NT_SUCCESS(Status))
    {
        TRACE("DispatchTable.AllocateClientBuffer failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    TRACE("ClientBaseAddress: %p\n", ClientBaseAddress);

    Ptr = (LPWSTR)((ULONG_PTR)LocalBuffer + sizeof(MSV1_0_INTERACTIVE_PROFILE));

    LocalBuffer->MessageType = MsV1_0InteractiveProfile;
    LocalBuffer->LogonCount = UserInfo->All.LogonCount;
    LocalBuffer->BadPasswordCount = UserInfo->All.BadPasswordCount;

    LocalBuffer->LogonTime.LowPart = UserInfo->All.LastLogon.LowPart;
    LocalBuffer->LogonTime.HighPart = UserInfo->All.LastLogon.HighPart;

//    LocalBuffer->LogoffTime.LowPart =
//    LocalBuffer->LogoffTime.HighPart =

//    LocalBuffer->KickOffTime.LowPart =
//    LocalBuffer->KickOffTime.HighPart =

    LocalBuffer->PasswordLastSet.LowPart = UserInfo->All.PasswordLastSet.LowPart;
    LocalBuffer->PasswordLastSet.HighPart = UserInfo->All.PasswordLastSet.HighPart;

    LocalBuffer->PasswordCanChange.LowPart = UserInfo->All.PasswordCanChange.LowPart;
    LocalBuffer->PasswordCanChange.HighPart = UserInfo->All.PasswordCanChange.HighPart;

    LocalBuffer->PasswordMustChange.LowPart = UserInfo->All.PasswordMustChange.LowPart;
    LocalBuffer->PasswordMustChange.HighPart = UserInfo->All.PasswordMustChange.HighPart;

    LocalBuffer->LogonScript.Length = UserInfo->All.ScriptPath.Length;
    LocalBuffer->LogonScript.MaximumLength = UserInfo->All.ScriptPath.Length + sizeof(WCHAR);
    LocalBuffer->LogonScript.Buffer = (LPWSTR)((ULONG_PTR)ClientBaseAddress + (ULONG_PTR)Ptr - (ULONG_PTR)LocalBuffer);
    memcpy(Ptr,
           UserInfo->All.ScriptPath.Buffer,
           UserInfo->All.ScriptPath.Length);

    Ptr = (LPWSTR)((ULONG_PTR)Ptr + LocalBuffer->LogonScript.MaximumLength);

    LocalBuffer->HomeDirectory.Length = UserInfo->All.HomeDirectory.Length;
    LocalBuffer->HomeDirectory.MaximumLength = UserInfo->All.HomeDirectory.Length + sizeof(WCHAR);
    LocalBuffer->HomeDirectory.Buffer = (LPWSTR)((ULONG_PTR)ClientBaseAddress + (ULONG_PTR)Ptr - (ULONG_PTR)LocalBuffer);
    memcpy(Ptr,
           UserInfo->All.HomeDirectory.Buffer,
           UserInfo->All.HomeDirectory.Length);

    Ptr = (LPWSTR)((ULONG_PTR)Ptr + LocalBuffer->HomeDirectory.MaximumLength);

    LocalBuffer->FullName.Length = UserInfo->All.FullName.Length;
    LocalBuffer->FullName.MaximumLength = UserInfo->All.FullName.Length + sizeof(WCHAR);
    LocalBuffer->FullName.Buffer = (LPWSTR)((ULONG_PTR)ClientBaseAddress + (ULONG_PTR)Ptr - (ULONG_PTR)LocalBuffer);
    memcpy(Ptr,
           UserInfo->All.FullName.Buffer,
           UserInfo->All.FullName.Length);
    TRACE("FullName.Buffer: %p\n", LocalBuffer->FullName.Buffer);

    Ptr = (LPWSTR)((ULONG_PTR)Ptr + LocalBuffer->FullName.MaximumLength);

    LocalBuffer->ProfilePath.Length = UserInfo->All.ProfilePath.Length;
    LocalBuffer->ProfilePath.MaximumLength = UserInfo->All.ProfilePath.Length + sizeof(WCHAR);
    LocalBuffer->ProfilePath.Buffer = (LPWSTR)((ULONG_PTR)ClientBaseAddress + (ULONG_PTR)Ptr - (ULONG_PTR)LocalBuffer);
    memcpy(Ptr,
           UserInfo->All.ProfilePath.Buffer,
           UserInfo->All.ProfilePath.Length);

    Ptr = (LPWSTR)((ULONG_PTR)Ptr + LocalBuffer->ProfilePath.MaximumLength);

    LocalBuffer->HomeDirectoryDrive.Length = UserInfo->All.HomeDirectoryDrive.Length;
    LocalBuffer->HomeDirectoryDrive.MaximumLength = UserInfo->All.HomeDirectoryDrive.Length + sizeof(WCHAR);
    LocalBuffer->HomeDirectoryDrive.Buffer = (LPWSTR)((ULONG_PTR)ClientBaseAddress + (ULONG_PTR)Ptr - (ULONG_PTR)LocalBuffer);
    memcpy(Ptr,
           UserInfo->All.HomeDirectoryDrive.Buffer,
           UserInfo->All.HomeDirectoryDrive.Length);

    Ptr = (LPWSTR)((ULONG_PTR)Ptr + LocalBuffer->HomeDirectoryDrive.MaximumLength);

    LocalBuffer->LogonServer.Length = LogonServer->Length;
    LocalBuffer->LogonServer.MaximumLength = LogonServer->Length + sizeof(WCHAR);
    LocalBuffer->LogonServer.Buffer = (LPWSTR)((ULONG_PTR)ClientBaseAddress + (ULONG_PTR)Ptr - (ULONG_PTR)LocalBuffer);;
    memcpy(Ptr,
           LogonServer->Buffer,
           LogonServer->Length);

    LocalBuffer->UserFlags = 0;

    Status = DispatchTable.CopyToClientBuffer(ClientRequest,
                                              BufferLength,
                                              ClientBaseAddress,
                                              LocalBuffer);
    if (!NT_SUCCESS(Status))
    {
        TRACE("DispatchTable.CopyToClientBuffer failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    *ProfileBuffer = (PMSV1_0_INTERACTIVE_PROFILE)ClientBaseAddress;
    *ProfileBufferLength = BufferLength;

done:
    if (LocalBuffer != NULL)
        DispatchTable.FreeLsaHeap(LocalBuffer);

    if (!NT_SUCCESS(Status))
    {
        if (ClientBaseAddress != NULL)
            DispatchTable.FreeClientBuffer(ClientRequest,
                                           ClientBaseAddress);
    }

    return Status;
}
예제 #18
0
파일: pview.c 프로젝트: mingpen/OpenNT
LONG
ExplodeDlgProc(
    HWND hwnd,
    UINT wMsg,
    DWORD wParam,
    LONG lParam)
{
    int nIndex;
    HWND ThreadList;
    HWND ProcessList;
    PSYSTEM_PROCESS_INFORMATION ProcessInfo;
    PSYSTEM_THREAD_INFORMATION ThreadInfo;
    HANDLE hProcess;

    switch (wMsg) {

    case WM_INITDIALOG:

        if (!RegisterHotKey(hwnd, 1, MOD_CONTROL | MOD_ALT, VK_ESCAPE) ) {
            EndDialog(hwnd, 0);
            return(FALSE);
        }

        ProcessInfo = NULL;
        DlgProcessInfo = ProcessInfo;
        wParam = 1;

        //
        // Tidy up the system menu
        //

        DeleteMenu(GetSystemMenu(hwnd, FALSE), SC_MAXIMIZE, MF_BYCOMMAND);
        DeleteMenu(GetSystemMenu(hwnd, FALSE), SC_SIZE, MF_BYCOMMAND);

        //
        // Hide acleditting controls if we can't handle them
        //

        if (!InitializeAclEditor()) {

            DbgPrint("PVIEW: Acl editor failed to initialize, ACL editting disabled\n");

            ShowWindow(GetDlgItem(hwnd, PXPLODE_SECURITY_GROUP), SW_HIDE);
            ShowWindow(GetDlgItem(hwnd, PXPLODE_PROCESS_ACL), SW_HIDE);
            ShowWindow(GetDlgItem(hwnd, PXPLODE_THREAD_ACL), SW_HIDE);
            ShowWindow(GetDlgItem(hwnd, PXPLODE_PROCESS_TOKEN_ACL), SW_HIDE);
            ShowWindow(GetDlgItem(hwnd, PXPLODE_THREAD_TOKEN_ACL), SW_HIDE);

            ShowWindow(GetDlgItem(hwnd, PXPLODE_TOKEN_GROUP), SW_HIDE);
            ShowWindow(GetDlgItem(hwnd, PXPLODE_PROCESS_TOKEN), SW_HIDE);
            ShowWindow(GetDlgItem(hwnd, PXPLODE_THREAD_TOKEN), SW_HIDE);
        }

        //
        // fall thru
        //

    case WM_HOTKEY:

        if ( wParam == 1 ) {
            PSYSTEM_PROCESS_INFORMATION ProcessInfo;
            NTSTATUS status;
            ULONG TotalOffset = 0;

            status = NtQuerySystemInformation(
                        SystemProcessInformation,
                        LargeBuffer1,
                        sizeof(LargeBuffer1),
                        NULL
                        );

            if (!NT_SUCCESS(status)) {
                EndDialog(hwnd, 0);
                return(FALSE);
                }

            ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)LargeBuffer1;
            DlgProcessInfo = ProcessInfo;
            Refresh = TRUE;
            InitProcessList(hwnd);
            Refresh = FALSE;

            ProcessList = GetDlgItem(hwnd, PXPLODE_PROCESS_LIST);
            nIndex = (int)SendMessage(ProcessList, CB_GETCURSEL, 0, 0);
            ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)SendMessage(
                                                        ProcessList,
                                                        CB_GETITEMDATA,
                                                        nIndex,
                                                        0
                                                        );
            if ( !ProcessInfo || CB_ERR == (LONG)ProcessInfo ) {
                ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)LargeBuffer1;
                }
            DlgProcessInfo = ProcessInfo;
            SetProcessFields(ProcessInfo,hwnd);

            SetForegroundWindow(hwnd);
            ShowWindow(hwnd, SW_NORMAL);
            }
        return FALSE;

    case WM_SYSCOMMAND:
        switch (wParam & 0xfff0) {
        case SC_CLOSE:
            EndDialog(hwnd, 0);
            return(TRUE);
        }
        return(FALSE);

    case WM_COMMAND:
        switch(LOWORD(wParam)) {

        case PXPLODE_THREAD_LIST:
            switch ( HIWORD(wParam) ) {
            case LBN_DBLCLK:
            case LBN_SELCHANGE:
                ThreadList = GetDlgItem(hwnd, PXPLODE_THREAD_LIST);
                nIndex = (int)SendMessage(ThreadList, LB_GETCURSEL, 0, 0);
                ThreadInfo = (PSYSTEM_THREAD_INFORMATION)SendMessage(
                                                            ThreadList,
                                                            LB_GETITEMDATA,
                                                            nIndex,
                                                            0
                                                            );
                if ( !ThreadInfo || LB_ERR == (LONG)ThreadInfo ) {
                    break;
                    }

                SetThreadFields(ThreadInfo,hwnd);
                break;
            }
            break;

        case PXPLODE_IMAGE_COMMIT:
            switch ( HIWORD(wParam) ) {
            case CBN_DBLCLK:
            case CBN_SELCHANGE:
                UpdateImageCommit(hwnd);
                break;
            }
            break;

        case PXPLODE_PROCESS_LIST:

            ProcessList = GetDlgItem(hwnd, PXPLODE_PROCESS_LIST);
            switch ( HIWORD(wParam) ) {
            case CBN_DBLCLK:
            case CBN_SELCHANGE:
                nIndex = (int)SendMessage(ProcessList, CB_GETCURSEL, 0, 0);
                SendMessage(ProcessList, CB_GETLBTEXT, nIndex, (LPARAM)LastProcess);
                ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)SendMessage(
                                                            ProcessList,
                                                            CB_GETITEMDATA,
                                                            nIndex,
                                                            0
                                                            );
                if ( !ProcessInfo || CB_ERR == (LONG)ProcessInfo ) {
                    break;
                    }

                DlgProcessInfo = ProcessInfo;
                SetProcessFields(ProcessInfo,hwnd);
                break;
            }
            break;

        case PXPLODE_EXIT:
            EndDialog(hwnd, 0);
            break;

        case PXPLODE_PRIORITY_NORMAL:
            hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,(DWORD)DlgProcessInfo->UniqueProcessId);
            SetPriorityClass(hProcess,NORMAL_PRIORITY_CLASS);
            CloseHandle(hProcess);
            goto refresh;
            break;

        case PXPLODE_PRIORITY_HIGH:
            hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,(DWORD)DlgProcessInfo->UniqueProcessId);
            SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS);
            CloseHandle(hProcess);
            goto refresh;
            break;

        case PXPLODE_PRIORITY_IDL:
            hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,(DWORD)DlgProcessInfo->UniqueProcessId);
            SetPriorityClass(hProcess,IDLE_PRIORITY_CLASS);
            CloseHandle(hProcess);
            goto refresh;
            break;

        case PXPLODE_HIDE:
            ShowWindow(hwnd,SW_HIDE);
            break;

        case PXPLODE_SHOWHEAPS:
        case PXPLODE_DUMPTOFILE:
            MessageBox(hwnd,"This function not implemented yet","Not Implemented",MB_ICONSTOP|MB_OK);
            break;

        case PXPLODE_PROCESS_ACL:
        case PXPLODE_PROCESS_TOKEN_ACL:
        case PXPLODE_PROCESS_TOKEN:
        {
            WCHAR Name[100];
            HANDLE Process;
            HANDLE Token;

            ProcessList = GetDlgItem(hwnd, PXPLODE_PROCESS_LIST);
            nIndex = (int)SendMessage(ProcessList, CB_GETCURSEL, 0, 0);

            ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)SendMessage(
                                                            ProcessList,
                                                            CB_GETITEMDATA,
                                                            nIndex,
                                                            0
                                                            );
            if ( !ProcessInfo || CB_ERR == (LONG)ProcessInfo ) {
                break;
                }

            SendMessageW(ProcessList, CB_GETLBTEXT, nIndex, (LPARAM)Name);

            switch(LOWORD(wParam)) {
            case PXPLODE_PROCESS_ACL:

                Process = OpenProcess(MAXIMUM_ALLOWED, FALSE, (DWORD)ProcessInfo->UniqueProcessId);
                if (Process != NULL) {
                    EditNtObjectSecurity(hwnd, Process, Name);
                    CloseHandle(Process);
                } else {
                    DbgPrint("Failed to open process for max allowed, error = %d\n", GetLastError());
                }
                break;

            default:

                Process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)ProcessInfo->UniqueProcessId);
                if (Process != NULL) {

                    if (OpenProcessToken(Process, MAXIMUM_ALLOWED, &Token)) {
                        if (LOWORD(wParam) == PXPLODE_PROCESS_TOKEN_ACL) {
                            EditNtObjectSecurity(hwnd, Token, Name);
                        } else {
                            HANDLE Token2;
                            if (OpenProcessToken(Process, TOKEN_QUERY, &Token2)) {
                                CloseHandle(Token2);
                                EditToken(hwnd, Token, Name);
                            } else {
                                MessageBox(hwnd,
                                   "You do not have permission to view the token on this process",
                                   "Access Denied", MB_ICONSTOP | MB_OK);
                            }
                        }
                        CloseHandle(Token);
                    } else {
                        MessageBox(hwnd,
                           "You do not have permission to access the token on this process",
                           "Access Denied", MB_ICONSTOP | MB_OK);
                    }
                    CloseHandle(Process);
                } else {
                    DbgPrint("Failed to open process for query information, error = %d\n", GetLastError());
                }
                break;
            }


            break;
        }

        case PXPLODE_THREAD_ACL:
        case PXPLODE_THREAD_TOKEN_ACL:
        case PXPLODE_THREAD_TOKEN:
        {
            WCHAR Name[100];
            HANDLE Thread;
            HANDLE Token;

            ThreadList = GetDlgItem(hwnd, PXPLODE_THREAD_LIST);
            nIndex = (int)SendMessage(ThreadList, LB_GETCURSEL, 0, 0);
            ThreadInfo = (PSYSTEM_THREAD_INFORMATION)SendMessage(
                                                        ThreadList,
                                                        LB_GETITEMDATA,
                                                        nIndex,
                                                        0
                                                        );
            if ( !ThreadInfo || LB_ERR == (LONG)ThreadInfo ) {
                break;
                }

            SendMessageW(ThreadList, LB_GETTEXT, nIndex, (LPARAM)Name);

            switch(LOWORD(wParam)) {
            case PXPLODE_THREAD_ACL:

                Thread = OpenThread(MAXIMUM_ALLOWED, FALSE, (DWORD)ThreadInfo->ClientId.UniqueThread);
                if (Thread != NULL) {
                    EditNtObjectSecurity(hwnd, Thread, Name);
                    CloseHandle(Thread);
                } else {
                    DbgPrint("Failed to open thread for max allowed, error = %d\n", GetLastError());
                }
                break;

            default:

                Thread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, (DWORD)ThreadInfo->ClientId.UniqueThread);
                if (Thread != NULL) {
                    if (OpenThreadToken(Thread, MAXIMUM_ALLOWED, TRUE, &Token)) {
                        if (LOWORD(wParam) == PXPLODE_THREAD_TOKEN_ACL) {
                            EditNtObjectSecurity(hwnd, Token, Name);
                        } else {
                            HANDLE Token2;
                            if (OpenThreadToken(Thread, TOKEN_QUERY, TRUE, &Token2)) {
                                CloseHandle(Token2);
                                EditToken(hwnd, Token, Name);
                            } else {
                                MessageBox(hwnd,
                                   "You do not have permission to view the token on this thread",
                                   "Access Denied", MB_ICONSTOP | MB_OK);
                            }
                        }
                        CloseHandle(Token);
                    } else {
                        DbgPrint("Failed to open thread token for max allowed, error = %d\n", GetLastError());
                    }
                    CloseHandle(Thread);
                } else {
                    DbgPrint("Failed to open thread for query information, error = %d\n", GetLastError());
                }
                break;
            }
            break;
        }

        case PXPLODE_TERMINATE:
            hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,(DWORD)DlgProcessInfo->UniqueProcessId);
            wsprintf(Buffer,"Selecting OK will terminate %s... Do you really want to do this ?",LastProcess);
            if ( MessageBox(hwnd,Buffer,"Terminate Process",MB_ICONSTOP|MB_OKCANCEL) == IDOK ) {
                TerminateProcess(hProcess,99);
                }
            CloseHandle(hProcess);

            //
            // fall thru
            //

        case PXPLODE_REFRESH:
refresh:
            {
                PSYSTEM_PROCESS_INFORMATION ProcessInfo;
                NTSTATUS status;
                ULONG TotalOffset = 0;

                ProcessList = GetDlgItem(hwnd, PXPLODE_PROCESS_LIST);
                status = NtQuerySystemInformation(
                            SystemProcessInformation,
                            LargeBuffer1,
                            sizeof(LargeBuffer1),
                            NULL
                            );

                if (!NT_SUCCESS(status)) {
                    ExitProcess(status);
                    }

                ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)LargeBuffer1;
                DlgProcessInfo = ProcessInfo;
                Refresh = TRUE;
                InitProcessList(hwnd);
                Refresh = FALSE;
                nIndex = (int)SendMessage(ProcessList, CB_GETCURSEL, 0, 0);
                ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)SendMessage(
                                                            ProcessList,
                                                            CB_GETITEMDATA,
                                                            nIndex,
                                                            0
                                                            );
                if ( !ProcessInfo || CB_ERR == (LONG)ProcessInfo ) {
                    ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)LargeBuffer1;
                    }
                DlgProcessInfo = ProcessInfo;
                SetProcessFields(ProcessInfo,hwnd);
            }
            return FALSE;
        }
    default:
        return FALSE;
    }

    return TRUE;
}
예제 #19
0
INT_PTR CALLBACK PhpEventPageProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
)
{
    PCOMMON_PAGE_CONTEXT pageContext;

    pageContext = PhpCommonPageHeader(hwndDlg, uMsg, wParam, lParam);

    if (!pageContext)
        return FALSE;

    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        PhpRefreshEventPageInfo(hwndDlg, pageContext);
    }
    break;
    case WM_COMMAND:
    {
        switch (LOWORD(wParam))
        {
        case IDC_SET:
        case IDC_RESET:
        case IDC_PULSE:
        {
            NTSTATUS status;
            HANDLE eventHandle;

            if (NT_SUCCESS(status = pageContext->OpenObject(
                                        &eventHandle,
                                        EVENT_MODIFY_STATE,
                                        pageContext->Context
                                    )))
            {
                switch (LOWORD(wParam))
                {
                case IDC_SET:
                    NtSetEvent(eventHandle, NULL);
                    break;
                case IDC_RESET:
                    NtResetEvent(eventHandle, NULL);
                    break;
                case IDC_PULSE:
                    NtPulseEvent(eventHandle, NULL);
                    break;
                }

                NtClose(eventHandle);
            }

            PhpRefreshEventPageInfo(hwndDlg, pageContext);

            if (!NT_SUCCESS(status))
                PhShowStatus(hwndDlg, L"Unable to open the event", status, 0);
        }
        break;
        }
    }
    break;
    }

    return FALSE;
}
예제 #20
0
파일: pview.c 프로젝트: mingpen/OpenNT
VOID
SetThreadFields(
    PSYSTEM_THREAD_INFORMATION ThreadInfo,
    HWND hwnd
    )
{
    TIME_FIELDS UserTime;
    TIME_FIELDS KernelTime;
    TIME_FIELDS RunTime;
    LARGE_INTEGER Time;
    CHAR TimeString[15];
    CHAR StartString[32];
    HANDLE hThread;
    CONTEXT ThreadContext;
    NTSTATUS Status;
    OBJECT_ATTRIBUTES Obja;
    ULONG PcValue;

    //
    // Display the selected thread information
    //

    //
    // Compute runtimes
    //

    RtlTimeToTimeFields ( &ThreadInfo->UserTime, &UserTime);
    RtlTimeToTimeFields ( &ThreadInfo->KernelTime, &KernelTime);

    RtlTimeToTimeFields ( &ThreadInfo->UserTime, &UserTime);
    RtlTimeToTimeFields ( &ThreadInfo->KernelTime, &KernelTime);
    Time.QuadPart = RefreshTimeOfDayInfo.CurrentTime.QuadPart - ThreadInfo->CreateTime.QuadPart;
    RtlTimeToTimeFields ( &Time, &RunTime);
    wsprintf(TimeString,"%3ld:%02ld:%02ld.%03ld",
                RunTime.Hour,
                RunTime.Minute,
                RunTime.Second,
                RunTime.Milliseconds
                );
    SetDlgItemText(
        hwnd,
        PXPLODE_THREADELAPSED_TIME,
        TimeString
        );

    wsprintf(TimeString,"%3ld:%02ld:%02ld.%03ld",
                UserTime.Hour,
                UserTime.Minute,
                UserTime.Second,
                UserTime.Milliseconds
                );
    SetDlgItemText(
        hwnd,
        PXPLODE_THREADUSER_TIME,
        TimeString
        );

    wsprintf(TimeString,"%3ld:%02ld:%02ld.%03ld",
                KernelTime.Hour,
                KernelTime.Minute,
                KernelTime.Second,
                KernelTime.Milliseconds
                );
    SetDlgItemText(
        hwnd,
        PXPLODE_THREADKERNEL_TIME,
        TimeString
        );

    wsprintf(StartString,"0x%08lx",
                ThreadInfo->StartAddress
                );
    SetDlgItemText(
        hwnd,
        PXPLODE_THREAD_START,
        StartString
        );

    //
    // Do the priority Group
    //

    SetDlgItemInt(
        hwnd,
        PXPLODE_THREAD_DYNAMIC,
        ThreadInfo->Priority,
        FALSE
        );
    switch ( ThreadInfo->BasePriority - DlgProcessInfo->BasePriority ) {

        case 2:
            CheckRadioButton(
                hwnd,
                PXPLODE_THREAD_HIGHEST,
                PXPLODE_THREAD_LOWEST,
                PXPLODE_THREAD_HIGHEST
                );
            break;

        case 1:
            CheckRadioButton(
                hwnd,
                PXPLODE_THREAD_HIGHEST,
                PXPLODE_THREAD_LOWEST,
                PXPLODE_THREAD_ABOVE
                );
            break;

        case -1:
            CheckRadioButton(
                hwnd,
                PXPLODE_THREAD_HIGHEST,
                PXPLODE_THREAD_LOWEST,
                PXPLODE_THREAD_BELOW
                );
            break;
        case -2:
            CheckRadioButton(
                hwnd,
                PXPLODE_THREAD_HIGHEST,
                PXPLODE_THREAD_LOWEST,
                PXPLODE_THREAD_LOWEST
                );
            break;
        case 0:
        default:
            CheckRadioButton(
                hwnd,
                PXPLODE_THREAD_HIGHEST,
                PXPLODE_THREAD_LOWEST,
                PXPLODE_THREAD_NORMAL
                );
            break;
        }
    //
    // Complete thread information
    //

    SetDlgItemInt(
        hwnd,
        PXPLODE_THREAD_SWITCHES,
        ThreadInfo->ContextSwitches,
        FALSE
        );

    PcValue = 0;
    InitializeObjectAttributes(&Obja, NULL, 0, NULL, NULL);
    Status = NtOpenThread(
                &hThread,
                THREAD_GET_CONTEXT,
                &Obja,
                &ThreadInfo->ClientId
                );
    if ( NT_SUCCESS(Status) ) {
        ThreadContext.ContextFlags = CONTEXT_CONTROL;
        Status = NtGetContextThread(hThread,&ThreadContext);
        NtClose(hThread);
        if ( NT_SUCCESS(Status) ) {
            PcValue = (ULONG) CONTEXT_TO_PROGRAM_COUNTER(&ThreadContext);
            }
        }
    if ( PcValue ) {
        wsprintf(StartString,"0x%08lx",
                    PcValue
                    );
        SetDlgItemText(
            hwnd,
            PXPLODE_THREAD_PC,
            StartString
            );
        }
    else {
        SetDlgItemText(
            hwnd,
            PXPLODE_THREAD_PC,
            "Unknown"
            );
        }


    //
    // Disable the thread buttons if we can't get at the thread or it's token
    //

    {
        HANDLE Thread;
        HANDLE Token;
        BOOL ThreadOK = FALSE;
        BOOL GotToken = FALSE;

        Thread = OpenThread(MAXIMUM_ALLOWED, FALSE, (DWORD)ThreadInfo->ClientId.UniqueThread);
        if (Thread != NULL) {

            ThreadOK = TRUE;

            if (OpenThreadToken(Thread, MAXIMUM_ALLOWED, TRUE, &Token)) {
                GotToken = TRUE;
                CloseHandle(Token);
            }
            CloseHandle(Thread);
        }

        EnableWindow(GetDlgItem(hwnd, PXPLODE_THREAD_ACL), ThreadOK);

        EnableWindow(GetDlgItem(hwnd, PXPLODE_THREAD_TOKEN), GotToken);
        EnableWindow(GetDlgItem(hwnd, PXPLODE_THREAD_TOKEN_ACL), GotToken);
    }
}
예제 #21
0
INT_PTR CALLBACK PhpSemaphorePageProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
)
{
    PCOMMON_PAGE_CONTEXT pageContext;

    pageContext = PhpCommonPageHeader(hwndDlg, uMsg, wParam, lParam);

    if (!pageContext)
        return FALSE;

    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        PhpRefreshSemaphorePageInfo(hwndDlg, pageContext);
    }
    break;
    case WM_COMMAND:
    {
        switch (LOWORD(wParam))
        {
        case IDC_ACQUIRE:
        case IDC_RELEASE:
        {
            NTSTATUS status;
            HANDLE semaphoreHandle;

            if (NT_SUCCESS(status = pageContext->OpenObject(
                                        &semaphoreHandle,
                                        LOWORD(wParam) == IDC_ACQUIRE ? SYNCHRONIZE : SEMAPHORE_MODIFY_STATE,
                                        pageContext->Context
                                    )))
            {
                switch (LOWORD(wParam))
                {
                case IDC_ACQUIRE:
                {
                    LARGE_INTEGER timeout;

                    timeout.QuadPart = 0;
                    NtWaitForSingleObject(semaphoreHandle, FALSE, &timeout);
                }
                break;
                case IDC_RELEASE:
                    NtReleaseSemaphore(semaphoreHandle, 1, NULL);
                    break;
                }

                NtClose(semaphoreHandle);
            }

            PhpRefreshSemaphorePageInfo(hwndDlg, pageContext);

            if (!NT_SUCCESS(status))
                PhShowStatus(hwndDlg, L"Unable to open the semaphore", status, 0);
        }
        break;
        }
    }
    break;
    }

    return FALSE;
}
예제 #22
0
파일: moufiltr.c 프로젝트: kcrazy/winekit
VOID
MouFilter_EvtIoInternalDeviceControl(
    IN WDFQUEUE      Queue,
    IN WDFREQUEST    Request,
    IN size_t        OutputBufferLength,
    IN size_t        InputBufferLength,
    IN ULONG         IoControlCode
)
/*++

Routine Description:

    This routine is the dispatch routine for internal device control requests.
    There are two specific control codes that are of interest:

    IOCTL_INTERNAL_MOUSE_CONNECT:
        Store the old context and function pointer and replace it with our own.
        This makes life much simpler than intercepting IRPs sent by the RIT and
        modifying them on the way back up.

    IOCTL_INTERNAL_I8042_HOOK_MOUSE:
        Add in the necessary function pointers and context values so that we can
        alter how the ps/2 mouse is initialized.

    NOTE:  Handling IOCTL_INTERNAL_I8042_HOOK_MOUSE is *NOT* necessary if
           all you want to do is filter MOUSE_INPUT_DATAs.  You can remove
           the handling code and all related device extension fields and
           functions to conserve space.


--*/
{

    PDEVICE_EXTENSION           devExt;
    PCONNECT_DATA               connectData;
    PINTERNAL_I8042_HOOK_MOUSE  hookMouse;
    NTSTATUS                   status = STATUS_SUCCESS;
    WDFDEVICE                 hDevice;
    size_t                           length;

    UNREFERENCED_PARAMETER(OutputBufferLength);
    UNREFERENCED_PARAMETER(InputBufferLength);

    PAGED_CODE();

    hDevice = WdfIoQueueGetDevice(Queue);
    devExt = FilterGetData(hDevice);

    switch (IoControlCode) {

    //
    // Connect a mouse class device driver to the port driver.
    //
    case IOCTL_INTERNAL_MOUSE_CONNECT:
        //
        // Only allow one connection.
        //
        if (devExt->UpperConnectData.ClassService != NULL) {
            status = STATUS_SHARING_VIOLATION;
            break;
        }

        //
        // Copy the connection parameters to the device extension.
        //
        status = WdfRequestRetrieveInputBuffer(Request,
                                               sizeof(CONNECT_DATA),
                                               &connectData,
                                               &length);
        if(!NT_SUCCESS(status)) {
            DebugPrint(("WdfRequestRetrieveInputBuffer failed %x\n", status));
            break;
        }


        devExt->UpperConnectData = *connectData;

        //
        // Hook into the report chain.  Everytime a mouse packet is reported to
        // the system, MouFilter_ServiceCallback will be called
        //
        connectData->ClassDeviceObject = WdfDeviceWdmGetDeviceObject(hDevice);
        connectData->ClassService = MouFilter_ServiceCallback;

        break;

    //
    // Disconnect a mouse class device driver from the port driver.
    //
    case IOCTL_INTERNAL_MOUSE_DISCONNECT:

        //
        // Clear the connection parameters in the device extension.
        //
        // devExt->UpperConnectData.ClassDeviceObject = NULL;
        // devExt->UpperConnectData.ClassService = NULL;

        status = STATUS_NOT_IMPLEMENTED;
        break;

    //
    // Attach this driver to the initialization and byte processing of the
    // i8042 (ie PS/2) mouse.  This is only necessary if you want to do PS/2
    // specific functions, otherwise hooking the CONNECT_DATA is sufficient
    //
    case IOCTL_INTERNAL_I8042_HOOK_MOUSE:

        DebugPrint(("hook mouse received!\n"));

        // Get the input buffer from the request
        // (Parameters.DeviceIoControl.Type3InputBuffer)
        //
        status = WdfRequestRetrieveInputBuffer(Request,
                                               sizeof(INTERNAL_I8042_HOOK_MOUSE),
                                               &hookMouse,
                                               &length);
        if(!NT_SUCCESS(status)) {
            DebugPrint(("WdfRequestRetrieveInputBuffer failed %x\n", status));
            break;
        }

        //
        // Set isr routine and context and record any values from above this driver
        //
        devExt->UpperContext = hookMouse->Context;
        hookMouse->Context = (PVOID) devExt;

        if (hookMouse->IsrRoutine) {
            devExt->UpperIsrHook = hookMouse->IsrRoutine;
        }
        hookMouse->IsrRoutine = (PI8042_MOUSE_ISR) MouFilter_IsrHook;

        //
        // Store all of the other functions we might need in the future
        //
        devExt->IsrWritePort = hookMouse->IsrWritePort;
        devExt->CallContext = hookMouse->CallContext;
        devExt->QueueMousePacket = hookMouse->QueueMousePacket;

        status = STATUS_SUCCESS;
        break;

    //
    // Might want to capture this in the future.  For now, then pass it down
    // the stack.  These queries must be successful for the RIT to communicate
    // with the mouse.
    //
    case IOCTL_MOUSE_QUERY_ATTRIBUTES:
    default:
        break;
    }

    if (!NT_SUCCESS(status)) {
        WdfRequestComplete(Request, status);
        return ;
    }

    MouFilter_DispatchPassThrough(Request,WdfDeviceGetIoTarget(hDevice));
}
예제 #23
0
NTSTATUS
NTAPI
InitVideo()
{
    ULONG iDevNum, iVGACompatible = -1, ulMaxObjectNumber = 0;
    WCHAR awcDeviceName[20];
    WCHAR awcBuffer[256];
    NTSTATUS Status;
    PGRAPHICS_DEVICE pGraphicsDevice;
    ULONG cbValue;
    HKEY hkey;

    TRACE("----------------------------- InitVideo() -------------------------------\n");

    /* Open the key for the boot command line */
    Status = RegOpenKey(L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control", &hkey);
    if (NT_SUCCESS(Status))
    {
        cbValue = 256;
        Status = RegQueryValue(hkey, L"SystemStartOptions", REG_SZ, awcBuffer, &cbValue);
        if (NT_SUCCESS(Status))
        {
            /* Check if VGA mode is requested. */
            if (wcsstr(awcBuffer, L"/BASEVIDEO") != 0)
            {
                ERR("VGA mode requested.\n");
                gbBaseVideo = TRUE;
            }
        }

        ZwClose(hkey);
    }

    /* Open the key for the adapters */
    Status = RegOpenKey(KEY_VIDEO, &hkey);
    if (!NT_SUCCESS(Status))
    {
        ERR("Could not open device registry key!\n");
        return Status;
    }

    /* Read the name of the VGA adapter */
    cbValue = 20;
    Status = RegQueryValue(hkey, L"VgaCompatible", REG_SZ, awcDeviceName, &cbValue);
    if (NT_SUCCESS(Status))
    {
        iVGACompatible = _wtoi(&awcDeviceName[13]);
        ERR("VGA adapter = %ld\n", iVGACompatible);
    }

    /* Get the maximum mumber of adapters */
    if (!RegReadDWORD(hkey, L"MaxObjectNumber", &ulMaxObjectNumber))
    {
        ERR("Could not read MaxObjectNumber, defaulting to 0.\n");
    }

    TRACE("Found %ld devices\n", ulMaxObjectNumber);

    /* Loop through all adapters */
    for (iDevNum = 0; iDevNum <= ulMaxObjectNumber; iDevNum++)
    {
        /* Create the adapter's key name */
        swprintf(awcDeviceName, L"\\Device\\Video%lu", iDevNum);

        /* Read the reg key name */
        cbValue = sizeof(awcBuffer);
        Status = RegQueryValue(hkey, awcDeviceName, REG_SZ, awcBuffer, &cbValue);
        if (!NT_SUCCESS(Status))
        {
            ERR("failed to query the registry path:0x%lx\n", Status);
            continue;
        }

        /* Initialize the driver for this device */
        pGraphicsDevice = InitDisplayDriver(awcDeviceName, awcBuffer);
        if (!pGraphicsDevice) continue;

        /* Check if this is the VGA adapter */
        if (iDevNum == iVGACompatible)
        {
            /* Set the VGA device as primary */
            gpVgaGraphicsDevice = pGraphicsDevice;
            ERR("gpVgaGraphicsDevice = %p\n", gpVgaGraphicsDevice);
        }

        /* Set the first one as primary device */
        if (!gpPrimaryGraphicsDevice)
            gpPrimaryGraphicsDevice = pGraphicsDevice;
    }

    /* Close the device map registry key */
    ZwClose(hkey);

    /* Check if we had any success */
    if (!gpPrimaryGraphicsDevice)
    {
        ERR("No usable display driver was found.\n");
        return STATUS_UNSUCCESSFUL;
    }

    if (gbBaseVideo)
    {
        if (gpVgaGraphicsDevice)
        {
            /* Set the VgaAdapter as primary */
            gpPrimaryGraphicsDevice = gpVgaGraphicsDevice;
            // FIXME: DEVMODE
        }
        else
        {
            ERR("Could not find VGA compatible driver. Trying normal.\n");
        }
    }

    InitSysParams();

    return 1;
}
예제 #24
0
파일: moufiltr.c 프로젝트: kcrazy/winekit
NTSTATUS
MouFilter_EvtDeviceAdd(
    IN WDFDRIVER        Driver,
    IN PWDFDEVICE_INIT  DeviceInit
)
/*++
Routine Description:

    EvtDeviceAdd is called by the framework in response to AddDevice
    call from the PnP manager. Here you can query the device properties
    using WdfFdoInitWdmGetPhysicalDevice/IoGetDeviceProperty and based
    on that, decide to create a filter device object and attach to the
    function stack.

    If you are not interested in filtering this particular instance of the
    device, you can just return STATUS_SUCCESS without creating a framework
    device.

Arguments:

    Driver - Handle to a framework driver object created in DriverEntry

    DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure.

Return Value:

    NTSTATUS

--*/
{
    WDF_OBJECT_ATTRIBUTES   deviceAttributes;
    NTSTATUS                            status;
    WDFDEVICE                          hDevice;
    WDF_IO_QUEUE_CONFIG        ioQueueConfig;

    UNREFERENCED_PARAMETER(Driver);

    PAGED_CODE();

    DebugPrint(("Enter FilterEvtDeviceAdd \n"));

    //
    // Tell the framework that you are filter driver. Framework
    // takes care of inherting all the device flags & characterstics
    // from the lower device you are attaching to.
    //
    WdfFdoInitSetFilter(DeviceInit);

    WdfDeviceInitSetDeviceType(DeviceInit, FILE_DEVICE_MOUSE);

    WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&deviceAttributes,
                                            DEVICE_EXTENSION);


    //
    // Create a framework device object.  This call will in turn create
    // a WDM deviceobject, attach to the lower stack and set the
    // appropriate flags and attributes.
    //
    status = WdfDeviceCreate(&DeviceInit, &deviceAttributes, &hDevice);
    if (!NT_SUCCESS(status)) {
        DebugPrint(("WdfDeviceCreate failed with status code 0x%x\n", status));
        return status;
    }


    //
    // Configure the default queue to be Parallel. Do not use sequential queue
    // if this driver is going to be filtering PS2 ports because it can lead to
    // deadlock. The PS2 port driver sends a request to the top of the stack when it
    // receives an ioctl request and waits for it to be completed. If you use a
    // a sequential queue, this request will be stuck in the queue because of the
    // outstanding ioctl request sent earlier to the port driver.
    //
    WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&ioQueueConfig,
                                           WdfIoQueueDispatchParallel);

    //
    // Framework by default creates non-power managed queues for
    // filter drivers.
    //
    ioQueueConfig.EvtIoInternalDeviceControl = MouFilter_EvtIoInternalDeviceControl;

    status = WdfIoQueueCreate(hDevice,
                              &ioQueueConfig,
                              WDF_NO_OBJECT_ATTRIBUTES,
                              WDF_NO_HANDLE // pointer to default queue
                             );
    if (!NT_SUCCESS(status)) {
        DebugPrint( ("WdfIoQueueCreate failed 0x%x\n", status));
        return status;
    }

    return status;
}
예제 #25
0
LONG
APIENTRY
UserChangeDisplaySettings(
   PUNICODE_STRING pustrDevice,
   LPDEVMODEW pdm,
   HWND hwnd,
   DWORD flags,
   LPVOID lParam)
{
    DEVMODEW dm;
    LONG lResult = DISP_CHANGE_SUCCESSFUL;
    HKEY hkey;
    NTSTATUS Status;
    PPDEVOBJ ppdev;
    PDESKTOP pdesk;

    /* If no DEVMODE is given, use registry settings */
    if (!pdm)
    {
        /* Get the registry settings */
        Status = UserEnumRegistryDisplaySettings(pustrDevice, &dm);
        if (!NT_SUCCESS(Status))
        {
            ERR("Could not load registry settings\n");
            return DISP_CHANGE_BADPARAM;
        }
    }
    else if (pdm->dmSize < FIELD_OFFSET(DEVMODEW, dmFields))
        return DISP_CHANGE_BADMODE; /* This is what winXP SP3 returns */
    else
        dm = *pdm;

    /* Check params */
    if ((dm.dmFields & (DM_PELSWIDTH | DM_PELSHEIGHT)) != (DM_PELSWIDTH | DM_PELSHEIGHT))
    {
        ERR("devmode doesn't specify the resolution.\n");
        return DISP_CHANGE_BADMODE;
    }

    /* Get the PDEV */
    ppdev = EngpGetPDEV(pustrDevice);
    if (!ppdev)
    {
        ERR("failed to get PDEV\n");
        return DISP_CHANGE_BADPARAM;
    }

    /* Fixup values */
    if(dm.dmBitsPerPel == 0 || !(dm.dmFields & DM_BITSPERPEL))
    {
        dm.dmBitsPerPel = ppdev->pdmwDev->dmBitsPerPel;
        dm.dmFields |= DM_BITSPERPEL;
    }

    if((dm.dmFields & DM_DISPLAYFREQUENCY) && (dm.dmDisplayFrequency == 0))
        dm.dmDisplayFrequency = ppdev->pdmwDev->dmDisplayFrequency;

    /* Look for the requested DEVMODE */
    pdm = PDEVOBJ_pdmMatchDevMode(ppdev, &dm);
    if (!pdm)
    {
        ERR("Could not find a matching DEVMODE\n");
        lResult = DISP_CHANGE_BADMODE;
        goto leave;
    }
    else if (flags & CDS_TEST)
    {
        /* It's possible, go ahead! */
        lResult = DISP_CHANGE_SUCCESSFUL;
        goto leave;
    }

    /* Shall we update the registry? */
    if (flags & CDS_UPDATEREGISTRY)
    {
        /* Open the local or global settings key */
        Status = UserOpenDisplaySettingsKey(&hkey, pustrDevice, flags & CDS_GLOBAL);
        if (NT_SUCCESS(Status))
        {
            /* Store the settings */
            RegWriteDisplaySettings(hkey, pdm);

            /* Close the registry key */
            ZwClose(hkey);
        }
        else
        {
            ERR("Could not open registry key\n");
            lResult = DISP_CHANGE_NOTUPDATED;
        }
    }

    /* Check if DEVMODE matches the current mode */
    if (pdm == ppdev->pdmwDev && !(flags & CDS_RESET))
    {
        ERR("DEVMODE matches, nothing to do\n");
        goto leave;
    }

    /* Shall we apply the settings? */
    if (!(flags & CDS_NORESET))
    {
        ULONG ulResult;
        PVOID pvOldCursor;

        /* Remove mouse pointer */
        pvOldCursor = UserSetCursor(NULL, TRUE);

        /* Do the mode switch */
        ulResult = PDEVOBJ_bSwitchMode(ppdev, pdm);

        /* Restore mouse pointer, no hooks called */
        UserSetCursor(pvOldCursor, TRUE);

        /* Check for failure */
        if (!ulResult)
        {
            ERR("failed to set mode\n");
            lResult = (lResult == DISP_CHANGE_NOTUPDATED) ?
                DISP_CHANGE_FAILED : DISP_CHANGE_RESTART;

            goto leave;
        }

        /* Update the system metrics */
        InitMetrics();

        //IntvGetDeviceCaps(&PrimarySurface, &GdiHandleTable->DevCaps);

        /* Set new size of the monitor */
        IntUpdateMonitorSize(ppdev);

        /* Remove all cursor clipping */
        UserClipCursor(NULL);

        pdesk = IntGetActiveDesktop();
        //IntHideDesktop(pdesk);

        /* Send WM_DISPLAYCHANGE to all toplevel windows */
        co_IntSendMessageTimeout(HWND_BROADCAST,
                                 WM_DISPLAYCHANGE,
                                 (WPARAM)ppdev->gdiinfo.cBitsPixel,
                                 (LPARAM)(ppdev->gdiinfo.ulHorzRes + (ppdev->gdiinfo.ulVertRes << 16)),
                                 SMTO_NORMAL,
                                 100,
                                 &ulResult);

        //co_IntShowDesktop(pdesk, ppdev->gdiinfo.ulHorzRes, ppdev->gdiinfo.ulVertRes);

        UserRedrawDesktop();
    }

leave:
    /* Release the PDEV */
    PDEVOBJ_vRelease(ppdev);

    return lResult;
}
예제 #26
0
static
NTSTATUS
BuildTokenInformationBuffer(PLSA_TOKEN_INFORMATION_V1 *TokenInformation,
                            PRPC_SID AccountDomainSid,
                            PSAMPR_USER_INFO_BUFFER UserInfo)
{
    PLSA_TOKEN_INFORMATION_V1 Buffer = NULL;
    ULONG i;
    NTSTATUS Status = STATUS_SUCCESS;

    Buffer = DispatchTable.AllocateLsaHeap(sizeof(LSA_TOKEN_INFORMATION_V1));
    if (Buffer == NULL)
    {
        TRACE("Failed to allocate the local buffer!\n");
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto done;
    }

    /* FIXME: */
    Buffer->ExpirationTime.QuadPart = -1;

    Status = BuildTokenUser(&Buffer->User,
                            (PSID)AccountDomainSid,
                            UserInfo->All.UserId);
    if (!NT_SUCCESS(Status))
        goto done;

    Status = BuildTokenPrimaryGroup(&Buffer->PrimaryGroup,
                                    (PSID)AccountDomainSid,
                                    UserInfo->All.PrimaryGroupId);
    if (!NT_SUCCESS(Status))
        goto done;

    Status = BuildTokenGroups(&Buffer->Groups,
                              (PSID)AccountDomainSid);
    if (!NT_SUCCESS(Status))
        goto done;

    *TokenInformation = Buffer;

done:
    if (!NT_SUCCESS(Status))
    {
        if (Buffer != NULL)
        {
            if (Buffer->User.User.Sid != NULL)
                DispatchTable.FreeLsaHeap(Buffer->User.User.Sid);

            if (Buffer->Groups != NULL)
            {
                for (i = 0; i < Buffer->Groups->GroupCount; i++)
                {
                    if (Buffer->Groups->Groups[i].Sid != NULL)
                        DispatchTable.FreeLsaHeap(Buffer->Groups->Groups[i].Sid);
                }

                DispatchTable.FreeLsaHeap(Buffer->Groups);
            }

            if (Buffer->PrimaryGroup.PrimaryGroup != NULL)
                DispatchTable.FreeLsaHeap(Buffer->PrimaryGroup.PrimaryGroup);

            if (Buffer->DefaultDacl.DefaultDacl != NULL)
                DispatchTable.FreeLsaHeap(Buffer->DefaultDacl.DefaultDacl);

            DispatchTable.FreeLsaHeap(Buffer);
        }
    }

    return Status;
}
예제 #27
0
VOID
NdisProtEvtIoWrite(
    IN WDFQUEUE         Queue,
    IN WDFREQUEST       Request,
    IN size_t           Length
    )
/*++

Routine Description:

    Dispatch routine to handle Request_MJ_WRITE.

Arguments:

    Queue - Default queue handle
    Request - Handle to the read/write request
    Lenght - Length of the data buffer associated with the request.
                 The default property of the queue is to not dispatch
                 zero lenght read & write requests to the driver and
                 complete is with status success. So we will never get
                 a zero length request.

Return Value:

    VOID

--*/
{
    ULONG                   DataLength;
    NTSTATUS                NtStatus;
    PNDISPROT_OPEN_CONTEXT  pOpenContext;
    PNET_BUFFER_LIST        pNetBufferList;
    NDISPROT_ETH_HEADER UNALIGNED *pEthHeader;
    PVOID                   CancelId;
    ULONG                   SendFlags = 0;
    PMDL                    pMdl = NULL;
    WDFFILEOBJECT           fileObject;
    PREQUEST_CONTEXT        reqContext;
    WDF_OBJECT_ATTRIBUTES   attributes;

    UNREFERENCED_PARAMETER(Queue);

    fileObject = WdfRequestGetFileObject(Request);
    pOpenContext = GetFileObjectContext(fileObject)->OpenContext;

    do
    {
        //
        // Create a context to track the length of transfer and NDIS packet
        // associated with this request.
        //
        WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, REQUEST_CONTEXT);

        NtStatus = WdfObjectAllocateContext(Request, &attributes, &reqContext);
        if(!NT_SUCCESS(NtStatus)){
            DEBUGP(DL_WARN, ("Write: WdfObjectAllocateContext failed: %x\n", NtStatus));
            NtStatus = STATUS_INVALID_HANDLE;
            break;

        }

        reqContext->Length = (ULONG) Length;

        if (pOpenContext == NULL)
        {
            DEBUGP(DL_WARN, ("Write: FileObject %p not yet associated with a device\n",
                fileObject));
            NtStatus = STATUS_INVALID_HANDLE;
            break;
        }

        NPROT_STRUCT_ASSERT(pOpenContext, oc);

        NtStatus = WdfRequestRetrieveInputWdmMdl(Request, &pMdl);
        if (!NT_SUCCESS(NtStatus))
        {
            DEBUGP(DL_FATAL, ("Write: WdfRequestRetrieveInputWdmMdl failed %x\n", NtStatus));
            break;
        }

        //
        // Try to get a virtual address for the MDL.
        //
        pEthHeader = MmGetSystemAddressForMdlSafe(pMdl, NormalPagePriority);

        if (pEthHeader == NULL)
        {
            DEBUGP(DL_FATAL, ("Write: MmGetSystemAddr failed for"
                    " Request %p, MDL %p\n",
                    Request, pMdl));
            NtStatus = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        //
        // Sanity-check the length.
        //
        DataLength = MmGetMdlByteCount(pMdl);
        if (DataLength < sizeof(NDISPROT_ETH_HEADER))
        {
            DEBUGP(DL_WARN, ("Write: too small to be a valid packet (%d bytes)\n",
                DataLength));
            NtStatus = STATUS_BUFFER_TOO_SMALL;
            break;
        }

        if (DataLength > (pOpenContext->MaxFrameSize + sizeof(NDISPROT_ETH_HEADER)))
        {
            DEBUGP(DL_WARN, ("Write: Open %p: data length (%d)"
                    " larger than max frame size (%d)\n",
                    pOpenContext, DataLength, pOpenContext->MaxFrameSize));

            NtStatus = STATUS_INVALID_BUFFER_SIZE;
            break;
        }

        //
        // To prevent applications from sending packets with spoofed
        // mac address, we will do the following check to make sure the source
        // address in the packet is same as the current MAC address of the NIC.
        //
        if ((WdfRequestGetRequestorMode(Request) == UserMode) &&
            !NPROT_MEM_CMP(pEthHeader->SrcAddr, pOpenContext->CurrentAddress, NPROT_MAC_ADDR_LEN))
        {
            DEBUGP(DL_WARN, ("Write: Failing with invalid Source address"));
            NtStatus = STATUS_INVALID_PARAMETER;
            break;
        }

        NPROT_ACQUIRE_LOCK(&pOpenContext->Lock, FALSE);

        if (!NPROT_TEST_FLAGS(pOpenContext->Flags, NPROTO_BIND_FLAGS, NPROTO_BIND_ACTIVE))
        {
            NPROT_RELEASE_LOCK(&pOpenContext->Lock, FALSE);

            DEBUGP(DL_FATAL, ("Write: Open %p is not bound"
            " or in low power state\n", pOpenContext));

            NtStatus = STATUS_INVALID_HANDLE;
            break;
        }

        if ((pOpenContext->State == NdisprotPaused)
            || (pOpenContext->State == NdisprotPausing))
        {
            NPROT_RELEASE_LOCK(&pOpenContext->Lock, FALSE);

            DEBUGP(DL_INFO, ("Device is paused.\n"));
            NtStatus = STATUS_UNSUCCESSFUL;
            break;
        }

        NPROT_ASSERT(pOpenContext->SendNetBufferListPool != NULL);
        pNetBufferList = NdisAllocateNetBufferAndNetBufferList(
                                pOpenContext->SendNetBufferListPool,
                                sizeof(NPROT_SEND_NETBUFLIST_RSVD), //Request control offset delta
                                0,           // back fill size
                                pMdl,
                                0,          // Data offset
                                DataLength);

        if (pNetBufferList == NULL)
        {
            NPROT_RELEASE_LOCK(&pOpenContext->Lock, FALSE);

            DEBUGP(DL_FATAL, ("Write: open %p, failed to alloc send net buffer list\n",
                    pOpenContext));
            NtStatus = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }
        pOpenContext->PendedSendCount++;

        NPROT_REF_OPEN(pOpenContext);  // pended send

        //
        //  Initialize the NetBufferList ref count. This NetBufferList will be freed
        //  when this count goes to zero.
        //
        NPROT_SEND_NBL_RSVD(pNetBufferList)->RefCount = 1;

        //
        //  We set up a cancel ID on each send NetBufferList (which maps to a Write IRP),
        //  and save the NetBufferList pointer in the IRP. If the IRP gets cancelled, we use
        //  NdisCancelSendNetBufferLists() to cancel the NetBufferList.
        //
        //  Note that this sample code does not implement the cancellation logic. An actual
        //  driver may find value in implementing this.
        //

        CancelId = NPROT_GET_NEXT_CANCEL_ID();
        NDIS_SET_NET_BUFFER_LIST_CANCEL_ID(pNetBufferList, CancelId);
        reqContext->NetBufferList = (PVOID)pNetBufferList;

        NPROT_RELEASE_LOCK(&pOpenContext->Lock, FALSE);

        //
        //  Set a back pointer from the packet to the IRP.
        //
        NPROT_REQUEST_FROM_SEND_NBL(pNetBufferList) = Request;

        NtStatus = STATUS_PENDING;

        pNetBufferList->SourceHandle = pOpenContext->BindingHandle;
        NPROT_ASSERT (pMdl->Next == NULL);

        SendFlags |= NDIS_SEND_FLAGS_CHECK_FOR_LOOPBACK;

        NdisSendNetBufferLists(
                        pOpenContext->BindingHandle,
                        pNetBufferList,
                        NDIS_DEFAULT_PORT_NUMBER,
                        SendFlags);

    }
    while (FALSE);

    if (NtStatus != STATUS_PENDING)
    {
        WdfRequestComplete(Request, NtStatus);
    }

    return;
}
예제 #28
0
static
NTSTATUS
MsvpChangePassword(IN PLSA_CLIENT_REQUEST ClientRequest,
                   IN PVOID ProtocolSubmitBuffer,
                   IN PVOID ClientBufferBase,
                   IN ULONG SubmitBufferLength,
                   OUT PVOID *ProtocolReturnBuffer,
                   OUT PULONG ReturnBufferLength,
                   OUT PNTSTATUS ProtocolStatus)
{
    PMSV1_0_CHANGEPASSWORD_REQUEST RequestBuffer;
    ULONG_PTR PtrOffset;

    SAMPR_HANDLE ServerHandle = NULL;
    SAMPR_HANDLE DomainHandle = NULL;
    SAMPR_HANDLE UserHandle = NULL;
    PRPC_SID DomainSid = NULL;
    RPC_UNICODE_STRING Names[1];
    SAMPR_ULONG_ARRAY RelativeIds = {0, NULL};
    SAMPR_ULONG_ARRAY Use = {0, NULL};
    NTSTATUS Status;

    ENCRYPTED_NT_OWF_PASSWORD OldNtPassword;
    ENCRYPTED_NT_OWF_PASSWORD NewNtPassword;
    ENCRYPTED_LM_OWF_PASSWORD OldLmPassword;
    ENCRYPTED_LM_OWF_PASSWORD NewLmPassword;
    OEM_STRING LmPwdString;
    CHAR LmPwdBuffer[15];
    BOOLEAN OldLmPasswordPresent = FALSE;
    BOOLEAN NewLmPasswordPresent = FALSE;

    ENCRYPTED_LM_OWF_PASSWORD OldLmEncryptedWithNewLm;
    ENCRYPTED_LM_OWF_PASSWORD NewLmEncryptedWithOldLm;
    ENCRYPTED_LM_OWF_PASSWORD OldNtEncryptedWithNewNt;
    ENCRYPTED_LM_OWF_PASSWORD NewNtEncryptedWithOldNt;
    PENCRYPTED_LM_OWF_PASSWORD pOldLmEncryptedWithNewLm = NULL;
    PENCRYPTED_LM_OWF_PASSWORD pNewLmEncryptedWithOldLm = NULL;

    TRACE("()\n");

    RequestBuffer = (PMSV1_0_CHANGEPASSWORD_REQUEST)ProtocolSubmitBuffer;

    /* Fix-up pointers in the request buffer info */
    PtrOffset = (ULONG_PTR)ProtocolSubmitBuffer - (ULONG_PTR)ClientBufferBase;

    RequestBuffer->DomainName.Buffer = FIXUP_POINTER(RequestBuffer->DomainName.Buffer, PtrOffset);
    RequestBuffer->AccountName.Buffer = FIXUP_POINTER(RequestBuffer->AccountName.Buffer, PtrOffset);
    RequestBuffer->OldPassword.Buffer = FIXUP_POINTER(RequestBuffer->OldPassword.Buffer, PtrOffset);
    RequestBuffer->NewPassword.Buffer = FIXUP_POINTER(RequestBuffer->NewPassword.Buffer, PtrOffset);

    TRACE("Domain: %S\n", RequestBuffer->DomainName.Buffer);
    TRACE("Account: %S\n", RequestBuffer->AccountName.Buffer);
    TRACE("Old Password: %S\n", RequestBuffer->OldPassword.Buffer);
    TRACE("New Password: %S\n", RequestBuffer->NewPassword.Buffer);

    /* Connect to the SAM server */
    Status = SamIConnect(NULL,
                         &ServerHandle,
                         SAM_SERVER_CONNECT | SAM_SERVER_LOOKUP_DOMAIN,
                         TRUE);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamIConnect() failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    /* Get the domain SID */
    Status = SamrLookupDomainInSamServer(ServerHandle,
                                         (PRPC_UNICODE_STRING)&RequestBuffer->DomainName,
                                         &DomainSid);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrLookupDomainInSamServer failed (Status %08lx)\n", Status);
        goto done;
    }

    /* Open the domain */
    Status = SamrOpenDomain(ServerHandle,
                            DOMAIN_LOOKUP,
                            DomainSid,
                            &DomainHandle);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrOpenDomain failed (Status %08lx)\n", Status);
        goto done;
    }

    Names[0].Length = RequestBuffer->AccountName.Length;
    Names[0].MaximumLength = RequestBuffer->AccountName.MaximumLength;
    Names[0].Buffer = RequestBuffer->AccountName.Buffer;

    /* Try to get the RID for the user name */
    Status = SamrLookupNamesInDomain(DomainHandle,
                                     1,
                                     Names,
                                     &RelativeIds,
                                     &Use);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrLookupNamesInDomain failed (Status %08lx)\n", Status);
        Status = STATUS_NO_SUCH_USER;
        goto done;
    }

    /* Fail, if it is not a user account */
    if (Use.Element[0] != SidTypeUser)
    {
        TRACE("Account is not a user account!\n");
        Status = STATUS_NO_SUCH_USER;
        goto done;
    }

    /* Open the user object */
    Status = SamrOpenUser(DomainHandle,
                          USER_CHANGE_PASSWORD,
                          RelativeIds.Element[0],
                          &UserHandle);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrOpenUser failed (Status %08lx)\n", Status);
        goto done;
    }


    /* Calculate the NT hash for the old password */
    Status = SystemFunction007(&RequestBuffer->OldPassword,
                               (LPBYTE)&OldNtPassword);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SystemFunction007 failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    /* Calculate the NT hash for the new password */
    Status = SystemFunction007(&RequestBuffer->NewPassword,
                               (LPBYTE)&NewNtPassword);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SystemFunction007 failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    /* Calculate the LM password and hash for the old password */
    LmPwdString.Length = 15;
    LmPwdString.MaximumLength = 15;
    LmPwdString.Buffer = LmPwdBuffer;
    ZeroMemory(LmPwdString.Buffer, LmPwdString.MaximumLength);

    Status = RtlUpcaseUnicodeStringToOemString(&LmPwdString,
                                               &RequestBuffer->OldPassword,
                                               FALSE);
    if (NT_SUCCESS(Status))
    {
        /* Calculate the LM hash value of the password */
        Status = SystemFunction006(LmPwdString.Buffer,
                                   (LPSTR)&OldLmPassword);
        if (NT_SUCCESS(Status))
        {
            OldLmPasswordPresent = TRUE;
        }
    }

    /* Calculate the LM password and hash for the new password */
    LmPwdString.Length = 15;
    LmPwdString.MaximumLength = 15;
    LmPwdString.Buffer = LmPwdBuffer;
    ZeroMemory(LmPwdString.Buffer, LmPwdString.MaximumLength);

    Status = RtlUpcaseUnicodeStringToOemString(&LmPwdString,
                                               &RequestBuffer->NewPassword,
                                               FALSE);
    if (NT_SUCCESS(Status))
    {
        /* Calculate the LM hash value of the password */
        Status = SystemFunction006(LmPwdString.Buffer,
                                   (LPSTR)&NewLmPassword);
        if (NT_SUCCESS(Status))
        {
            NewLmPasswordPresent = TRUE;
        }
    }

    /* Encrypt the old and new LM passwords, if they exist */
    if (OldLmPasswordPresent && NewLmPasswordPresent)
    {
        /* Encrypt the old LM password */
        Status = SystemFunction012((const BYTE *)&OldLmPassword,
                                   (const BYTE *)&NewLmPassword,
                                   (LPBYTE)&OldLmEncryptedWithNewLm);
        if (!NT_SUCCESS(Status))
        {
            TRACE("SystemFunction012 failed (Status 0x%08lx)\n", Status);
            goto done;
        }

        /* Encrypt the new LM password */
        Status = SystemFunction012((const BYTE *)&NewLmPassword,
                                   (const BYTE *)&OldLmPassword,
                                   (LPBYTE)&NewLmEncryptedWithOldLm);
        if (!NT_SUCCESS(Status))
        {
            TRACE("SystemFunction012 failed (Status 0x%08lx)\n", Status);
            goto done;
        }

        pOldLmEncryptedWithNewLm = &OldLmEncryptedWithNewLm;
        pNewLmEncryptedWithOldLm = &NewLmEncryptedWithOldLm;
    }

    /* Encrypt the old NT password */
    Status = SystemFunction012((const BYTE *)&OldNtPassword,
                               (const BYTE *)&NewNtPassword,
                               (LPBYTE)&OldNtEncryptedWithNewNt);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SystemFunction012 failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    /* Encrypt the new NT password */
    Status = SystemFunction012((const BYTE *)&NewNtPassword,
                               (const BYTE *)&OldNtPassword,
                               (LPBYTE)&NewNtEncryptedWithOldNt);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SystemFunction012 failed (Status 0x%08lx)\n", Status);
        goto done;
    }

    /* Change the password */
    Status = SamrChangePasswordUser(UserHandle,
                                    OldLmPasswordPresent && NewLmPasswordPresent,
                                    pOldLmEncryptedWithNewLm,
                                    pNewLmEncryptedWithOldLm,
                                    TRUE,
                                    &OldNtEncryptedWithNewNt,
                                    &NewNtEncryptedWithOldNt,
                                    FALSE,
                                    NULL,
                                    FALSE,
                                    NULL);
    if (!NT_SUCCESS(Status))
    {
        TRACE("SamrChangePasswordUser failed (Status %08lx)\n", Status);
        goto done;
    }

done:
    if (UserHandle != NULL)
        SamrCloseHandle(&UserHandle);

    SamIFree_SAMPR_ULONG_ARRAY(&RelativeIds);
    SamIFree_SAMPR_ULONG_ARRAY(&Use);

    if (DomainHandle != NULL)
        SamrCloseHandle(&DomainHandle);

    if (DomainSid != NULL)
        SamIFreeVoid(DomainSid);

    if (ServerHandle != NULL)
        SamrCloseHandle(&ServerHandle);

    return Status;
}
예제 #29
0
NTSTATUS
NdisprotIoControl(
    IN PDEVICE_OBJECT   pDeviceObject,
    IN PIRP             pIrp
    )
/*++

Routine Description:

    This is the dispatch routine for handling device ioctl requests.

Arguments:

    pDeviceObject - Pointer to the device object.

    pIrp - Pointer to the request packet.

Return Value:

    Status is returned.

--*/
{
    PIO_STACK_LOCATION      pIrpSp;
    ULONG                   FunctionCode;
    NTSTATUS                NtStatus;
    NDIS_STATUS             Status;
    PNDISPROT_OPEN_CONTEXT  pOpenContext;
    ULONG                   BytesReturned;
#if !DBG
    UNREFERENCED_PARAMETER(pDeviceObject);
#endif
    PAGED_CODE();
    DEBUGP(DL_LOUD, ("IoControl: DevObj %p, Irp %p\n", pDeviceObject, pIrp));

    pIrpSp = IoGetCurrentIrpStackLocation(pIrp);

    FunctionCode = pIrpSp->Parameters.DeviceIoControl.IoControlCode;
    pOpenContext = (PNDISPROT_OPEN_CONTEXT)pIrpSp->FileObject->FsContext;
    BytesReturned = 0;

    switch (FunctionCode)
    {
        case IOCTL_NDISPROT_BIND_WAIT:
            //
            //  Block until we have seen a NetEventBindsComplete event,
            //  meaning that we have finished binding to all running
            //  adapters that we are supposed to bind to.
            //
            //  If we don't get this event in 5 seconds, time out.
            //
            NPROT_ASSERT((FunctionCode & 0x3) == METHOD_BUFFERED);
            
            if (NPROT_WAIT_EVENT(&Globals.BindsComplete, 5000))
            {
                NtStatus = STATUS_SUCCESS;
            }
            else
            {
                NtStatus = STATUS_TIMEOUT;
            }
            DEBUGP(DL_INFO, ("IoControl: BindWait returning %x\n", NtStatus));
            break;

        case IOCTL_NDISPROT_QUERY_BINDING:
            
            NPROT_ASSERT((FunctionCode & 0x3) == METHOD_BUFFERED);
            
            Status = ndisprotQueryBinding(
                            pIrp->AssociatedIrp.SystemBuffer,
                            pIrpSp->Parameters.DeviceIoControl.InputBufferLength,
                            pIrpSp->Parameters.DeviceIoControl.OutputBufferLength,
                            &BytesReturned
                            );

            NDIS_STATUS_TO_NT_STATUS(Status, &NtStatus);

            DEBUGP(DL_LOUD, ("IoControl: QueryBinding returning %x\n", NtStatus));

            break;

        case IOCTL_NDISPROT_OPEN_DEVICE:

            NPROT_ASSERT((FunctionCode & 0x3) == METHOD_BUFFERED);
            if (pOpenContext != NULL)
            {
                NPROT_STRUCT_ASSERT(pOpenContext, oc);
                DEBUGP(DL_WARN, ("IoControl: OPEN_DEVICE: FileObj %p already"
                    " associated with open %p\n", pIrpSp->FileObject, pOpenContext));

                NtStatus = STATUS_DEVICE_BUSY;
                break;
            }

            NtStatus = ndisprotOpenDevice(
                            pIrp->AssociatedIrp.SystemBuffer,
                            pIrpSp->Parameters.DeviceIoControl.InputBufferLength,
                            pIrpSp->FileObject,
                            &pOpenContext
                            );

            if (NT_SUCCESS(NtStatus))
            {

                DEBUGP(DL_VERY_LOUD, ("IoControl OPEN_DEVICE: Open %p <-> FileObject %p\n",
                        pOpenContext, pIrpSp->FileObject));

            }
            else
            {
                DEBUGP(DL_INFO, ("NdisprotIoControl: IOCTL_NDISPROT_OPEN_DEVICE, ndisprotOpenDevice failed %lx\n", NtStatus));
            }

            break;

        case IOCTL_NDISPROT_QUERY_OID_VALUE:

            NPROT_ASSERT((FunctionCode & 0x3) == METHOD_BUFFERED);
            if (pOpenContext != NULL)
            {
                Status = ndisprotQueryOidValue(
                            pOpenContext,
                            pIrp->AssociatedIrp.SystemBuffer,
                            pIrpSp->Parameters.DeviceIoControl.OutputBufferLength,
                            &BytesReturned
                            );

                NDIS_STATUS_TO_NT_STATUS(Status, &NtStatus);
            }
            else
            {
                NtStatus = STATUS_DEVICE_NOT_CONNECTED;
            }
            break;

        case IOCTL_NDISPROT_SET_OID_VALUE:

            NPROT_ASSERT((FunctionCode & 0x3) == METHOD_BUFFERED);
            if (pOpenContext != NULL)
            {
                Status = ndisprotSetOidValue(
                            pOpenContext,
                            pIrp->AssociatedIrp.SystemBuffer,
                            pIrpSp->Parameters.DeviceIoControl.InputBufferLength
                            );

                BytesReturned = 0;

                NDIS_STATUS_TO_NT_STATUS(Status, &NtStatus);
            }
            else
            {
                NtStatus = STATUS_DEVICE_NOT_CONNECTED;
            }
            break;
                        
        default:

            NtStatus = STATUS_NOT_SUPPORTED;
            break;
    }

    if (NtStatus != STATUS_PENDING)
    {
        pIrp->IoStatus.Information = BytesReturned;
        pIrp->IoStatus.Status = NtStatus;
        IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    }

    return NtStatus;
}
예제 #30
0
NTSTATUS
DriverEntry(
   DRIVER_OBJECT* driverObject,
   UNICODE_STRING* registryPath
   )
{
   NTSTATUS status;
   WDFDEVICE device;
   WDFDRIVER driver;
   WDFKEY configKey;
   NET_BUFFER_LIST_POOL_PARAMETERS nblPoolParams = {0};

   // Request NX Non-Paged Pool when available
   ExInitializeDriverRuntime(DrvRtPoolNxOptIn);

   status = StreamEditInitDriverObjects(
               driverObject,
               registryPath,
               &driver,
               &device
               );

   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }

   status = WdfDriverOpenParametersRegistryKey(
               driver,
               KEY_READ,
               WDF_NO_OBJECT_ATTRIBUTES,
               &configKey
               );

   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }

   status = StreamEditLoadConfig(configKey);

   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }

   gStringToReplaceMdl = IoAllocateMdl(
                           configStringToReplace,
                           (ULONG) strlen(configStringToReplace),
                           FALSE,
                           FALSE,
                           NULL
                           );
   if (gStringToReplaceMdl == NULL)
   {
      status = STATUS_NO_MEMORY;
      goto Exit;
   }

   MmBuildMdlForNonPagedPool(gStringToReplaceMdl);

   gNdisGenericObj = NdisAllocateGenericObject(
                        driverObject, 
                        STREAM_EDITOR_NDIS_OBJ_TAG, 
                        0
                        );

   if (gNdisGenericObj == NULL)
   {
      status = STATUS_NO_MEMORY;
      goto Exit;
   }

   nblPoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
   nblPoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
   nblPoolParams.Header.Size = sizeof(nblPoolParams);

   nblPoolParams.fAllocateNetBuffer = TRUE;
   nblPoolParams.DataSize = 0;

   nblPoolParams.PoolTag = STREAM_EDITOR_NBL_POOL_TAG;

   gNetBufferListPool = NdisAllocateNetBufferListPool(
                           gNdisGenericObj,
                           &nblPoolParams
                           );

   if (gNetBufferListPool == NULL)
   {
      status = STATUS_NO_MEMORY;
      goto Exit;
   }

   status = FwpsInjectionHandleCreate(
               AF_UNSPEC,
               FWPS_INJECTION_TYPE_STREAM,
               &gInjectionHandle
               );

   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }

   gWdmDevice = WdfDeviceWdmGetDeviceObject(device);

   status = StreamEditRegisterCallout(
               &gStreamEditor,
               gWdmDevice
               );

   if (!NT_SUCCESS(status))
   {
      goto Exit;
   }

   if (configEditInline)
   {
      InlineEditInit(&gStreamEditor);
   }
   else
   {

      status = OobEditInit(&gStreamEditor);

      if (!NT_SUCCESS(status))
      {
         goto Exit;
      }
   }

Exit:
   
   if (!NT_SUCCESS(status))
   {
      if (gEngineHandle != NULL)
      {
         StreamEditUnregisterCallout();
      }
      if (gInjectionHandle != NULL)
      {
         FwpsInjectionHandleDestroy(gInjectionHandle);
      }
      if (gNetBufferListPool != NULL)
      {
         NdisFreeNetBufferListPool(gNetBufferListPool);
      }
      if (gNdisGenericObj != NULL)
      {
         NdisFreeGenericObject(gNdisGenericObj);
      }
      if (gStringToReplaceMdl != NULL)
      {
         IoFreeMdl(gStringToReplaceMdl);
      }
   }

   return status;
}