@@ -542,7 +542,12 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
542
542
{
543
543
/* Privilege adjustment */
544
544
HANDLE token = NULL ;
545
- TOKEN_PRIVILEGES tp ;
545
+ struct {
546
+ TOKEN_PRIVILEGES base ;
547
+ /* overallocate by a few array elements */
548
+ LUID_AND_ATTRIBUTES privs [4 ];
549
+ } tp , previousTp ;
550
+ int previousTpSize = 0 ;
546
551
547
552
/* Reparse data buffer */
548
553
const USHORT prefix_len = 4 ;
@@ -566,17 +571,21 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
566
571
567
572
/* Adjust privileges to allow rewriting directory entry as a
568
573
junction point. */
569
- if (!OpenProcessToken (GetCurrentProcess (), TOKEN_ADJUST_PRIVILEGES , & token ))
574
+ if (!OpenProcessToken (GetCurrentProcess (),
575
+ TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY , & token )) {
570
576
goto cleanup ;
577
+ }
571
578
572
- if (!LookupPrivilegeValue (NULL , SE_RESTORE_NAME , & tp .Privileges [0 ].Luid ))
579
+ if (!LookupPrivilegeValue (NULL , SE_RESTORE_NAME , & tp .base . Privileges [0 ].Luid )) {
573
580
goto cleanup ;
581
+ }
574
582
575
- tp .PrivilegeCount = 1 ;
576
- tp .Privileges [0 ].Attributes = SE_PRIVILEGE_ENABLED ;
577
- if (!AdjustTokenPrivileges (token , FALSE, & tp , sizeof (TOKEN_PRIVILEGES ),
578
- NULL , NULL ))
583
+ tp .base . PrivilegeCount = 1 ;
584
+ tp .base . Privileges [0 ].Attributes = SE_PRIVILEGE_ENABLED ;
585
+ if (!AdjustTokenPrivileges (token , FALSE, & tp . base , sizeof (previousTp ),
586
+ & previousTp . base , & previousTpSize )) {
579
587
goto cleanup ;
588
+ }
580
589
581
590
if (GetFileAttributesW (src_path ) == INVALID_FILE_ATTRIBUTES )
582
591
goto cleanup ;
@@ -657,8 +666,15 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
657
666
cleanup :
658
667
ret = GetLastError ();
659
668
660
- CloseHandle (token );
661
- CloseHandle (junction );
669
+ if (previousTpSize ) {
670
+ AdjustTokenPrivileges (token , FALSE, & previousTp .base , previousTpSize ,
671
+ NULL , NULL );
672
+ }
673
+
674
+ if (token != NULL )
675
+ CloseHandle (token );
676
+ if (junction != NULL )
677
+ CloseHandle (junction );
662
678
PyMem_RawFree (rdb );
663
679
664
680
if (ret != 0 )
0 commit comments