详述OpenProcess获取句柄的流程

前面我在《重要》从用户模式切换到内核模式的完整过程分析这篇文章中,已经把OpenProcess怎么从R3进入R0已经说的很详细了。

R3状态下调用OpenProcess,实际调用的是ntdll.dll中的ZwOpenProcess/NtOpenProcess。通过查看可以得知ntdll.dll中ZwOpenProcess/NtOpenProcess是对应同一个地址。通过sysenter进入R0.在ssdt中,通过函数的序号调用真正的内核API NtOpenProcess。

我们反汇编NtOpenProcess这个函数。

image

发现NtOpenProcess调用的是PsOpenProcess。然后我们继续跟进PsOpenProcess。

image

首先通过SeCreateAccessState使用accessmask创建访问状态,然后使用SeSinglePrivilegeCheck检查当前线程权限。

所以我们会发现在使用此函数时会发现不能成功获得有些系统进程的句柄,原因是没有权限。解决办法是在调用此函数前让我们的进程得到SeDebugPrivilege权限。

image

如果是线程ID则调用PsLookupProcessThreadByCid按照给定的CID从PspCidTable查找相应的线程对象。

image

否则使用PsLookupProcessByProcessId 通过ID获得对应的PEPROCESS。

内部通过ExMapHandleToPointer将ID转换成为HANDLE_TABLE_ENTRY的指针(底层调用ExpLookupHandleTableEntry),通过指针的Object对象判断是否为PEPROCESS,如果是则解除引用,将PEPROCESS对象赋值给PsLookupProcessByProcessId的指向进程对象的指针,之后ExUnlockHandleTableEntry解锁PspcidTable并返回。

image

ObOpenObjectByPointer 通过返回的peprocess指针获取进程对象句柄。

delete掉accessmask所创建的访问状态。

ObDereferenceObject解除引用。

返回进程句柄。

