2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/ob/obhandle.c
5 * PURPOSE: Manages all functions related to the Object Manager handle
6 * implementation, including creating and destroying handles
7 * and/or handle tables, duplicating objects, and setting the
8 * permanent or temporary flags.
9 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
11 * Thomas Weidenmueller (w3seek@reactos.org)
14 /* INCLUDES ******************************************************************/
20 PHANDLE_TABLE ObpKernelHandleTable
= NULL
;
21 ULONG ObpAccessProtectCloseBit
= MAXIMUM_ALLOWED
;
23 #define TAG_OB_HANDLE 'dHbO'
25 /* PRIVATE FUNCTIONS *********************************************************/
29 ObReferenceProcessHandleTable(IN PEPROCESS Process
)
31 PHANDLE_TABLE HandleTable
= NULL
;
33 /* Lock the process */
34 if (ExAcquireRundownProtection(&Process
->RundownProtect
))
36 /* Get the handle table */
37 HandleTable
= Process
->ObjectTable
;
40 /* No table, release the lock */
41 ExReleaseRundownProtection(&Process
->RundownProtect
);
45 /* Return the handle table */
51 ObDereferenceProcessHandleTable(IN PEPROCESS Process
)
53 /* Release the process lock */
54 ExReleaseRundownProtection(&Process
->RundownProtect
);
59 ObGetProcessHandleCount(IN PEPROCESS Process
)
62 PHANDLE_TABLE HandleTable
;
66 /* Ensure the handle table doesn't go away while we use it */
67 HandleTable
= ObReferenceProcessHandleTable(Process
);
69 if (HandleTable
!= NULL
)
71 /* Count the number of handles the process has */
72 HandleCount
= HandleTable
->HandleCount
;
74 /* Let the handle table go */
75 ObDereferenceProcessHandleTable(Process
);
79 /* No handle table, no handles */
88 ObpReferenceProcessObjectByHandle(IN HANDLE Handle
,
90 IN PHANDLE_TABLE HandleTable
,
91 IN KPROCESSOR_MODE AccessMode
,
93 OUT POBJECT_HANDLE_INFORMATION HandleInformation
,
94 OUT PACCESS_MASK AuditMask
)
96 PHANDLE_TABLE_ENTRY HandleEntry
;
97 POBJECT_HEADER ObjectHeader
;
98 ACCESS_MASK GrantedAccess
;
100 PETHREAD Thread
= PsGetCurrentThread();
106 /* Check if this is a special handle */
107 if (HandleToLong(Handle
) < 0)
109 /* Check if the caller wants the current process */
110 if (Handle
== NtCurrentProcess())
112 /* Return handle info */
113 HandleInformation
->HandleAttributes
= 0;
114 HandleInformation
->GrantedAccess
= Process
->GrantedAccess
;
119 /* Reference ourselves */
120 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Process
);
121 InterlockedIncrement(&ObjectHeader
->PointerCount
);
123 /* Return the pointer */
125 ASSERT(*Object
!= NULL
);
126 return STATUS_SUCCESS
;
129 /* Check if the caller wants the current thread */
130 if (Handle
== NtCurrentThread())
132 /* Return handle information */
133 HandleInformation
->HandleAttributes
= 0;
134 HandleInformation
->GrantedAccess
= Thread
->GrantedAccess
;
136 /* Reference ourselves */
137 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Thread
);
138 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
, 1);
143 /* Return the pointer */
145 ASSERT(*Object
!= NULL
);
146 return STATUS_SUCCESS
;
149 /* This is a kernel handle... do we have access? */
150 if (AccessMode
== KernelMode
)
152 /* Use the kernel handle table and get the actual handle value */
153 Handle
= ObKernelHandleToHandle(Handle
);
154 HandleTable
= ObpKernelHandleTable
;
158 /* This is an illegal attempt to access a kernel handle */
159 return STATUS_INVALID_HANDLE
;
163 /* Enter a critical region while we touch the handle table */
164 ASSERT(HandleTable
!= NULL
);
165 KeEnterCriticalRegion();
167 /* Get the handle entry */
168 HandleEntry
= ExMapHandleToPointer(HandleTable
, Handle
);
171 /* Get the object header and validate the type*/
172 ObjectHeader
= ObpGetHandleObject(HandleEntry
);
174 /* Get the granted access and validate it */
175 GrantedAccess
= HandleEntry
->GrantedAccess
;
177 /* Mask out the internal attributes */
178 Attributes
= HandleEntry
->ObAttributes
& OBJ_HANDLE_ATTRIBUTES
;
180 /* Fill out the information */
181 HandleInformation
->HandleAttributes
= Attributes
;
182 HandleInformation
->GrantedAccess
= GrantedAccess
;
184 /* No audit mask (FIXME!) */
187 /* Return the pointer */
188 *Object
= &ObjectHeader
->Body
;
190 /* Add a reference */
191 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
, 1);
193 /* Unlock the handle */
194 ExUnlockHandleTableEntry(HandleTable
, HandleEntry
);
195 KeLeaveCriticalRegion();
198 ASSERT(*Object
!= NULL
);
199 return STATUS_SUCCESS
;
204 Status
= STATUS_INVALID_HANDLE
;
207 /* Return failure status */
208 KeLeaveCriticalRegion();
214 ObpEnumFindHandleProcedure(IN PHANDLE_TABLE_ENTRY HandleEntry
,
218 POBJECT_HEADER ObjectHeader
;
219 ACCESS_MASK GrantedAccess
;
220 ULONG HandleAttributes
;
221 POBP_FIND_HANDLE_DATA FindData
= Context
;
223 /* Get the object header */
224 ObjectHeader
= ObpGetHandleObject(HandleEntry
);
226 /* Make sure it's valid and matching */
227 if ((FindData
->ObjectHeader
) && (FindData
->ObjectHeader
!= ObjectHeader
))
233 /* Now attempt to match the object type */
234 if ((FindData
->ObjectType
) && (FindData
->ObjectType
!= ObjectHeader
->Type
))
240 /* Check if we have extra information */
241 if (FindData
->HandleInformation
)
243 /* Get the granted access and attributes */
244 GrantedAccess
= HandleEntry
->GrantedAccess
;
245 HandleAttributes
= HandleEntry
->ObAttributes
& OBJ_HANDLE_ATTRIBUTES
;
247 /* Attempt to match them */
248 if ((FindData
->HandleInformation
->HandleAttributes
!= HandleAttributes
) ||
249 (FindData
->HandleInformation
->GrantedAccess
!= GrantedAccess
))
256 /* We have a match */
260 POBJECT_HANDLE_COUNT_ENTRY
262 ObpInsertHandleCount(IN POBJECT_HEADER ObjectHeader
)
264 POBJECT_HEADER_HANDLE_INFO HandleInfo
;
265 POBJECT_HANDLE_COUNT_ENTRY FreeEntry
;
266 POBJECT_HANDLE_COUNT_DATABASE HandleDatabase
, OldHandleDatabase
;
269 OBJECT_HANDLE_COUNT_DATABASE SingleDatabase
;
272 /* Get the handle info */
273 HandleInfo
= OBJECT_HEADER_TO_HANDLE_INFO(ObjectHeader
);
274 if (!HandleInfo
) return NULL
;
276 /* Check if we only have one entry */
277 if (ObjectHeader
->Flags
& OB_FLAG_SINGLE_PROCESS
)
279 /* Fill out the single entry */
280 SingleDatabase
.CountEntries
= 1;
281 SingleDatabase
.HandleCountEntries
[0] = HandleInfo
->SingleEntry
;
283 /* Use this as the old size */
284 OldHandleDatabase
= &SingleDatabase
;
285 OldSize
= sizeof(SingleDatabase
);
287 /* Now we'll have two entries, and an entire DB */
289 Size
= sizeof(OBJECT_HANDLE_COUNT_DATABASE
) +
290 ((i
- 1) * sizeof(OBJECT_HANDLE_COUNT_ENTRY
));
294 /* We already have a DB, get the information from it */
295 OldHandleDatabase
= HandleInfo
->HandleCountDatabase
;
296 i
= OldHandleDatabase
->CountEntries
;
297 OldSize
= sizeof(OBJECT_HANDLE_COUNT_DATABASE
) +
298 ((i
- 1) * sizeof(OBJECT_HANDLE_COUNT_ENTRY
));
300 /* Add 4 more entries */
302 Size
= OldSize
+ (4 * sizeof(OBJECT_HANDLE_COUNT_ENTRY
));
305 /* Allocate the DB */
306 HandleDatabase
= ExAllocatePoolWithTag(PagedPool
, Size
, TAG_OB_HANDLE
);
307 if (!HandleDatabase
) return NULL
;
309 /* Copy the old database */
310 RtlCopyMemory(HandleDatabase
, OldHandleDatabase
, OldSize
);
312 /* Check if we he had a single entry before */
313 if (ObjectHeader
->Flags
& OB_FLAG_SINGLE_PROCESS
)
315 /* Now we have more */
316 ObjectHeader
->Flags
&= ~OB_FLAG_SINGLE_PROCESS
;
320 /* Otherwise we had a DB, free it */
321 ExFreePoolWithTag(OldHandleDatabase
, TAG_OB_HANDLE
);
324 /* Find the end of the copy and zero out the new data */
325 FreeEntry
= (PVOID
)((ULONG_PTR
)HandleDatabase
+ OldSize
);
326 RtlZeroMemory(FreeEntry
, Size
- OldSize
);
328 /* Set the new information and return the free entry */
329 HandleDatabase
->CountEntries
= i
;
330 HandleInfo
->HandleCountDatabase
= HandleDatabase
;
336 ObpIncrementHandleDataBase(IN POBJECT_HEADER ObjectHeader
,
337 IN PEPROCESS Process
,
338 IN OUT PULONG NewProcessHandleCount
)
340 POBJECT_HEADER_HANDLE_INFO HandleInfo
;
341 POBJECT_HANDLE_COUNT_ENTRY HandleEntry
, FreeEntry
= NULL
;
342 POBJECT_HANDLE_COUNT_DATABASE HandleDatabase
;
346 /* Get the handle info and check if we only have one entry */
347 HandleInfo
= OBJECT_HEADER_TO_HANDLE_INFO(ObjectHeader
);
348 if (ObjectHeader
->Flags
& OB_FLAG_SINGLE_PROCESS
)
350 /* Check if the entry is free */
351 if (!HandleInfo
->SingleEntry
.HandleCount
)
354 HandleInfo
->SingleEntry
.HandleCount
= 1;
355 HandleInfo
->SingleEntry
.Process
= Process
;
357 /* Return success and 1 handle */
358 *NewProcessHandleCount
= 1;
359 return STATUS_SUCCESS
;
361 else if (HandleInfo
->SingleEntry
.Process
== Process
)
363 /* Busy entry, but same process */
364 *NewProcessHandleCount
= ++HandleInfo
->SingleEntry
.HandleCount
;
365 return STATUS_SUCCESS
;
369 /* Insert a new entry */
370 FreeEntry
= ObpInsertHandleCount(ObjectHeader
);
371 if (!FreeEntry
) return STATUS_INSUFFICIENT_RESOURCES
;
372 ASSERT(!FreeEntry
->Process
);
373 ASSERT(!FreeEntry
->HandleCount
);
376 FreeEntry
->Process
= Process
;
377 FreeEntry
->HandleCount
= 1;
379 /* Return success and 1 handle */
380 *NewProcessHandleCount
= 1;
381 return STATUS_SUCCESS
;
385 /* We have a database instead */
386 HandleDatabase
= HandleInfo
->HandleCountDatabase
;
389 /* Get the entries and loop them */
390 i
= HandleDatabase
->CountEntries
;
391 HandleEntry
= &HandleDatabase
->HandleCountEntries
[0];
394 /* Check if this is a match */
395 if (HandleEntry
->Process
== Process
)
397 /* Found it, get the process handle count */
398 *NewProcessHandleCount
= ++HandleEntry
->HandleCount
;
399 return STATUS_SUCCESS
;
401 else if (!HandleEntry
->HandleCount
)
403 /* Found a free entry */
404 FreeEntry
= HandleEntry
;
412 /* Check if we couldn't find a free entry */
416 FreeEntry
= ObpInsertHandleCount(ObjectHeader
);
417 if (!FreeEntry
) return STATUS_INSUFFICIENT_RESOURCES
;
418 ASSERT(!FreeEntry
->Process
);
419 ASSERT(!FreeEntry
->HandleCount
);
422 /* Fill out the entry */
423 FreeEntry
->Process
= Process
;
424 FreeEntry
->HandleCount
= 1;
425 *NewProcessHandleCount
= 1;
428 /* Return success if we got here */
429 return STATUS_SUCCESS
;
434 ObpChargeQuotaForObject(IN POBJECT_HEADER ObjectHeader
,
435 IN POBJECT_TYPE ObjectType
,
436 OUT PBOOLEAN NewObject
)
438 POBJECT_HEADER_QUOTA_INFO ObjectQuota
;
439 ULONG PagedPoolCharge
, NonPagedPoolCharge
;
441 /* Get quota information */
442 ObjectQuota
= OBJECT_HEADER_TO_QUOTA_INFO(ObjectHeader
);
445 /* Check if this is a new object */
446 if (ObjectHeader
->Flags
& OB_FLAG_CREATE_INFO
)
448 /* Remove the flag */
449 ObjectHeader
->Flags
&= ~ OB_FLAG_CREATE_INFO
;
452 /* We have a quota, get the charges */
453 PagedPoolCharge
= ObjectQuota
->PagedPoolCharge
;
454 NonPagedPoolCharge
= ObjectQuota
->NonPagedPoolCharge
;
458 /* Get it from the object type */
459 PagedPoolCharge
= ObjectType
->TypeInfo
.DefaultPagedPoolCharge
;
460 NonPagedPoolCharge
= ObjectType
->TypeInfo
.DefaultNonPagedPoolCharge
;
463 /* Charge the quota */
464 ObjectHeader
->QuotaBlockCharged
= (PVOID
)1;
465 DPRINT("FIXME: Should charge: %lx %lx\n", PagedPoolCharge
, NonPagedPoolCharge
);
467 PsChargeSharedPoolQuota(PsGetCurrentProcess(),
472 /* Check if we don't have a quota block */
473 if (!ObjectHeader
->QuotaBlockCharged
) return STATUS_QUOTA_EXCEEDED
;
475 /* Now set the flag */
480 return STATUS_SUCCESS
;
485 ObpValidateAccessMask(IN PACCESS_STATE AccessState
)
487 PISECURITY_DESCRIPTOR SecurityDescriptor
;
489 /* We're only interested if the object for this access state has an SD */
490 SecurityDescriptor
= AccessState
->SecurityDescriptor
;
491 if (SecurityDescriptor
)
493 /* Check if the SD has a system ACL but hasn't been granted access to get/set it */
494 if ((SecurityDescriptor
->Control
& SE_SACL_PRESENT
) &&
495 !(AccessState
->PreviouslyGrantedAccess
& ACCESS_SYSTEM_SECURITY
))
497 /* We're gonna need access */
498 AccessState
->RemainingDesiredAccess
|= ACCESS_SYSTEM_SECURITY
;
502 /* This can't fail */
503 return STATUS_SUCCESS
;
507 * @name ObpDecrementHandleCount
509 * The ObpDecrementHandleCount routine <FILLMEIN>
517 * @param GrantedAccess
527 ObpDecrementHandleCount(IN PVOID ObjectBody
,
528 IN PEPROCESS Process
,
529 IN ACCESS_MASK GrantedAccess
,
530 IN POBJECT_TYPE ObjectType
)
532 POBJECT_HEADER ObjectHeader
;
533 LONG SystemHandleCount
, ProcessHandleCount
;
536 POBJECT_HEADER_HANDLE_INFO HandleInfo
;
537 POBJECT_HANDLE_COUNT_ENTRY HandleEntry
;
538 POBJECT_HANDLE_COUNT_DATABASE HandleDatabase
;
542 /* Get the object type and header */
543 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(ObjectBody
);
544 OBTRACE(OB_HANDLE_DEBUG
,
545 "%s - Decrementing count for: %p. HC PC %lx %lx\n",
548 ObjectHeader
->HandleCount
,
549 ObjectHeader
->PointerCount
);
551 /* Lock the object */
552 ObpAcquireObjectLock(ObjectHeader
);
554 /* Set default counts */
555 SystemHandleCount
= ObjectHeader
->HandleCount
;
556 ProcessHandleCount
= 0;
558 /* Decrement the handle count */
559 NewCount
= InterlockedDecrement(&ObjectHeader
->HandleCount
);
561 /* Check if we're out of handles and this was an exclusive object */
562 if (!(NewCount
) && (ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
))
564 /* Clear the exclusive flag */
565 OBJECT_HEADER_TO_QUOTA_INFO(ObjectHeader
)->ExclusiveProcess
= NULL
;
568 /* Is the object type keeping track of handles? */
569 if (ObjectType
->TypeInfo
.MaintainHandleCount
)
571 /* Get handle information */
572 HandleInfo
= OBJECT_HEADER_TO_HANDLE_INFO(ObjectHeader
);
574 /* Check if there's only a single entry */
575 if (ObjectHeader
->Flags
& OB_FLAG_SINGLE_PROCESS
)
577 /* It should be us */
578 ASSERT(HandleInfo
->SingleEntry
.Process
== Process
);
579 ASSERT(HandleInfo
->SingleEntry
.HandleCount
> 0);
581 /* Get the handle counts */
582 ProcessHandleCount
= HandleInfo
->SingleEntry
.HandleCount
--;
583 HandleEntry
= &HandleInfo
->SingleEntry
;
587 /* Otherwise, get the database */
588 HandleDatabase
= HandleInfo
->HandleCountDatabase
;
591 /* Get the entries and loop them */
592 i
= HandleDatabase
->CountEntries
;
593 HandleEntry
= &HandleDatabase
->HandleCountEntries
[0];
596 /* Check if this is a match */
597 if ((HandleEntry
->HandleCount
) &&
598 (HandleEntry
->Process
== Process
))
600 /* Found it, get the process handle count */
601 ProcessHandleCount
= HandleEntry
->HandleCount
--;
612 /* No database, so no entry */
617 /* Check if this is the last handle */
618 if (ProcessHandleCount
== 1)
620 /* Then clear the entry */
621 HandleEntry
->Process
= NULL
;
622 HandleEntry
->HandleCount
= 0;
626 /* Release the lock */
627 ObpReleaseObjectLock(ObjectHeader
);
629 /* Check if we have a close procedure */
630 if (ObjectType
->TypeInfo
.CloseProcedure
)
633 ObpCalloutStart(&CalloutIrql
);
634 ObjectType
->TypeInfo
.CloseProcedure(Process
,
639 ObpCalloutEnd(CalloutIrql
, "Close", ObjectType
, ObjectBody
);
642 /* Check if we should delete the object */
643 ObpDeleteNameCheck(ObjectBody
);
645 /* Decrease the total number of handles for this type */
646 InterlockedDecrement((PLONG
)&ObjectType
->TotalNumberOfHandles
);
647 OBTRACE(OB_HANDLE_DEBUG
,
648 "%s - Decremented count for: %p. HC PC %lx %lx\n",
651 ObjectHeader
->HandleCount
,
652 ObjectHeader
->PointerCount
);
656 * @name ObpCloseHandleTableEntry
658 * The ObpCloseHandleTableEntry routine <FILLMEIN>
672 * @param IgnoreHandleProtection
675 * @return <FILLMEIN>.
682 ObpCloseHandleTableEntry(IN PHANDLE_TABLE HandleTable
,
683 IN PHANDLE_TABLE_ENTRY HandleEntry
,
685 IN KPROCESSOR_MODE AccessMode
,
686 IN BOOLEAN IgnoreHandleProtection
)
689 POBJECT_TYPE ObjectType
;
690 POBJECT_HEADER ObjectHeader
;
691 ACCESS_MASK GrantedAccess
;
695 /* Get the object data */
696 ObjectHeader
= ObpGetHandleObject(HandleEntry
);
697 ObjectType
= ObjectHeader
->Type
;
698 Body
= &ObjectHeader
->Body
;
699 GrantedAccess
= HandleEntry
->GrantedAccess
;
700 OBTRACE(OB_HANDLE_DEBUG
,
701 "%s - Closing handle: %p for %p. HC PC %lx %lx\n",
705 ObjectHeader
->HandleCount
,
706 ObjectHeader
->PointerCount
);
708 /* Check if the object has an Okay To Close procedure */
709 if (ObjectType
->TypeInfo
.OkayToCloseProcedure
)
711 /* Call it and check if it's not letting us close it */
712 ObpCalloutStart(&CalloutIrql
);
713 if (!ObjectType
->TypeInfo
.OkayToCloseProcedure(PsGetCurrentProcess(),
719 ObpCalloutEnd(CalloutIrql
, "NtClose", ObjectType
, Body
);
720 ExUnlockHandleTableEntry(HandleTable
, HandleEntry
);
721 return STATUS_HANDLE_NOT_CLOSABLE
;
724 /* Success, validate callout retrn */
725 ObpCalloutEnd(CalloutIrql
, "NtClose", ObjectType
, Body
);
728 /* The callback allowed us to close it, but does the handle itself? */
729 if ((HandleEntry
->ObAttributes
& OBJ_PROTECT_CLOSE
) &&
730 !(IgnoreHandleProtection
))
732 /* It doesn't, are we from user mode? */
733 if (AccessMode
!= KernelMode
)
735 /* We are! Unlock the entry */
736 ExUnlockHandleTableEntry(HandleTable
, HandleEntry
);
738 /* Make sure we have a debug port */
739 if (PsGetCurrentProcess()->DebugPort
)
741 /* Raise an exception */
742 return KeRaiseUserException(STATUS_HANDLE_NOT_CLOSABLE
);
746 /* Return the error instead */
747 return STATUS_HANDLE_NOT_CLOSABLE
;
752 /* Otherwise, bugcheck the OS */
753 KeBugCheckEx(INVALID_KERNEL_HANDLE
, (ULONG_PTR
)Handle
, 0, 0, 0);
757 /* Destroy and unlock the handle entry */
758 ExDestroyHandle(HandleTable
, Handle
, HandleEntry
);
760 /* Now decrement the handle count */
761 ObpDecrementHandleCount(Body
,
762 PsGetCurrentProcess(),
766 /* Dereference the object as well */
767 ObDereferenceObject(Body
);
769 /* Return to caller */
770 OBTRACE(OB_HANDLE_DEBUG
,
771 "%s - Closed handle: %p for %p.\n",
775 return STATUS_SUCCESS
;
779 * @name ObpIncrementHandleCount
781 * The ObpIncrementHandleCount routine <FILLMEIN>
792 * @param HandleAttributes
801 * @return <FILLMEIN>.
808 ObpIncrementHandleCount(IN PVOID Object
,
809 IN PACCESS_STATE AccessState OPTIONAL
,
810 IN KPROCESSOR_MODE AccessMode
,
811 IN ULONG HandleAttributes
,
812 IN PEPROCESS Process
,
813 IN OB_OPEN_REASON OpenReason
)
815 POBJECT_HEADER ObjectHeader
;
816 POBJECT_TYPE ObjectType
;
817 ULONG ProcessHandleCount
;
819 PEPROCESS ExclusiveProcess
;
820 BOOLEAN Exclusive
= FALSE
, NewObject
;
821 POBJECT_HEADER_CREATOR_INFO CreatorInfo
;
823 KPROCESSOR_MODE ProbeMode
;
825 POBJECT_HEADER_NAME_INFO NameInfo
;
828 /* Get the object header and type */
829 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
830 ObjectType
= ObjectHeader
->Type
;
831 OBTRACE(OB_HANDLE_DEBUG
,
832 "%s - Incrementing count for: %p. Reason: %lx. HC PC %lx %lx\n",
836 ObjectHeader
->HandleCount
,
837 ObjectHeader
->PointerCount
);
839 /* Check if caller is forcing user mode */
840 if (HandleAttributes
& OBJ_FORCE_ACCESS_CHECK
)
843 ProbeMode
= UserMode
;
847 /* Keep original setting */
848 ProbeMode
= AccessMode
;
851 /* Lock the object */
852 ObpAcquireObjectLock(ObjectHeader
);
854 /* Charge quota and remove the creator info flag */
855 Status
= ObpChargeQuotaForObject(ObjectHeader
, ObjectType
, &NewObject
);
856 if (!NT_SUCCESS(Status
)) return Status
;
858 /* Check if the open is exclusive */
859 if (HandleAttributes
& OBJ_EXCLUSIVE
)
861 /* Check if the object allows this, or if the inherit flag was given */
862 if ((HandleAttributes
& OBJ_INHERIT
) ||
863 !(ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
))
865 /* Incorrect attempt */
866 Status
= STATUS_INVALID_PARAMETER
;
870 /* Check if we have access to it */
871 ExclusiveProcess
= OBJECT_HEADER_TO_EXCLUSIVE_PROCESS(ObjectHeader
);
872 if ((!(ExclusiveProcess
) && (ObjectHeader
->HandleCount
)) ||
873 ((ExclusiveProcess
) && (ExclusiveProcess
!= PsGetCurrentProcess())))
875 /* This isn't the right process */
876 Status
= STATUS_ACCESS_DENIED
;
880 /* Now you got exclusive access */
883 else if ((ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
) &&
884 (OBJECT_HEADER_TO_EXCLUSIVE_PROCESS(ObjectHeader
)))
886 /* Caller didn't want exclusive access, but the object is exclusive */
887 Status
= STATUS_ACCESS_DENIED
;
891 /* Check for exclusive kernel object */
892 NameInfo
= OBJECT_HEADER_TO_NAME_INFO(ObjectHeader
);
893 if ((NameInfo
) && (NameInfo
->QueryReferences
& OB_FLAG_KERNEL_EXCLUSIVE
) &&
894 (ProbeMode
!= KernelMode
))
896 /* Caller is not kernel, but the object is kernel exclusive */
897 Status
= STATUS_ACCESS_DENIED
;
902 * Check if this is an object that went from 0 handles back to existence,
903 * but doesn't have an open procedure, only a close procedure. This means
904 * that it will never realize that the object is back alive, so we must
907 if (!(ObjectHeader
->HandleCount
) &&
909 (ObjectType
->TypeInfo
.MaintainHandleCount
) &&
910 !(ObjectType
->TypeInfo
.OpenProcedure
) &&
911 (ObjectType
->TypeInfo
.CloseProcedure
))
914 Status
= STATUS_UNSUCCESSFUL
;
918 /* Check if we're opening an existing handle */
919 if ((OpenReason
== ObOpenHandle
) ||
920 ((OpenReason
== ObDuplicateHandle
) && (AccessState
)))
922 /* Validate the caller's access to this object */
923 if (!ObCheckObjectAccess(Object
,
929 /* Access was denied, so fail */
933 else if (OpenReason
== ObCreateHandle
)
935 /* Convert MAXIMUM_ALLOWED to GENERIC_ALL */
936 if (AccessState
->RemainingDesiredAccess
& MAXIMUM_ALLOWED
)
938 /* Mask out MAXIMUM_ALLOWED and stick GENERIC_ALL instead */
939 AccessState
->RemainingDesiredAccess
&= ~MAXIMUM_ALLOWED
;
940 AccessState
->RemainingDesiredAccess
|= GENERIC_ALL
;
943 /* Check if we have to map the GENERIC mask */
944 if (AccessState
->RemainingDesiredAccess
& GENERIC_ACCESS
)
946 /* Map it to the correct access masks */
947 RtlMapGenericMask(&AccessState
->RemainingDesiredAccess
,
948 &ObjectType
->TypeInfo
.GenericMapping
);
951 /* Check if the caller is trying to access system security */
952 if (AccessState
->RemainingDesiredAccess
& ACCESS_SYSTEM_SECURITY
)
955 DPRINT1("ACCESS_SYSTEM_SECURITY not validated!\n");
959 /* Check if this is an exclusive handle */
962 /* Save the owner process */
963 OBJECT_HEADER_TO_QUOTA_INFO(ObjectHeader
)->ExclusiveProcess
= Process
;
966 /* Increase the handle count */
967 InterlockedIncrement(&ObjectHeader
->HandleCount
);
968 ProcessHandleCount
= 0;
970 /* Check if we have a handle database */
971 if (ObjectType
->TypeInfo
.MaintainHandleCount
)
973 /* Increment the handle database */
974 Status
= ObpIncrementHandleDataBase(ObjectHeader
,
976 &ProcessHandleCount
);
977 if (!NT_SUCCESS(Status
))
979 /* FIXME: This should never happen for now */
980 DPRINT1("Unhandled case\n");
986 /* Release the lock */
987 ObpReleaseObjectLock(ObjectHeader
);
989 /* Check if we have an open procedure */
990 Status
= STATUS_SUCCESS
;
991 if (ObjectType
->TypeInfo
.OpenProcedure
)
994 ObpCalloutStart(&CalloutIrql
);
995 Status
= ObjectType
->TypeInfo
.OpenProcedure(OpenReason
,
1000 PreviouslyGrantedAccess
:
1002 ProcessHandleCount
);
1003 ObpCalloutEnd(CalloutIrql
, "Open", ObjectType
, Object
);
1005 /* Check if the open procedure failed */
1006 if (!NT_SUCCESS(Status
))
1008 /* FIXME: This should never happen for now */
1009 DPRINT1("Unhandled case\n");
1015 /* Check if this is a create operation */
1016 if (OpenReason
== ObCreateHandle
)
1018 /* Check if we have creator info */
1019 CreatorInfo
= OBJECT_HEADER_TO_CREATOR_INFO(ObjectHeader
);
1022 /* We do, acquire the lock */
1023 ObpEnterObjectTypeMutex(ObjectType
);
1025 /* Insert us on the list */
1026 InsertTailList(&ObjectType
->TypeList
, &CreatorInfo
->TypeList
);
1028 /* Release the lock */
1029 ObpLeaveObjectTypeMutex(ObjectType
);
1033 /* Increase total number of handles */
1034 Total
= InterlockedIncrement((PLONG
)&ObjectType
->TotalNumberOfHandles
);
1035 if (Total
> ObjectType
->HighWaterNumberOfHandles
)
1038 ObjectType
->HighWaterNumberOfHandles
= Total
;
1041 /* Trace call and return */
1042 OBTRACE(OB_HANDLE_DEBUG
,
1043 "%s - Incremented count for: %p. Reason: %lx HC PC %lx %lx\n",
1047 ObjectHeader
->HandleCount
,
1048 ObjectHeader
->PointerCount
);
1052 /* Release lock and return */
1053 ObpReleaseObjectLock(ObjectHeader
);
1058 * @name ObpIncrementUnnamedHandleCount
1060 * The ObpIncrementUnnamedHandleCount routine <FILLMEIN>
1065 * @param AccessState
1071 * @param HandleAttributes
1080 * @return <FILLMEIN>.
1087 ObpIncrementUnnamedHandleCount(IN PVOID Object
,
1088 IN PACCESS_MASK DesiredAccess
,
1089 IN KPROCESSOR_MODE AccessMode
,
1090 IN ULONG HandleAttributes
,
1091 IN PEPROCESS Process
)
1093 POBJECT_HEADER ObjectHeader
;
1094 POBJECT_TYPE ObjectType
;
1095 ULONG ProcessHandleCount
;
1097 PEPROCESS ExclusiveProcess
;
1098 BOOLEAN Exclusive
= FALSE
, NewObject
;
1099 POBJECT_HEADER_CREATOR_INFO CreatorInfo
;
1103 /* Get the object header and type */
1104 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
1105 ObjectType
= ObjectHeader
->Type
;
1106 OBTRACE(OB_HANDLE_DEBUG
,
1107 "%s - Incrementing count for: %p. UNNAMED. HC PC %lx %lx\n",
1110 ObjectHeader
->HandleCount
,
1111 ObjectHeader
->PointerCount
);
1113 /* Lock the object */
1114 ObpAcquireObjectLock(ObjectHeader
);
1116 /* Charge quota and remove the creator info flag */
1117 Status
= ObpChargeQuotaForObject(ObjectHeader
, ObjectType
, &NewObject
);
1118 if (!NT_SUCCESS(Status
)) return Status
;
1120 /* Check if the open is exclusive */
1121 if (HandleAttributes
& OBJ_EXCLUSIVE
)
1123 /* Check if the object allows this, or if the inherit flag was given */
1124 if ((HandleAttributes
& OBJ_INHERIT
) ||
1125 !(ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
))
1127 /* Incorrect attempt */
1128 Status
= STATUS_INVALID_PARAMETER
;
1132 /* Check if we have access to it */
1133 ExclusiveProcess
= OBJECT_HEADER_TO_EXCLUSIVE_PROCESS(ObjectHeader
);
1134 if ((!(ExclusiveProcess
) && (ObjectHeader
->HandleCount
)) ||
1135 ((ExclusiveProcess
) && (ExclusiveProcess
!= PsGetCurrentProcess())))
1137 /* This isn't the right process */
1138 Status
= STATUS_ACCESS_DENIED
;
1142 /* Now you got exclusive access */
1145 else if ((ObjectHeader
->Flags
& OB_FLAG_EXCLUSIVE
) &&
1146 (OBJECT_HEADER_TO_EXCLUSIVE_PROCESS(ObjectHeader
)))
1148 /* Caller didn't want exclusive access, but the object is exclusive */
1149 Status
= STATUS_ACCESS_DENIED
;
1154 * Check if this is an object that went from 0 handles back to existence,
1155 * but doesn't have an open procedure, only a close procedure. This means
1156 * that it will never realize that the object is back alive, so we must
1159 if (!(ObjectHeader
->HandleCount
) &&
1161 (ObjectType
->TypeInfo
.MaintainHandleCount
) &&
1162 !(ObjectType
->TypeInfo
.OpenProcedure
) &&
1163 (ObjectType
->TypeInfo
.CloseProcedure
))
1166 Status
= STATUS_UNSUCCESSFUL
;
1170 /* Convert MAXIMUM_ALLOWED to GENERIC_ALL */
1171 if (*DesiredAccess
& MAXIMUM_ALLOWED
)
1173 /* Mask out MAXIMUM_ALLOWED and stick GENERIC_ALL instead */
1174 *DesiredAccess
&= ~MAXIMUM_ALLOWED
;
1175 *DesiredAccess
|= GENERIC_ALL
;
1178 /* Check if we have to map the GENERIC mask */
1179 if (*DesiredAccess
& GENERIC_ACCESS
)
1181 /* Map it to the correct access masks */
1182 RtlMapGenericMask(DesiredAccess
,
1183 &ObjectType
->TypeInfo
.GenericMapping
);
1186 /* Check if this is an exclusive handle */
1189 /* Save the owner process */
1190 OBJECT_HEADER_TO_QUOTA_INFO(ObjectHeader
)->ExclusiveProcess
= Process
;
1193 /* Increase the handle count */
1194 InterlockedIncrement(&ObjectHeader
->HandleCount
);
1195 ProcessHandleCount
= 0;
1197 /* Check if we have a handle database */
1198 if (ObjectType
->TypeInfo
.MaintainHandleCount
)
1200 /* Increment the handle database */
1201 Status
= ObpIncrementHandleDataBase(ObjectHeader
,
1203 &ProcessHandleCount
);
1204 if (!NT_SUCCESS(Status
))
1206 /* FIXME: This should never happen for now */
1207 DPRINT1("Unhandled case\n");
1213 /* Release the lock */
1214 ObpReleaseObjectLock(ObjectHeader
);
1216 /* Check if we have an open procedure */
1217 Status
= STATUS_SUCCESS
;
1218 if (ObjectType
->TypeInfo
.OpenProcedure
)
1221 ObpCalloutStart(&CalloutIrql
);
1222 Status
= ObjectType
->TypeInfo
.OpenProcedure(ObCreateHandle
,
1226 ProcessHandleCount
);
1227 ObpCalloutEnd(CalloutIrql
, "Open", ObjectType
, Object
);
1229 /* Check if the open procedure failed */
1230 if (!NT_SUCCESS(Status
))
1232 /* FIXME: This should never happen for now */
1233 DPRINT1("Unhandled case\n");
1239 /* Check if we have creator info */
1240 CreatorInfo
= OBJECT_HEADER_TO_CREATOR_INFO(ObjectHeader
);
1243 /* We do, acquire the lock */
1244 ObpEnterObjectTypeMutex(ObjectType
);
1246 /* Insert us on the list */
1247 InsertTailList(&ObjectType
->TypeList
, &CreatorInfo
->TypeList
);
1249 /* Release the lock */
1250 ObpLeaveObjectTypeMutex(ObjectType
);
1253 /* Increase total number of handles */
1254 Total
= InterlockedIncrement((PLONG
)&ObjectType
->TotalNumberOfHandles
);
1255 if (Total
> ObjectType
->HighWaterNumberOfHandles
)
1258 ObjectType
->HighWaterNumberOfHandles
= Total
;
1261 /* Trace call and return */
1262 OBTRACE(OB_HANDLE_DEBUG
,
1263 "%s - Incremented count for: %p. UNNAMED HC PC %lx %lx\n",
1266 ObjectHeader
->HandleCount
,
1267 ObjectHeader
->PointerCount
);
1271 /* Release lock and return */
1272 ObpReleaseObjectLock(ObjectHeader
);
1277 * @name ObpCreateUnnamedHandle
1279 * The ObpCreateUnnamedHandle routine <FILLMEIN>
1284 * @param DesiredAccess
1287 * @param AdditionalReferences
1290 * @param HandleAttributes
1296 * @param ReturnedObject
1299 * @param ReturnedHandle
1302 * @return <FILLMEIN>.
1309 ObpCreateUnnamedHandle(IN PVOID Object
,
1310 IN ACCESS_MASK DesiredAccess
,
1311 IN ULONG AdditionalReferences
,
1312 IN ULONG HandleAttributes
,
1313 IN KPROCESSOR_MODE AccessMode
,
1314 OUT PVOID
*ReturnedObject
,
1315 OUT PHANDLE ReturnedHandle
)
1317 HANDLE_TABLE_ENTRY NewEntry
;
1318 POBJECT_HEADER ObjectHeader
;
1320 KAPC_STATE ApcState
;
1321 BOOLEAN AttachedToProcess
= FALSE
, KernelHandle
= FALSE
;
1324 ACCESS_MASK GrantedAccess
;
1325 POBJECT_TYPE ObjectType
;
1328 /* Get the object header and type */
1329 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
1330 ObjectType
= ObjectHeader
->Type
;
1331 OBTRACE(OB_HANDLE_DEBUG
,
1332 "%s - Creating handle for: %p. UNNAMED. HC PC %lx %lx\n",
1335 ObjectHeader
->HandleCount
,
1336 ObjectHeader
->PointerCount
);
1338 /* Save the object header */
1339 NewEntry
.Object
= ObjectHeader
;
1341 /* Mask out the internal attributes */
1342 NewEntry
.ObAttributes
|= HandleAttributes
& OBJ_HANDLE_ATTRIBUTES
;
1344 /* Check if this is a kernel handle */
1345 if (HandleAttributes
& OBJ_KERNEL_HANDLE
)
1347 /* Set the handle table */
1348 HandleTable
= ObpKernelHandleTable
;
1349 KernelHandle
= TRUE
;
1351 /* Check if we're not in the system process */
1352 if (PsGetCurrentProcess() != PsInitialSystemProcess
)
1354 /* Attach to the system process */
1355 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
1356 AttachedToProcess
= TRUE
;
1361 /* Get the current handle table */
1362 HandleTable
= PsGetCurrentProcess()->ObjectTable
;
1365 /* Increment the handle count */
1366 Status
= ObpIncrementUnnamedHandleCount(Object
,
1370 PsGetCurrentProcess());
1371 if (!NT_SUCCESS(Status
))
1374 * We failed (meaning security failure, according to NT Internals)
1377 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1381 /* Remove what's not in the valid access mask */
1382 GrantedAccess
= DesiredAccess
& (ObjectType
->TypeInfo
.ValidAccessMask
|
1383 ACCESS_SYSTEM_SECURITY
);
1385 /* Handle extra references */
1386 if (AdditionalReferences
)
1388 /* Add them to the header */
1389 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
,
1390 AdditionalReferences
);
1393 /* Save the access mask */
1394 NewEntry
.GrantedAccess
= GrantedAccess
;
1397 * Create the actual handle. We'll need to do this *after* calling
1398 * ObpIncrementHandleCount to make sure that Object Security is valid
1399 * (specified in Gl00my documentation on Ob)
1401 OBTRACE(OB_HANDLE_DEBUG
,
1402 "%s - Handle Properties: [%p-%lx-%lx]\n",
1404 NewEntry
.Object
, NewEntry
.ObAttributes
& 3, NewEntry
.GrantedAccess
);
1405 Handle
= ExCreateHandle(HandleTable
, &NewEntry
);
1407 /* Make sure we got a handle */
1410 /* Check if this was a kernel handle */
1411 if (KernelHandle
) Handle
= ObMarkHandleAsKernelHandle(Handle
);
1413 /* Return handle and object */
1414 *ReturnedHandle
= Handle
;
1416 /* Return the new object only if caller wanted it biased */
1417 if ((AdditionalReferences
) && (ReturnedObject
))
1420 *ReturnedObject
= Object
;
1423 /* Detach if needed */
1424 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1426 /* Trace and return */
1427 OBTRACE(OB_HANDLE_DEBUG
,
1428 "%s - Returning Handle: %p HC PC %lx %lx\n",
1431 ObjectHeader
->HandleCount
,
1432 ObjectHeader
->PointerCount
);
1433 return STATUS_SUCCESS
;
1436 /* Handle extra references */
1437 if (AdditionalReferences
)
1439 /* Dereference it as many times as required */
1440 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
,
1441 -(LONG
)AdditionalReferences
);
1444 /* Decrement the handle count and detach */
1445 ObpDecrementHandleCount(&ObjectHeader
->Body
,
1446 PsGetCurrentProcess(),
1450 /* Detach and fail */
1451 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1452 return STATUS_INSUFFICIENT_RESOURCES
;
1456 * @name ObpCreateHandle
1458 * The ObpCreateHandle routine <FILLMEIN>
1469 * @param AccessState
1472 * @param AdditionalReferences
1475 * @param HandleAttributes
1481 * @param ReturnedObject
1484 * @param ReturnedHandle
1487 * @return <FILLMEIN>.
1489 * @remarks Cleans up the Lookup Context on return.
1494 ObpCreateHandle(IN OB_OPEN_REASON OpenReason
,
1496 IN POBJECT_TYPE Type OPTIONAL
,
1497 IN PACCESS_STATE AccessState
,
1498 IN ULONG AdditionalReferences
,
1499 IN ULONG HandleAttributes
,
1500 IN POBP_LOOKUP_CONTEXT Context
,
1501 IN KPROCESSOR_MODE AccessMode
,
1502 OUT PVOID
*ReturnedObject
,
1503 OUT PHANDLE ReturnedHandle
)
1505 HANDLE_TABLE_ENTRY NewEntry
;
1506 POBJECT_HEADER ObjectHeader
;
1508 KAPC_STATE ApcState
;
1509 BOOLEAN AttachedToProcess
= FALSE
, KernelHandle
= FALSE
;
1510 POBJECT_TYPE ObjectType
;
1513 ACCESS_MASK DesiredAccess
, GrantedAccess
;
1514 PAUX_ACCESS_DATA AuxData
;
1517 /* Get the object header and type */
1518 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
1519 ObjectType
= ObjectHeader
->Type
;
1520 OBTRACE(OB_HANDLE_DEBUG
,
1521 "%s - Creating handle for: %p. Reason: %lx. HC PC %lx %lx\n",
1525 ObjectHeader
->HandleCount
,
1526 ObjectHeader
->PointerCount
);
1528 /* Check if the types match */
1529 if ((Type
) && (ObjectType
!= Type
))
1531 /* They don't, cleanup */
1532 if (Context
) ObpReleaseLookupContext(Context
);
1533 return STATUS_OBJECT_TYPE_MISMATCH
;
1536 /* Save the object header */
1537 NewEntry
.Object
= ObjectHeader
;
1539 /* Check if this is a kernel handle */
1540 if (HandleAttributes
& OBJ_KERNEL_HANDLE
)
1542 /* Set the handle table */
1543 HandleTable
= ObpKernelHandleTable
;
1544 KernelHandle
= TRUE
;
1546 /* Check if we're not in the system process */
1547 if (PsGetCurrentProcess() != PsInitialSystemProcess
)
1549 /* Attach to the system process */
1550 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
1551 AttachedToProcess
= TRUE
;
1556 /* Get the current handle table */
1557 HandleTable
= PsGetCurrentProcess()->ObjectTable
;
1560 /* Increment the handle count */
1561 Status
= ObpIncrementHandleCount(Object
,
1565 PsGetCurrentProcess(),
1567 if (!NT_SUCCESS(Status
))
1570 * We failed (meaning security failure, according to NT Internals)
1573 if (Context
) ObpReleaseLookupContext(Context
);
1574 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1578 /* Check if we are doing audits on close */
1579 if (AccessState
->GenerateOnClose
)
1581 /* Force the attribute on */
1582 HandleAttributes
|= OBJ_AUDIT_OBJECT_CLOSE
;
1585 /* Mask out the internal attributes */
1586 NewEntry
.ObAttributes
|= (HandleAttributes
& OBJ_HANDLE_ATTRIBUTES
);
1588 /* Get the original desired access */
1589 DesiredAccess
= AccessState
->RemainingDesiredAccess
|
1590 AccessState
->PreviouslyGrantedAccess
;
1592 /* Remove what's not in the valid access mask */
1593 GrantedAccess
= DesiredAccess
& (ObjectType
->TypeInfo
.ValidAccessMask
|
1594 ACCESS_SYSTEM_SECURITY
);
1596 /* Update the value in the access state */
1597 AccessState
->PreviouslyGrantedAccess
= GrantedAccess
;
1599 /* Get the auxiliary data */
1600 AuxData
= AccessState
->AuxData
;
1602 /* Handle extra references */
1603 if (AdditionalReferences
)
1605 /* Add them to the header */
1606 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
, AdditionalReferences
);
1609 /* Now we can release the object */
1610 if (Context
) ObpReleaseLookupContext(Context
);
1612 /* Save the access mask */
1613 NewEntry
.GrantedAccess
= GrantedAccess
;
1616 * Create the actual handle. We'll need to do this *after* calling
1617 * ObpIncrementHandleCount to make sure that Object Security is valid
1618 * (specified in Gl00my documentation on Ob)
1620 OBTRACE(OB_HANDLE_DEBUG
,
1621 "%s - Handle Properties: [%p-%lx-%lx]\n",
1623 NewEntry
.Object
, NewEntry
.ObAttributes
& 3, NewEntry
.GrantedAccess
);
1624 Handle
= ExCreateHandle(HandleTable
, &NewEntry
);
1626 /* Make sure we got a handle */
1629 /* Check if this was a kernel handle */
1630 if (KernelHandle
) Handle
= ObMarkHandleAsKernelHandle(Handle
);
1633 *ReturnedHandle
= Handle
;
1635 /* Check if we need to generate on audit */
1636 if (AccessState
->GenerateAudit
)
1638 /* Audit the handle creation */
1639 //SeAuditHandleCreation(AccessState, Handle);
1642 /* Check if this was a create */
1643 if (OpenReason
== ObCreateHandle
)
1645 /* Check if we need to audit the privileges */
1646 if ((AuxData
->PrivilegeSet
) &&
1647 (AuxData
->PrivilegeSet
->PrivilegeCount
))
1651 SePrivilegeObjectAuditAlarm(Handle
,
1653 SubjectSecurityContext
,
1655 AuxData
->PrivilegeSet
,
1657 ExGetPreviousMode());
1662 /* Return the new object only if caller wanted it biased */
1663 if ((AdditionalReferences
) && (ReturnedObject
))
1666 *ReturnedObject
= Object
;
1669 /* Detach if needed */
1670 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1672 /* Trace and return */
1673 OBTRACE(OB_HANDLE_DEBUG
,
1674 "%s - Returning Handle: %p HC PC %lx %lx\n",
1677 ObjectHeader
->HandleCount
,
1678 ObjectHeader
->PointerCount
);
1679 return STATUS_SUCCESS
;
1682 /* Decrement the handle count and detach */
1683 ObpDecrementHandleCount(&ObjectHeader
->Body
,
1684 PsGetCurrentProcess(),
1688 /* Handle extra references */
1689 if (AdditionalReferences
)
1691 /* Check how many extra references were added */
1692 if (AdditionalReferences
> 1)
1694 /* Dereference it many times */
1695 InterlockedExchangeAdd(&ObjectHeader
->PointerCount
,
1696 -(LONG
)(AdditionalReferences
- 1));
1699 /* Dereference the object one last time */
1700 ObDereferenceObject(Object
);
1703 /* Detach if necessary and fail */
1704 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1705 return STATUS_INSUFFICIENT_RESOURCES
;
1709 * @name ObpCloseHandle
1711 * The ObpCloseHandle routine <FILLMEIN>
1719 * @return <FILLMEIN>.
1726 ObpCloseHandle(IN HANDLE Handle
,
1727 IN KPROCESSOR_MODE AccessMode
)
1730 BOOLEAN AttachedToProcess
= FALSE
;
1731 KAPC_STATE ApcState
;
1732 PHANDLE_TABLE_ENTRY HandleTableEntry
;
1734 PEPROCESS Process
= PsGetCurrentProcess();
1736 OBTRACE(OB_HANDLE_DEBUG
,
1737 "%s - Closing handle: %p\n", __FUNCTION__
, Handle
);
1739 if (AccessMode
== KernelMode
&& Handle
== (HANDLE
)-1)
1740 return STATUS_INVALID_HANDLE
;
1742 /* Check if we're dealing with a kernel handle */
1743 if (ObpIsKernelHandle(Handle
, AccessMode
))
1745 /* Use the kernel table and convert the handle */
1746 HandleTable
= ObpKernelHandleTable
;
1747 Handle
= ObKernelHandleToHandle(Handle
);
1749 /* Check if we're not in the system process */
1750 if (Process
!= PsInitialSystemProcess
)
1752 /* Attach to the system process */
1753 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
1754 AttachedToProcess
= TRUE
;
1759 /* Use the process's handle table */
1760 HandleTable
= Process
->ObjectTable
;
1763 /* Enter a critical region to protect handle access */
1764 KeEnterCriticalRegion();
1766 /* Get the handle entry */
1767 HandleTableEntry
= ExMapHandleToPointer(HandleTable
, Handle
);
1768 if (HandleTableEntry
)
1770 /* Now close the entry */
1771 Status
= ObpCloseHandleTableEntry(HandleTable
,
1777 /* We can quit the critical region now */
1778 KeLeaveCriticalRegion();
1780 /* Detach and return success */
1781 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1785 /* We failed, quit the critical region */
1786 KeLeaveCriticalRegion();
1789 if (AttachedToProcess
) KeUnstackDetachProcess(&ApcState
);
1791 /* Check if we have a valid handle that's not the process or thread */
1793 (Handle
!= NtCurrentProcess()) &&
1794 (Handle
!= NtCurrentThread()))
1796 /* Check if we came from user mode */
1797 if (AccessMode
!= KernelMode
)
1799 /* Check if we have no debug port */
1800 if (Process
->DebugPort
)
1802 /* Make sure we're not attached */
1803 if (!KeIsAttachedProcess())
1805 /* Raise an exception */
1806 return KeRaiseUserException(STATUS_INVALID_HANDLE
);
1812 /* This is kernel mode. Check if we're exiting */
1813 if (!(PsIsThreadTerminating(PsGetCurrentThread())) &&
1816 /* Check if the debugger is enabled */
1817 if (KdDebuggerEnabled
)
1820 KeBugCheckEx(INVALID_KERNEL_HANDLE
, (ULONG_PTR
)Handle
, 1, 0, 0);
1826 /* Set invalid status */
1827 Status
= STATUS_INVALID_HANDLE
;
1831 OBTRACE(OB_HANDLE_DEBUG
,
1832 "%s - Closed handle: %p S: %lx\n",
1833 __FUNCTION__
, Handle
, Status
);
1838 * @name ObpSetHandleAttributes
1840 * The ObpSetHandleAttributes routine <FILLMEIN>
1842 * @param HandleTableEntry
1848 * @return <FILLMEIN>.
1855 ObpSetHandleAttributes(IN OUT PHANDLE_TABLE_ENTRY HandleTableEntry
,
1856 IN ULONG_PTR Context
)
1858 POBP_SET_HANDLE_ATTRIBUTES_CONTEXT SetHandleInfo
= (PVOID
)Context
;
1859 POBJECT_HEADER ObjectHeader
= ObpGetHandleObject(HandleTableEntry
);
1861 /* Check if making the handle inheritable */
1862 if (SetHandleInfo
->Information
.Inherit
)
1864 /* Check if inheriting is not supported for this object */
1865 if (ObjectHeader
->Type
->TypeInfo
.InvalidAttributes
& OBJ_INHERIT
)
1867 /* Fail without changing anything */
1872 HandleTableEntry
->ObAttributes
|= OBJ_INHERIT
;
1876 /* Otherwise this implies we're removing the flag */
1877 HandleTableEntry
->ObAttributes
&= ~OBJ_INHERIT
;
1880 /* Check if making the handle protected */
1881 if (SetHandleInfo
->Information
.ProtectFromClose
)
1884 HandleTableEntry
->GrantedAccess
|= ObpAccessProtectCloseBit
;
1888 /* Otherwise, remove it */
1889 HandleTableEntry
->GrantedAccess
&= ~ObpAccessProtectCloseBit
;
1892 /* Return success */
1897 * @name ObpCloseHandleCallback
1899 * The ObpCloseHandleCallback routine <FILLMEIN>
1901 * @param HandleTable
1907 * @param GrantedAccess
1913 * @return <FILLMEIN>.
1920 ObpCloseHandleCallback(IN PHANDLE_TABLE_ENTRY HandleTableEntry
,
1924 POBP_CLOSE_HANDLE_CONTEXT CloseContext
= (POBP_CLOSE_HANDLE_CONTEXT
)Context
;
1926 /* Simply decrement the handle count */
1927 ObpCloseHandleTableEntry(CloseContext
->HandleTable
,
1930 CloseContext
->AccessMode
,
1936 * @name ObpDuplicateHandleCallback
1938 * The ObpDuplicateHandleCallback routine <FILLMEIN>
1940 * @param HandleTable
1943 * @param HandleTableEntry
1949 * @return <FILLMEIN>.
1956 ObpDuplicateHandleCallback(IN PEPROCESS Process
,
1957 IN PHANDLE_TABLE HandleTable
,
1958 IN PHANDLE_TABLE_ENTRY OldEntry
,
1959 IN PHANDLE_TABLE_ENTRY HandleTableEntry
)
1961 POBJECT_HEADER ObjectHeader
;
1962 BOOLEAN Ret
= FALSE
;
1963 ACCESS_STATE AccessState
;
1967 /* Make sure that the handle is inheritable */
1968 Ret
= (HandleTableEntry
->ObAttributes
& OBJ_INHERIT
) != 0;
1971 /* Get the object header */
1972 ObjectHeader
= ObpGetHandleObject(HandleTableEntry
);
1974 /* Increment the pointer count */
1975 InterlockedIncrement(&ObjectHeader
->PointerCount
);
1977 /* Release the handle lock */
1978 ExUnlockHandleTableEntry(HandleTable
, OldEntry
);
1980 /* Setup the access state */
1981 AccessState
.PreviouslyGrantedAccess
= HandleTableEntry
->GrantedAccess
;
1983 /* Call the shared routine for incrementing handles */
1984 Status
= ObpIncrementHandleCount(&ObjectHeader
->Body
,
1987 HandleTableEntry
->ObAttributes
& OBJ_HANDLE_ATTRIBUTES
,
1990 if (!NT_SUCCESS(Status
))
1992 /* Return failure */
1993 ObDereferenceObject(&ObjectHeader
->Body
);
1999 /* Release the handle lock */
2000 ExUnlockHandleTableEntry(HandleTable
, OldEntry
);
2003 /* Return duplication result */
2008 * @name ObClearProcessHandleTable
2010 * The ObClearProcessHandleTable routine clears the handle table
2011 * of the given process.
2014 * The process of which the handle table should be cleared.
2023 ObClearProcessHandleTable(IN PEPROCESS Process
)
2025 PHANDLE_TABLE HandleTable
;
2026 OBP_CLOSE_HANDLE_CONTEXT Context
;
2027 KAPC_STATE ApcState
;
2028 BOOLEAN AttachedToProcess
= FALSE
;
2032 /* Ensure the handle table doesn't go away while we use it */
2033 HandleTable
= ObReferenceProcessHandleTable(Process
);
2034 if (!HandleTable
) return;
2036 /* Attach to the current process if needed */
2037 if (PsGetCurrentProcess() != Process
)
2039 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
2040 AttachedToProcess
= TRUE
;
2043 /* Enter a critical region */
2044 KeEnterCriticalRegion();
2046 /* Fill out the context */
2047 Context
.AccessMode
= UserMode
;
2048 Context
.HandleTable
= HandleTable
;
2050 /* Sweep the handle table to close all handles */
2051 ExSweepHandleTable(HandleTable
,
2052 ObpCloseHandleCallback
,
2055 /* Leave the critical region */
2056 KeLeaveCriticalRegion();
2058 /* Detach if needed */
2059 if (AttachedToProcess
)
2060 KeUnstackDetachProcess(&ApcState
);
2062 /* Let the handle table go */
2063 ObDereferenceProcessHandleTable(Process
);
2067 * @name ObInitProcess
2069 * The ObInitProcess routine initializes the handle table for the process
2070 * to be initialized, by either creating a new one or duplicating it from
2071 * the parent process.
2074 * A parent process (optional).
2077 * The process to initialize.
2079 * @return Success or failure.
2086 ObInitProcess(IN PEPROCESS Parent OPTIONAL
,
2087 IN PEPROCESS Process
)
2089 PHANDLE_TABLE ParentTable
, ObjectTable
;
2091 /* Check for a parent */
2094 /* Reference the parent's table */
2095 ParentTable
= ObReferenceProcessHandleTable(Parent
);
2096 if (!ParentTable
) return STATUS_PROCESS_IS_TERMINATING
;
2099 ObjectTable
= ExDupHandleTable(Process
,
2101 ObpDuplicateHandleCallback
,
2106 /* Otherwise just create a new table */
2108 ObjectTable
= ExCreateHandleTable(Process
);
2111 /* Make sure we have a table */
2115 Process
->ObjectTable
= ObjectTable
;
2117 /* Check for auditing */
2118 if (SeDetailedAuditingWithToken(NULL
))
2121 DPRINT1("Need auditing!\n");
2124 /* Get rid of the old table now */
2125 if (ParentTable
) ObDereferenceProcessHandleTable(Parent
);
2128 return STATUS_SUCCESS
;
2133 Process
->ObjectTable
= NULL
;
2134 if (ParentTable
) ObDereferenceProcessHandleTable(Parent
);
2135 return STATUS_INSUFFICIENT_RESOURCES
;
2140 * @name ObKillProcess
2142 * The ObKillProcess routine performs rundown operations on the process,
2143 * then clears and destroys its handle table.
2146 * The process to be killed.
2150 * @remarks Called by the Object Manager cleanup code (kernel)
2151 * when a process is to be destroyed.
2156 ObKillProcess(IN PEPROCESS Process
)
2158 PHANDLE_TABLE HandleTable
;
2159 OBP_CLOSE_HANDLE_CONTEXT Context
;
2163 /* Wait for process rundown and then complete it */
2164 ExWaitForRundownProtectionRelease(&Process
->RundownProtect
);
2165 ExRundownCompleted(&Process
->RundownProtect
);
2167 /* Get the object table */
2168 HandleTable
= Process
->ObjectTable
;
2169 if (!HandleTable
) return;
2171 /* Disable hard errors while we close handles */
2172 HardErrors
= IoSetThreadHardErrorMode(FALSE
);
2174 /* Enter a critical region */
2175 KeEnterCriticalRegion();
2177 /* Fill out the context */
2178 Context
.AccessMode
= KernelMode
;
2179 Context
.HandleTable
= HandleTable
;
2181 /* Sweep the handle table to close all handles */
2182 ExSweepHandleTable(HandleTable
,
2183 ObpCloseHandleCallback
,
2185 ASSERT(HandleTable
->HandleCount
== 0);
2187 /* Leave the critical region */
2188 KeLeaveCriticalRegion();
2190 /* Re-enable hard errors */
2191 IoSetThreadHardErrorMode(HardErrors
);
2193 /* Destroy the object table */
2194 Process
->ObjectTable
= NULL
;
2195 ExDestroyHandleTable(HandleTable
, NULL
);
2200 ObDuplicateObject(IN PEPROCESS SourceProcess
,
2201 IN HANDLE SourceHandle
,
2202 IN PEPROCESS TargetProcess OPTIONAL
,
2203 IN PHANDLE TargetHandle OPTIONAL
,
2204 IN ACCESS_MASK DesiredAccess
,
2205 IN ULONG HandleAttributes
,
2207 IN KPROCESSOR_MODE PreviousMode
)
2209 HANDLE_TABLE_ENTRY NewHandleEntry
;
2210 BOOLEAN AttachedToProcess
= FALSE
;
2212 POBJECT_HEADER ObjectHeader
;
2213 POBJECT_TYPE ObjectType
;
2215 KAPC_STATE ApcState
;
2217 ACCESS_MASK TargetAccess
, SourceAccess
;
2218 ACCESS_STATE AccessState
;
2219 PACCESS_STATE PassedAccessState
= NULL
;
2220 AUX_ACCESS_DATA AuxData
;
2221 PHANDLE_TABLE HandleTable
;
2222 OBJECT_HANDLE_INFORMATION HandleInformation
;
2224 BOOLEAN KernelHandle
= FALSE
;
2227 OBTRACE(OB_HANDLE_DEBUG
,
2228 "%s - Duplicating handle: %p for %p into %p\n",
2234 /* Assume failure */
2235 if (TargetHandle
) *TargetHandle
= NULL
;
2237 /* Check if we're not duplicating the same access */
2238 if (!(Options
& DUPLICATE_SAME_ACCESS
))
2240 /* Validate the desired access */
2241 Status
= STATUS_SUCCESS
; //ObpValidateDesiredAccess(DesiredAccess);
2242 if (!NT_SUCCESS(Status
)) return Status
;
2245 /* Reference the object table */
2246 HandleTable
= ObReferenceProcessHandleTable(SourceProcess
);
2247 if (!HandleTable
) return STATUS_PROCESS_IS_TERMINATING
;
2249 /* Reference the process object */
2250 Status
= ObpReferenceProcessObjectByHandle(SourceHandle
,
2257 if (!NT_SUCCESS(Status
))
2260 ObDereferenceProcessHandleTable(SourceProcess
);
2265 /* Check if we have to don't have to audit object close */
2266 if (!(HandleInformation
.HandleAttributes
& OBJ_AUDIT_OBJECT_CLOSE
))
2268 /* Then there is no audit mask */
2273 /* Check if there's no target process */
2276 /* Check if the caller wanted actual duplication */
2277 if (!(Options
& DUPLICATE_CLOSE_SOURCE
))
2279 /* Invalid request */
2280 Status
= STATUS_INVALID_PARAMETER
;
2284 /* Otherwise, do the attach */
2285 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2287 /* Close the handle and detach */
2288 NtClose(SourceHandle
);
2289 KeUnstackDetachProcess(&ApcState
);
2293 ObDereferenceProcessHandleTable(SourceProcess
);
2294 ObDereferenceObject(SourceObject
);
2298 /* Create a kernel handle if asked, but only in the system process */
2299 if (PreviousMode
== KernelMode
&&
2300 HandleAttributes
& OBJ_KERNEL_HANDLE
&&
2301 TargetProcess
== PsInitialSystemProcess
)
2303 KernelHandle
= TRUE
;
2306 /* Get the target handle table */
2307 HandleTable
= ObReferenceProcessHandleTable(TargetProcess
);
2310 /* Check if the caller wanted us to close the handle */
2311 if (Options
& DUPLICATE_CLOSE_SOURCE
)
2314 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2316 /* Close the handle and detach */
2317 NtClose(SourceHandle
);
2318 KeUnstackDetachProcess(&ApcState
);
2322 ObDereferenceProcessHandleTable(SourceProcess
);
2323 ObDereferenceObject(SourceObject
);
2324 return STATUS_PROCESS_IS_TERMINATING
;
2327 /* Get the source access */
2328 SourceAccess
= HandleInformation
.GrantedAccess
;
2330 /* Check if we're not in the target process */
2331 if (TargetProcess
!= PsGetCurrentProcess())
2334 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
2335 AttachedToProcess
= TRUE
;
2338 /* Check if we're duplicating the attributes */
2339 if (Options
& DUPLICATE_SAME_ATTRIBUTES
)
2341 /* Duplicate them */
2342 HandleAttributes
= HandleInformation
.HandleAttributes
;
2346 /* Don't allow caller to bypass auditing */
2347 HandleAttributes
|= HandleInformation
.HandleAttributes
&
2348 OBJ_AUDIT_OBJECT_CLOSE
;
2351 /* Check if we're duplicating the access */
2352 if (Options
& DUPLICATE_SAME_ACCESS
) DesiredAccess
= SourceAccess
;
2354 /* Get object data */
2355 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(SourceObject
);
2356 ObjectType
= ObjectHeader
->Type
;
2358 /* Fill out the entry */
2359 RtlZeroMemory(&NewHandleEntry
, sizeof(HANDLE_TABLE_ENTRY
));
2360 NewHandleEntry
.Object
= ObjectHeader
;
2361 NewHandleEntry
.ObAttributes
|= (HandleAttributes
& OBJ_HANDLE_ATTRIBUTES
);
2363 /* Check if we're using a generic mask */
2364 if (DesiredAccess
& GENERIC_ACCESS
)
2367 RtlMapGenericMask(&DesiredAccess
,
2368 &ObjectType
->TypeInfo
.GenericMapping
);
2371 /* Set the target access, always propagate ACCESS_SYSTEM_SECURITY */
2372 TargetAccess
= DesiredAccess
& (ObjectType
->TypeInfo
.ValidAccessMask
|
2373 ACCESS_SYSTEM_SECURITY
);
2374 NewHandleEntry
.GrantedAccess
= TargetAccess
;
2376 /* Check if we're asking for new access */
2377 if (TargetAccess
& ~SourceAccess
)
2379 /* We are. We need the security procedure to validate this */
2380 if (ObjectType
->TypeInfo
.SecurityProcedure
== SeDefaultObjectMethod
)
2382 /* Use our built-in access state */
2383 PassedAccessState
= &AccessState
;
2384 Status
= SeCreateAccessState(&AccessState
,
2387 &ObjectType
->TypeInfo
.GenericMapping
);
2391 /* Otherwise we can't allow this privilege elevation */
2392 Status
= STATUS_ACCESS_DENIED
;
2397 /* We don't need an access state */
2398 Status
= STATUS_SUCCESS
;
2401 /* Make sure the access state was created OK */
2402 if (NT_SUCCESS(Status
))
2404 /* Add a new handle */
2405 Status
= ObpIncrementHandleCount(SourceObject
,
2409 PsGetCurrentProcess(),
2413 /* Check if we were attached */
2414 if (AttachedToProcess
)
2416 /* We can safely detach now */
2417 KeUnstackDetachProcess(&ApcState
);
2418 AttachedToProcess
= FALSE
;
2421 /* Check if we have to close the source handle */
2422 if (Options
& DUPLICATE_CLOSE_SOURCE
)
2424 /* Attach and close */
2425 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
2426 NtClose(SourceHandle
);
2427 KeUnstackDetachProcess(&ApcState
);
2430 /* Check if we had an access state */
2431 if (PassedAccessState
) SeDeleteAccessState(PassedAccessState
);
2433 /* Now check if incrementing actually failed */
2434 if (!NT_SUCCESS(Status
))
2436 /* Dereference handle tables */
2437 ObDereferenceProcessHandleTable(SourceProcess
);
2438 ObDereferenceProcessHandleTable(TargetProcess
);
2440 /* Dereference the source object */
2441 ObDereferenceObject(SourceObject
);
2445 /* Now create the handle */
2446 NewHandle
= ExCreateHandle(HandleTable
, &NewHandleEntry
);
2449 /* Undo the increment */
2450 ObpDecrementHandleCount(SourceObject
,
2455 /* Deference the object and set failure status */
2456 ObDereferenceObject(SourceObject
);
2457 Status
= STATUS_INSUFFICIENT_RESOURCES
;
2460 /* Mark it as a kernel handle if requested */
2463 NewHandle
= ObMarkHandleAsKernelHandle(NewHandle
);
2466 /* Return the handle */
2467 if (TargetHandle
) *TargetHandle
= NewHandle
;
2469 /* Dereference handle tables */
2470 ObDereferenceProcessHandleTable(SourceProcess
);
2471 ObDereferenceProcessHandleTable(TargetProcess
);
2474 OBTRACE(OB_HANDLE_DEBUG
,
2475 "%s - Duplicated handle: %p for %p into %p. Source: %p HC PC %lx %lx\n",
2481 ObjectHeader
->PointerCount
,
2482 ObjectHeader
->HandleCount
);
2486 /* PUBLIC FUNCTIONS *********************************************************/
2489 * @name ObOpenObjectByName
2492 * The ObOpenObjectByName routine <FILLMEIN>
2494 * @param ObjectAttributes
2503 * @param PassedAccessState
2506 * @param DesiredAccess
2509 * @param ParseContext
2515 * @return <FILLMEIN>.
2522 ObOpenObjectByName(IN POBJECT_ATTRIBUTES ObjectAttributes
,
2523 IN POBJECT_TYPE ObjectType
,
2524 IN KPROCESSOR_MODE AccessMode
,
2525 IN PACCESS_STATE PassedAccessState
,
2526 IN ACCESS_MASK DesiredAccess
,
2527 IN OUT PVOID ParseContext
,
2530 PVOID Object
= NULL
;
2531 UNICODE_STRING ObjectName
;
2532 NTSTATUS Status
, Status2
;
2533 POBJECT_HEADER ObjectHeader
;
2534 PGENERIC_MAPPING GenericMapping
= NULL
;
2535 OB_OPEN_REASON OpenReason
;
2536 POB_TEMP_BUFFER TempBuffer
;
2539 /* Assume failure */
2542 /* Check if we didn't get any Object Attributes */
2543 if (!ObjectAttributes
)
2545 /* Fail with special status code */
2546 return STATUS_INVALID_PARAMETER
;
2549 /* Allocate the temporary buffer */
2550 TempBuffer
= ExAllocatePoolWithTag(NonPagedPool
,
2551 sizeof(OB_TEMP_BUFFER
),
2552 TAG_OB_TEMP_STORAGE
);
2553 if (!TempBuffer
) return STATUS_INSUFFICIENT_RESOURCES
;
2555 /* Capture all the info */
2556 Status
= ObpCaptureObjectCreateInformation(ObjectAttributes
,
2560 &TempBuffer
->ObjectCreateInfo
,
2562 if (!NT_SUCCESS(Status
))
2565 ExFreePoolWithTag(TempBuffer
, TAG_OB_TEMP_STORAGE
);
2569 /* Check if we didn't get an access state */
2570 if (!PassedAccessState
)
2572 /* Try to get the generic mapping if we can */
2573 if (ObjectType
) GenericMapping
= &ObjectType
->TypeInfo
.GenericMapping
;
2575 /* Use our built-in access state */
2576 PassedAccessState
= &TempBuffer
->LocalAccessState
;
2577 Status
= SeCreateAccessState(&TempBuffer
->LocalAccessState
,
2578 &TempBuffer
->AuxData
,
2581 if (!NT_SUCCESS(Status
)) goto Quickie
;
2584 /* Get the security descriptor */
2585 if (TempBuffer
->ObjectCreateInfo
.SecurityDescriptor
)
2587 /* Save it in the access state */
2588 PassedAccessState
->SecurityDescriptor
=
2589 TempBuffer
->ObjectCreateInfo
.SecurityDescriptor
;
2592 /* Validate the access mask */
2593 Status
= ObpValidateAccessMask(PassedAccessState
);
2594 if (!NT_SUCCESS(Status
))
2596 /* Cleanup after lookup */
2597 ObpReleaseLookupContext(&TempBuffer
->LookupContext
);
2601 /* Now do the lookup */
2602 Status
= ObpLookupObjectName(TempBuffer
->ObjectCreateInfo
.RootDirectory
,
2604 TempBuffer
->ObjectCreateInfo
.Attributes
,
2608 TempBuffer
->ObjectCreateInfo
.SecurityQos
,
2611 &TempBuffer
->LookupContext
,
2613 if (!NT_SUCCESS(Status
))
2615 /* Cleanup after lookup */
2616 ObpReleaseLookupContext(&TempBuffer
->LookupContext
);
2620 /* Check if this object has create information */
2621 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2622 if (ObjectHeader
->Flags
& OB_FLAG_CREATE_INFO
)
2624 /* Then we are creating a new handle */
2625 OpenReason
= ObCreateHandle
;
2627 /* Check if we still have create info */
2628 if (ObjectHeader
->ObjectCreateInfo
)
2631 ObpFreeObjectCreateInformation(ObjectHeader
->
2633 ObjectHeader
->ObjectCreateInfo
= NULL
;
2638 /* Otherwise, we are merely opening it */
2639 OpenReason
= ObOpenHandle
;
2642 /* Check if we have invalid object attributes */
2643 if (ObjectHeader
->Type
->TypeInfo
.InvalidAttributes
&
2644 TempBuffer
->ObjectCreateInfo
.Attributes
)
2646 /* Set failure code */
2647 Status
= STATUS_INVALID_PARAMETER
;
2649 /* Cleanup after lookup */
2650 ObpReleaseLookupContext(&TempBuffer
->LookupContext
);
2652 /* Dereference the object */
2653 ObDereferenceObject(Object
);
2657 /* Create the actual handle now */
2658 Status2
= ObpCreateHandle(OpenReason
,
2663 TempBuffer
->ObjectCreateInfo
.Attributes
,
2664 &TempBuffer
->LookupContext
,
2668 if (!NT_SUCCESS(Status2
))
2670 ObDereferenceObject(Object
);
2676 /* Delete the access state */
2677 if (PassedAccessState
== &TempBuffer
->LocalAccessState
)
2679 SeDeleteAccessState(PassedAccessState
);
2683 /* Release the object attributes and temporary buffer */
2684 ObpReleaseObjectCreateInformation(&TempBuffer
->ObjectCreateInfo
);
2685 if (ObjectName
.Buffer
) ObpFreeObjectNameBuffer(&ObjectName
);
2686 ExFreePoolWithTag(TempBuffer
, TAG_OB_TEMP_STORAGE
);
2689 OBTRACE(OB_HANDLE_DEBUG
,
2690 "%s - returning Object %p with PC S: %lx %lx\n",
2693 Object
? OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
: -1,
2699 * @name ObOpenObjectByPointer
2702 * The ObOpenObjectByPointer routine <FILLMEIN>
2707 * @param HandleAttributes
2710 * @param PassedAccessState
2713 * @param DesiredAccess
2725 * @return <FILLMEIN>.
2732 ObOpenObjectByPointer(IN PVOID Object
,
2733 IN ULONG HandleAttributes
,
2734 IN PACCESS_STATE PassedAccessState
,
2735 IN ACCESS_MASK DesiredAccess
,
2736 IN POBJECT_TYPE ObjectType
,
2737 IN KPROCESSOR_MODE AccessMode
,
2740 POBJECT_HEADER Header
;
2742 ACCESS_STATE AccessState
;
2743 AUX_ACCESS_DATA AuxData
;
2746 /* Assume failure */
2749 /* Reference the object */
2750 Status
= ObReferenceObjectByPointer(Object
,
2754 if (!NT_SUCCESS(Status
)) return Status
;
2756 /* Get the Header Info */
2757 Header
= OBJECT_TO_OBJECT_HEADER(Object
);
2759 /* Check if we didn't get an access state */
2760 if (!PassedAccessState
)
2762 /* Use our built-in access state */
2763 PassedAccessState
= &AccessState
;
2764 Status
= SeCreateAccessState(&AccessState
,
2767 &Header
->Type
->TypeInfo
.GenericMapping
);
2768 if (!NT_SUCCESS(Status
))
2771 ObDereferenceObject(Object
);
2776 /* Check if we have invalid object attributes */
2777 if (Header
->Type
->TypeInfo
.InvalidAttributes
& HandleAttributes
)
2779 /* Delete the access state */
2780 if (PassedAccessState
== &AccessState
)
2782 SeDeleteAccessState(PassedAccessState
);
2785 /* Dereference the object */
2786 ObDereferenceObject(Object
);
2787 return STATUS_INVALID_PARAMETER
;
2790 /* Create the handle */
2791 Status
= ObpCreateHandle(ObOpenHandle
,
2801 if (!NT_SUCCESS(Status
)) ObDereferenceObject(Object
);
2803 /* Delete the access state */
2804 if (PassedAccessState
== &AccessState
)
2806 SeDeleteAccessState(PassedAccessState
);
2810 OBTRACE(OB_HANDLE_DEBUG
,
2811 "%s - returning Object with PC S: %lx %lx\n",
2813 OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
,
2819 * @name ObFindHandleForObject
2822 * The ObFindHandleForObject routine <FILLMEIN>
2833 * @param HandleInformation
2836 * @param HandleReturn
2839 * @return <FILLMEIN>.
2846 ObFindHandleForObject(IN PEPROCESS Process
,
2848 IN POBJECT_TYPE ObjectType
,
2849 IN POBJECT_HANDLE_INFORMATION HandleInformation
,
2852 OBP_FIND_HANDLE_DATA FindData
;
2853 BOOLEAN Result
= FALSE
;
2856 /* Make sure we have an object table */
2857 ObjectTable
= ObReferenceProcessHandleTable(Process
);
2860 /* Check if we have an object */
2863 /* Set its header */
2864 FindData
.ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2868 /* Otherwise, no object to match*/
2869 FindData
.ObjectHeader
= NULL
;
2872 /* Set other information */
2873 FindData
.ObjectType
= ObjectType
;
2874 FindData
.HandleInformation
= HandleInformation
;
2876 /* Enumerate the handle table */
2877 if (ExEnumHandleTable(Process
->ObjectTable
,
2878 ObpEnumFindHandleProcedure
,
2886 /* Let go of the table */
2887 ObDereferenceProcessHandleTable(Process
);
2890 /* Return the result */
2895 * @name ObInsertObject
2898 * The ObInsertObject routine <FILLMEIN>
2903 * @param PassedAccessState
2906 * @param DesiredAccess
2909 * @param AdditionalReferences
2912 * @param ReferencedObject
2918 * @return <FILLMEIN>.
2925 ObInsertObject(IN PVOID Object
,
2926 IN PACCESS_STATE AccessState OPTIONAL
,
2927 IN ACCESS_MASK DesiredAccess
,
2928 IN ULONG ObjectPointerBias
,
2929 OUT PVOID
*NewObject OPTIONAL
,
2932 POBJECT_CREATE_INFORMATION ObjectCreateInfo
;
2933 POBJECT_HEADER ObjectHeader
;
2934 POBJECT_TYPE ObjectType
;
2935 PUNICODE_STRING ObjectName
;
2937 PSECURITY_DESCRIPTOR ParentDescriptor
= NULL
;
2938 BOOLEAN SdAllocated
= FALSE
;
2939 POBJECT_HEADER_NAME_INFO ObjectNameInfo
;
2940 OBP_LOOKUP_CONTEXT Context
;
2941 ACCESS_STATE LocalAccessState
;
2942 AUX_ACCESS_DATA AuxData
;
2943 OB_OPEN_REASON OpenReason
;
2944 KPROCESSOR_MODE PreviousMode
;
2945 NTSTATUS Status
= STATUS_SUCCESS
, RealStatus
;
2946 BOOLEAN IsNewObject
;
2949 /* Get the Header */
2950 ObjectHeader
= OBJECT_TO_OBJECT_HEADER(Object
);
2952 /* Detect invalid insert */
2953 if (!(ObjectHeader
->Flags
& OB_FLAG_CREATE_INFO
))
2955 /* Display warning and break into debugger */
2956 DPRINT1("OB: Attempting to insert existing object %p\n", Object
);
2959 /* Allow debugger to continue */
2960 ObDereferenceObject(Object
);
2961 return STATUS_INVALID_PARAMETER
;
2964 /* Get the create and name info, as well as the object type */
2965 ObjectCreateInfo
= ObjectHeader
->ObjectCreateInfo
;
2966 ObjectNameInfo
= ObpReferenceNameInfo(ObjectHeader
);
2967 ObjectType
= ObjectHeader
->Type
;
2970 /* Check if this is an named object */
2971 if ((ObjectNameInfo
) && (ObjectNameInfo
->Name
.Buffer
))
2973 /* Get the object name */
2974 ObjectName
= &ObjectNameInfo
->Name
;
2979 ((ObjectPointerBias
== 0) &&
2980 (ObjectName
== NULL
) &&
2981 (ObjectType
->TypeInfo
.SecurityRequired
) &&
2982 (NewObject
== NULL
)));
2984 /* Check if the object is unnamed and also doesn't have security */
2985 PreviousMode
= KeGetPreviousMode();
2986 if (!(ObjectType
->TypeInfo
.SecurityRequired
) && !(ObjectName
))
2988 /* Assume failure */
2990 ObjectHeader
->ObjectCreateInfo
= NULL
;
2992 /* Create the handle */
2993 Status
= ObpCreateUnnamedHandle(Object
,
2995 ObjectPointerBias
+ 1,
2996 ObjectCreateInfo
->Attributes
,
3001 /* Free the create information */
3002 ObpFreeObjectCreateInformation(ObjectCreateInfo
);
3004 /* Release the object name information */
3005 ObpDereferenceNameInfo(ObjectNameInfo
);
3007 /* Remove the extra keep-alive reference */
3008 ObDereferenceObject(Object
);
3011 OBTRACE(OB_HANDLE_DEBUG
,
3012 "%s - returning Object with PC S: %lx %lx\n",
3014 ObjectHeader
->PointerCount
,
3019 /* Check if we didn't get an access state */
3022 /* Use our built-in access state */
3023 AccessState
= &LocalAccessState
;
3024 Status
= SeCreateAccessState(&LocalAccessState
,
3027 &ObjectType
->TypeInfo
.GenericMapping
);
3028 if (!NT_SUCCESS(Status
))
3031 ObpDereferenceNameInfo(ObjectNameInfo
);
3032 ObDereferenceObject(Object
);
3037 /* Save the security descriptor */
3038 AccessState
->SecurityDescriptor
= ObjectCreateInfo
->SecurityDescriptor
;
3040 /* Validate the access mask */
3041 Status
= ObpValidateAccessMask(AccessState
);
3042 if (!NT_SUCCESS(Status
))
3045 ObpDereferenceNameInfo(ObjectNameInfo
);
3046 ObDereferenceObject(Object
);
3050 /* Setup a lookup context */
3051 ObpInitializeLookupContext(&Context
);
3052 InsertObject
= Object
;
3053 OpenReason
= ObCreateHandle
;
3055 /* Check if the object is named */
3059 Status
= ObpLookupObjectName(ObjectCreateInfo
->RootDirectory
,
3061 ObjectCreateInfo
->Attributes
,
3063 (ObjectHeader
->Flags
& OB_FLAG_KERNEL_MODE
) ?
3064 KernelMode
: UserMode
,
3065 ObjectCreateInfo
->ParseContext
,
3066 ObjectCreateInfo
->SecurityQos
,
3072 /* Check if we found an object that doesn't match the one requested */
3073 if ((NT_SUCCESS(Status
)) && (InsertObject
) && (Object
!= InsertObject
))
3075 /* This means we're opening an object, not creating a new one */
3076 OpenReason
= ObOpenHandle
;
3078 /* Make sure the caller said it's OK to do this */
3079 if (ObjectCreateInfo
->Attributes
& OBJ_OPENIF
)
3081 /* He did, but did he want this type? */
3082 if (ObjectType
!= OBJECT_TO_OBJECT_HEADER(InsertObject
)->Type
)
3084 /* Wrong type, so fail */
3085 Status
= STATUS_OBJECT_TYPE_MISMATCH
;
3089 /* Right type, so warn */
3090 Status
= STATUS_OBJECT_NAME_EXISTS
;
3095 /* Check if this was a symbolic link */
3096 if (OBJECT_TO_OBJECT_HEADER(InsertObject
)->Type
==
3099 /* Dereference it */
3100 ObDereferenceObject(InsertObject
);
3103 /* Caller wanted to create a new object, fail */
3104 Status
= STATUS_OBJECT_NAME_COLLISION
;
3108 /* Check if anything until now failed */
3109 if (!NT_SUCCESS(Status
))
3111 /* Cleanup after lookup */
3112 ObpReleaseLookupContext(&Context
);
3114 /* Remove query reference that we added */
3115 ObpDereferenceNameInfo(ObjectNameInfo
);
3117 /* Dereference the object and delete the access state */
3118 ObDereferenceObject(Object
);
3119 if (AccessState
== &LocalAccessState
)
3121 /* We used a local one; delete it */
3122 SeDeleteAccessState(AccessState
);
3125 /* Return failure code */
3130 /* Check if this is a symbolic link */
3131 if (ObjectType
== ObSymbolicLinkType
)
3133 /* Create the internal name */
3134 ObpCreateSymbolicLinkName(Object
);
3139 /* Now check if this object is being created */
3140 if (InsertObject
== Object
)
3142 /* Check if it's named or forces security */
3143 if ((ObjectName
) || (ObjectType
->TypeInfo
.SecurityRequired
))
3145 /* Make sure it's inserted into an object directory */
3146 if ((ObjectNameInfo
) && (ObjectNameInfo
->Directory
))
3148 /* Get the current descriptor */
3149 ObGetObjectSecurity(ObjectNameInfo
->Directory
,
3155 Status
= ObAssignSecurity(AccessState
,
3160 /* Check if we captured one */
3161 if (ParentDescriptor
)
3163 /* We did, release it */
3164 ObReleaseObjectSecurity(ParentDescriptor
, SdAllocated
);
3166 else if (NT_SUCCESS(Status
))
3168 /* Other we didn't, but we were able to use the current SD */
3169 SeReleaseSecurityDescriptor(ObjectCreateInfo
->SecurityDescriptor
,
3170 ObjectCreateInfo
->ProbeMode
,
3173 /* Clear the current one */
3174 AccessState
->SecurityDescriptor
=
3175 ObjectCreateInfo
->SecurityDescriptor
= NULL
;
3179 /* Check if anything until now failed */
3180 if (!NT_SUCCESS(Status
))
3182 /* Check if the directory was added */
3183 if (Context
.DirectoryLocked
)
3185 /* Weird case where we need to do a manual delete */
3186 DPRINT1("Unhandled path\n");
3190 /* Cleanup the lookup */
3191 ObpReleaseLookupContext(&Context
);
3193 /* Remove query reference that we added */
3194 ObpDereferenceNameInfo(ObjectNameInfo
);
3196 /* Dereference the object and delete the access state */
3197 ObDereferenceObject(Object
);
3198 if (AccessState
== &LocalAccessState
)
3200 /* We used a local one; delete it */
3201 SeDeleteAccessState(AccessState
);
3204 /* Return failure code */
3210 /* Save the actual status until here */
3211 RealStatus
= Status
;
3213 /* Check if caller wants us to create a handle */
3214 ObjectHeader
->ObjectCreateInfo
= NULL
;
3217 /* Create the handle */
3218 Status
= ObpCreateHandle(OpenReason
,
3222 ObjectPointerBias
+ 1,
3223 ObjectCreateInfo
->Attributes
,
3228 if (!NT_SUCCESS(Status
))
3230 /* If the object had a name, backout everything */
3231 if (ObjectName
) ObpDeleteNameCheck(Object
);
3233 /* Return the status of the failure */
3235 RealStatus
= Status
;
3238 /* Remove a query reference */
3239 ObpDereferenceNameInfo(ObjectNameInfo
);
3241 /* Remove the extra keep-alive reference */
3242 ObDereferenceObject(Object
);
3246 /* Otherwise, lock the object */
3247 ObpAcquireObjectLock(ObjectHeader
);
3249 /* And charge quota for the process to make it appear as used */
3250 RealStatus
= ObpChargeQuotaForObject(ObjectHeader
,
3254 /* Release the lock */
3255 ObpReleaseObjectLock(ObjectHeader
);
3257 /* Check if we failed and dereference the object if so */
3258 if (!NT_SUCCESS(RealStatus
)) ObDereferenceObject(Object
);
3261 /* We can delete the Create Info now */
3262 ObpFreeObjectCreateInformation(ObjectCreateInfo
);
3264 /* Check if we created our own access state and delete it if so */
3265 if (AccessState
== &LocalAccessState
) SeDeleteAccessState(AccessState
);
3267 /* Return status code */
3268 OBTRACE(OB_HANDLE_DEBUG
,
3269 "%s - returning Object with PC RS/S: %lx %lx %lx\n",
3271 OBJECT_TO_OBJECT_HEADER(Object
)->PointerCount
,
3272 RealStatus
, Status
);
3277 * @name ObSetHandleAttributes
3278 * @implemented NT5.1
3280 * The ObSetHandleAttributes routine <FILLMEIN>
3285 * @param HandleFlags
3288 * @param PreviousMode
3291 * @return <FILLMEIN>.
3298 ObSetHandleAttributes(IN HANDLE Handle
,
3299 IN POBJECT_HANDLE_ATTRIBUTE_INFORMATION HandleFlags
,
3300 IN KPROCESSOR_MODE PreviousMode
)
3302 OBP_SET_HANDLE_ATTRIBUTES_CONTEXT SetHandleAttributesContext
;
3303 BOOLEAN Result
, AttachedToSystemProcess
= FALSE
;
3304 PHANDLE_TABLE HandleTable
;
3305 KAPC_STATE ApcState
;
3308 /* Check if this is a kernel handle */
3309 if (ObpIsKernelHandle(Handle
, PreviousMode
))
3311 /* Use the kernel table and convert the handle */
3312 HandleTable
= ObpKernelHandleTable
;
3313 Handle
= ObKernelHandleToHandle(Handle
);
3315 /* Check if we're not in the system process */
3316 if (PsGetCurrentProcess() != PsInitialSystemProcess
)
3318 /* Attach to the system process */
3319 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
3320 AttachedToSystemProcess
= TRUE
;
3325 /* Get the current process' handle table */
3326 HandleTable
= PsGetCurrentProcess()->ObjectTable
;
3329 /* Initialize the handle attribute context */
3330 SetHandleAttributesContext
.PreviousMode
= PreviousMode
;
3331 SetHandleAttributesContext
.Information
= *HandleFlags
;
3333 /* Invoke the ObpSetHandleAttributes callback */
3334 Result
= ExChangeHandle(HandleTable
,
3336 ObpSetHandleAttributes
,
3337 (ULONG_PTR
)&SetHandleAttributesContext
);
3339 /* Did we attach to the system process? */
3340 if (AttachedToSystemProcess
)
3342 /* Detach from it */
3343 KeUnstackDetachProcess(&ApcState
);
3346 /* Return the result as an NTSTATUS value */
3347 return Result
? STATUS_SUCCESS
: STATUS_ACCESS_DENIED
;
3351 * @name ObCloseHandle
3352 * @implemented NT5.1
3354 * The ObCloseHandle routine <FILLMEIN>
3362 * @return <FILLMEIN>.
3369 ObCloseHandle(IN HANDLE Handle
,
3370 IN KPROCESSOR_MODE AccessMode
)
3372 /* Call the internal API */
3373 return ObpCloseHandle(Handle
, AccessMode
);
3380 * The NtClose routine <FILLMEIN>
3385 * @return <FILLMEIN>.
3392 NtClose(IN HANDLE Handle
)
3394 /* Call the internal API */
3395 return ObpCloseHandle(Handle
, ExGetPreviousMode());
3400 NtDuplicateObject(IN HANDLE SourceProcessHandle
,
3401 IN HANDLE SourceHandle
,
3402 IN HANDLE TargetProcessHandle OPTIONAL
,
3403 OUT PHANDLE TargetHandle OPTIONAL
,
3404 IN ACCESS_MASK DesiredAccess
,
3405 IN ULONG HandleAttributes
,
3408 PEPROCESS SourceProcess
, TargetProcess
, Target
;
3410 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3412 OBTRACE(OB_HANDLE_DEBUG
,
3413 "%s - Duplicating handle: %p for %p into %p.\n",
3416 SourceProcessHandle
,
3417 TargetProcessHandle
);
3419 /* Check if we have a target handle */
3420 if ((TargetHandle
) && (PreviousMode
!= KernelMode
))
3425 /* Probe the handle and assume failure */
3426 ProbeForWriteHandle(TargetHandle
);
3427 *TargetHandle
= NULL
;
3429 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3431 /* Return the exception code */
3432 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3437 /* Now reference the input handle */
3438 Status
= ObReferenceObjectByHandle(SourceProcessHandle
,
3442 (PVOID
*)&SourceProcess
,
3444 if (!NT_SUCCESS(Status
)) return Status
;
3446 /* Check if got a target handle */
3447 if (TargetProcessHandle
)
3449 /* Now reference the output handle */
3450 Status
= ObReferenceObjectByHandle(TargetProcessHandle
,
3454 (PVOID
*)&TargetProcess
,
3456 if (NT_SUCCESS(Status
))
3458 /* Use this target process */
3459 Target
= TargetProcess
;
3463 /* No target process */
3469 /* No target process */
3470 Status
= STATUS_SUCCESS
;
3474 /* Call the internal routine */
3475 Status
= ObDuplicateObject(SourceProcess
,
3484 /* Check if the caller wanted the return handle */
3487 /* Protect the write to user mode */
3490 /* Write the new handle */
3491 *TargetHandle
= hTarget
;
3493 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3495 /* Otherwise, get the exception code */
3496 Status
= _SEH2_GetExceptionCode();
3501 /* Dereference the processes */
3502 OBTRACE(OB_HANDLE_DEBUG
,
3503 "%s - Duplicated handle: %p into %p S %lx\n",
3506 TargetProcessHandle
,
3508 if (Target
) ObDereferenceObject(Target
);
3509 ObDereferenceObject(SourceProcess
);
3515 ObIsKernelHandle(IN HANDLE Handle
)
3517 /* Use the inlined version. We know we are in kernel mode. */
3518 return ObpIsKernelHandle(Handle
, KernelMode
);