@@ -542,7 +542,12 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
542542{
543543 /* Privilege adjustment */
544544 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 ;
546551
547552 /* Reparse data buffer */
548553 const USHORT prefix_len = 4 ;
@@ -566,17 +571,21 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
566571
567572 /* Adjust privileges to allow rewriting directory entry as a
568573 junction point. */
569- if (!OpenProcessToken (GetCurrentProcess (), TOKEN_ADJUST_PRIVILEGES , & token ))
574+ if (!OpenProcessToken (GetCurrentProcess (),
575+ TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY , & token )) {
570576 goto cleanup ;
577+ }
571578
572- if (!LookupPrivilegeValue (NULL , SE_RESTORE_NAME , & tp .Privileges [0 ].Luid ))
579+ if (!LookupPrivilegeValue (NULL , SE_RESTORE_NAME , & tp .base . Privileges [0 ].Luid )) {
573580 goto cleanup ;
581+ }
574582
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 )) {
579587 goto cleanup ;
588+ }
580589
581590 if (GetFileAttributesW (src_path ) == INVALID_FILE_ATTRIBUTES )
582591 goto cleanup ;
@@ -657,8 +666,15 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
657666cleanup :
658667 ret = GetLastError ();
659668
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 );
662678 PyMem_RawFree (rdb );
663679
664680 if (ret != 0 )
0 commit comments