我们来看看NtOpenProcess的源码,是不是和我们分析的一样!!!(WRK-v1.2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
NTSTATUS
NtOpenProcess (
    __out PHANDLE ProcessHandle,
    __in ACCESS_MASK DesiredAccess,
    __in POBJECT_ATTRIBUTES ObjectAttributes,
    __in_opt PCLIENT_ID ClientId
    )

/*++

Routine Description:

    This function opens a handle to a process object with the specified
    desired access.

    The object is located either by name, or by locating a thread whose
    Client ID matches the specified Client ID and then opening that thread's
    process.

Arguments:

    ProcessHandle - Supplies a pointer to a variable that will receive
        the process object handle.

    DesiredAccess - Supplies the desired types of access for the process
        object.

    ObjectAttributes - Supplies a pointer to an object attributes structure.
        If the ObjectName field is specified, then ClientId must not be
        specified.

    ClientId - Supplies a pointer to a ClientId that if supplied
        specifies the thread whose process is to be opened. If this
        argument is specified, then ObjectName field of the ObjectAttributes
        structure must not be specified.

Return Value:

    NTSTATUS - Status of call

--*/


{

    HANDLE Handle;
    KPROCESSOR_MODE PreviousMode;
    NTSTATUS Status;
    PEPROCESS Process;
    PETHREAD Thread;
    CLIENT_ID CapturedCid={0};
    BOOLEAN ObjectNamePresent;
    BOOLEAN ClientIdPresent;
    ACCESS_STATE AccessState;
    AUX_ACCESS_DATA AuxData;
    ULONG Attributes;

    PAGED_CODE();

    //
    // Make sure that only one of either ClientId or ObjectName is
    // present.
    //

    PreviousMode = KeGetPreviousMode();
    if (PreviousMode != KernelMode) {

        //
        // Since we need to look at the ObjectName field, probe
        // ObjectAttributes and capture object name present indicator.
        //

        try {

            ProbeForWriteHandle (ProcessHandle);

            ProbeForReadSmallStructure (ObjectAttributes,
                                        sizeof(OBJECT_ATTRIBUTES),
                                        sizeof(ULONG));
            ObjectNamePresent = (BOOLEAN)ARGUMENT_PRESENT (ObjectAttributes->ObjectName);
            Attributes = ObSanitizeHandleAttributes (ObjectAttributes->Attributes, UserMode);

            if (ARGUMENT_PRESENT (ClientId)) {
                ProbeForReadSmallStructure (ClientId, sizeof (CLIENT_ID), sizeof (ULONG));
                CapturedCid = *ClientId;
                ClientIdPresent = TRUE;
            } else {
                ClientIdPresent = FALSE;
            }
        } except (EXCEPTION_EXECUTE_HANDLER) {
            return GetExceptionCode();
        }
    } else {
        ObjectNamePresent = (BOOLEAN)ARGUMENT_PRESENT (ObjectAttributes->ObjectName);
        Attributes = ObSanitizeHandleAttributes (ObjectAttributes->Attributes, KernelMode);
        if (ARGUMENT_PRESENT (ClientId)) {
            CapturedCid = *ClientId;
            ClientIdPresent = TRUE;
        } else {
            ClientIdPresent = FALSE;
        }
    }

    if (ObjectNamePresent && ClientIdPresent) {
        return STATUS_INVALID_PARAMETER_MIX;
    }

    //
    // Create an AccessState here, because the caller may have
    // DebugPrivilege, which requires us to make special adjustments
    // to his desired access mask.  We do this by modifying the
    // internal fields in the AccessState to achieve the effect
    // we desire.
    //

    Status = SeCreateAccessState(
                 &AccessState,
                 &AuxData,
                 DesiredAccess,
                 &PsProcessType->TypeInfo.GenericMapping
                 );

    if ( !NT_SUCCESS(Status) ) {

        return Status;
    }

    //
    // Check here to see if the caller has SeDebugPrivilege.  If
    // he does, we will allow him any access he wants to the process.
    // We do this by clearing the DesiredAccess in the AccessState
    // and recording what we want him to have in the PreviouslyGrantedAccess
    // field.
    //
    // Note that this routine performs auditing as appropriate.
    //

    if (SeSinglePrivilegeCheck( SeDebugPrivilege, PreviousMode )) {

        if ( AccessState.RemainingDesiredAccess & MAXIMUM_ALLOWED ) {
            AccessState.PreviouslyGrantedAccess |= PROCESS_ALL_ACCESS;

        } else {

            AccessState.PreviouslyGrantedAccess |= ( AccessState.RemainingDesiredAccess );
        }

        AccessState.RemainingDesiredAccess = 0;

    }

    if (ObjectNamePresent) {

        //
        // Open handle to the process object with the specified desired access,
        // set process handle value, and return service completion status.
        //

        Status = ObOpenObjectByName(
                    ObjectAttributes,
                    PsProcessType,
                    PreviousMode,
                    &AccessState,
                    0,
                    NULL,
                    &Handle
                    );

        SeDeleteAccessState( &AccessState );

        if ( NT_SUCCESS(Status) ) {
            try {
                *ProcessHandle = Handle;
            } except (EXCEPTION_EXECUTE_HANDLER) {
                return GetExceptionCode ();
            }
        }

        return Status;
    }

    if ( ClientIdPresent ) {

        Thread = NULL;
        if (CapturedCid.UniqueThread) {
            Status = PsLookupProcessThreadByCid(
                        &CapturedCid,
                        &Process,
                        &Thread
                        );

            if (!NT_SUCCESS(Status)) {
                SeDeleteAccessState( &AccessState );
                return Status;
            }
        } else {
            Status = PsLookupProcessByProcessId(
                        CapturedCid.UniqueProcess,
                        &Process
                        );

            if ( !NT_SUCCESS(Status) ) {
                SeDeleteAccessState( &AccessState );
                return Status;
            }
        }

        //
        // OpenObjectByAddress
        //

        Status = ObOpenObjectByPointer(
                    Process,
                    Attributes,
                    &AccessState,
                    0,
                    PsProcessType,
                    PreviousMode,
                    &Handle
                    );

        SeDeleteAccessState( &AccessState );

        if (Thread) {
            ObDereferenceObject(Thread);
        }

        ObDereferenceObject(Process);

        if (NT_SUCCESS (Status)) {

            try {
                *ProcessHandle = Handle;
            } except (EXCEPTION_EXECUTE_HANDLER) {
                return GetExceptionCode ();
            }
        }

        return Status;

    }

    return STATUS_INVALID_PARAMETER_MIX;
}

基本上和我们上面反汇编的结果是一样的,,,我发现IDA还是很流弊的,哈哈。。。

本文链接:http://www.alonemonkey.com/openprocess-flow-path.html