Skip to content

Commit f801d85

Browse files
zoobaaisk
authored andcommitted
pythongh-114096: Restore privileges in _winapi.CreateJunction after creating the junction (pythonGH-114089)
This avoids impact on later parts of the application which may be able to do things they otherwise shouldn't.
1 parent 7b7301e commit f801d85

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Process privileges that are activated for creating directory junctions are
2+
now restored afterwards, avoiding behaviour changes in other parts of the
3+
program.

Modules/_winapi.c

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,12 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
532532
{
533533
/* Privilege adjustment */
534534
HANDLE token = NULL;
535-
TOKEN_PRIVILEGES tp;
535+
struct {
536+
TOKEN_PRIVILEGES base;
537+
/* overallocate by a few array elements */
538+
LUID_AND_ATTRIBUTES privs[4];
539+
} tp, previousTp;
540+
int previousTpSize = 0;
536541

537542
/* Reparse data buffer */
538543
const USHORT prefix_len = 4;
@@ -556,17 +561,21 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
556561

557562
/* Adjust privileges to allow rewriting directory entry as a
558563
junction point. */
559-
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
564+
if (!OpenProcessToken(GetCurrentProcess(),
565+
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
560566
goto cleanup;
567+
}
561568

562-
if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.Privileges[0].Luid))
569+
if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.base.Privileges[0].Luid)) {
563570
goto cleanup;
571+
}
564572

565-
tp.PrivilegeCount = 1;
566-
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
567-
if (!AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
568-
NULL, NULL))
573+
tp.base.PrivilegeCount = 1;
574+
tp.base.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
575+
if (!AdjustTokenPrivileges(token, FALSE, &tp.base, sizeof(previousTp),
576+
&previousTp.base, &previousTpSize)) {
569577
goto cleanup;
578+
}
570579

571580
if (GetFileAttributesW(src_path) == INVALID_FILE_ATTRIBUTES)
572581
goto cleanup;
@@ -647,6 +656,11 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
647656
cleanup:
648657
ret = GetLastError();
649658

659+
if (previousTpSize) {
660+
AdjustTokenPrivileges(token, FALSE, &previousTp.base, previousTpSize,
661+
NULL, NULL);
662+
}
663+
650664
if (token != NULL)
651665
CloseHandle(token);
652666
if (junction != NULL)

0 commit comments

Comments
 (0)