Johnaudi
Johnaudi

Reputation: 257

Access Violation Error after DeviceIoControl

I am trying to send INOUT_PARAM to my kernel driver, and it seems that I had succeeded. As I am trying to edit it and send it back to the application I am getting the following error: error

Here is the Application code:

typedef struct _INOUT_PARAM {
    ULONG PID;
    ULONG Addr;
    PCHAR Str;
    ULONG RAddr;
    PCHAR RStr;
} INOUT_PARAM, *PINOUTPARAM;

INOUT_PARAM TellDriver(DWORD IOCTL, INOUT_PARAM rtmp)
{
    INOUT_PARAM tmp = rtmp;
    HANDLE          h;
    DWORD           bytesIO;

    h = CreateFile(TEXT("\\\\.\\KJPA"), GENERIC_READ | GENERIC_WRITE,
        0, NULL, OPEN_EXISTING, 0, NULL);
    if (h != INVALID_HANDLE_VALUE) {

        DeviceIoControl(h, IOCTL,
            &tmp, sizeof(tmp), &tmp,
            sizeof(tmp), &bytesIO, NULL);
        CloseHandle(h);
    }
    return tmp;
}

int __cdecl main(int argc, char* argv[])
{
    echo("Input some text for IOCTL_Entry");
    gecho();

    INOUT_PARAM parms;
    initParms(&parms);

    INOUT_PARAM n = TellDriver(IOCTL_ENTRY, parms);
    echo(n.RStr);

    gecho();
    return 0;
}

And here is the driver IOCTL function:

NTSTATUS Function_IRP_DEVICE_CONTROL(PDEVICE_OBJECT pDeviceObject, PIRP Irp)
{
    NTSTATUS                status = STATUS_SUCCESS;
    ULONG                   bytesIO = 0;
    PIO_STACK_LOCATION      stack;
    BOOLEAN                 condition = FALSE;

    PINOUTPARAM             wp;

    UNREFERENCED_PARAMETER(pDeviceObject);

    stack = IoGetCurrentIrpStackLocation(Irp);

    if (stack == NULL) {
        status = STATUS_INTERNAL_ERROR;
    }

    wp = (PINOUTPARAM)Irp->AssociatedIrp.SystemBuffer;

    wp->RStr = "Test";

    Irp->IoStatus.Status = status;
    Irp->IoStatus.Information = sizeof(INOUT_PARAM);

    IoCompleteRequest(Irp, IO_NO_INCREMENT);

    return status;
}

I cannot seem to find where the issue resides, any help would be appreciated.

Thank you in advance.

Note: When I send the INOUT_PARAM without the wp->RStr = "Test"; it successfully echoes the initial value, meaning that editing or reading the edited memory by the driver is not working properly.

Note 2: Error shows up only when I echo/cout the n.RStr PCHAR value.

IMPORTANT NOTE: If I have wp->PID = 6969; in the driver and then echo(n.PID); it actually works... I have no idea why PCHAR is causing issues, but this is most likely it. Any ideas how to fix that?

Upvotes: 0

Views: 303

Answers (1)

Johnaudi
Johnaudi

Reputation: 257

I found a solution to make it work. I've used the following:

typedef struct _INOUT_PARAM {
    ULONG PID;
    ULONG Addr;
    CHAR Str[1024];
    ULONG RAddr;
    CHAR RStr[1024];
} INOUT_PARAM, *PINOUTPARAM;

By changing PCHAR to Char[] actually did the job - I've used strcpy() on my strings. But I do not understand why, any explanation please? I will not mark this as the answer as if the explanation is more important than the answer for me.

Upvotes: 1

Related Questions