Privilege Context Switching Error

Description

Privilege Context Switching Error is a vulnerability that occurs when a product does not properly manage privileges while switching between different contexts that have different privileges or spheres of control. This weakness arises when applications transition between security domains, trust zones, or user contexts without correctly adjusting the active privilege level to match the target context. The result can be that operations intended to run with one set of permissions actually execute with the privileges of a different context, allowing unauthorized access to resources or functionality.

Risk

Improper privilege context switching creates significant security risks by allowing privilege leakage across security boundaries. When applications fail to properly manage context switches, users may inherit privileges from previous contexts, potentially gaining access to resources they should not be able to reach. In web browsers, this manifests as cross-domain vulnerabilities where scripts from untrusted sites can access data from trusted zones. In operating systems, this can allow processes to retain elevated privileges when transitioning to restricted contexts. Attackers who identify context switching errors can exploit them for privilege escalation, cross-site scripting across zones, or unauthorized access to protected resources.

Solution

Carefully manage privilege settings during all context transitions, ensuring explicit trust zone management. Implement clear privilege boundaries between different security contexts and verify that privilege levels are properly adjusted when crossing boundaries. Run code with the minimal required privileges and create isolated accounts for specific tasks to limit the impact of context switching errors. Apply the separation of privilege principle, requiring multiple conditions before granting access to sensitive resources. Design systems with explicit context switching functions that atomically update all privilege-related state. Test context transitions thoroughly, especially for edge cases like navigation history (back button) and callback execution across trust boundaries.

Common Consequences

ImpactDetails
Access ControlScope: Access Control

Users can assume another user's identity or privilege level in a separate context with different permissions. This enables unauthorized access to protected resources and potential exposure of other users' credentials or sensitive data. Context switching errors may also allow code from untrusted sources to execute with elevated privileges.

Example Code

Vulnerable Code (JavaScript/Web Context)

The following examples demonstrate privilege context switching vulnerabilities:

// Vulnerable: Web application with context switching errors
class VulnerableContextManager {

    constructor() {
        this.currentContext = 'untrusted';
        this.trustedDomains = ['secure.example.com', 'admin.example.com'];
    }

    handleNavigation(newUrl, navigationType) {
        const previousContext = this.currentContext;

        // Vulnerable: Back button navigation doesn't properly switch context
        if (navigationType === 'back') {
            // Context remains from the page being navigated FROM
            // not the page being navigated TO
            // User goes from trusted -> untrusted, but keeps trusted context
            this.loadPage(newUrl);
            // currentContext not updated!
        } else {
            this.updateContext(newUrl);
            this.loadPage(newUrl);
        }
    }

    executeCallback(callback, sourceContext) {
        // Vulnerable: Callback executes in current context, not source context
        // Callback registered in untrusted context executes after
        // user navigates to trusted context
        callback();  // Runs with trusted privileges!
    }
}
// Vulnerable: C process context switching without privilege management
#include <unistd.h>
#include <sys/types.h>

void vulnerable_context_switch(uid_t target_uid) {
    // Current process running as root

    // Vulnerable: Switching user context without managing all privileges
    setuid(target_uid);  // May fail silently on some systems

    // Process continues - did the switch succeed?
    // Other privilege aspects (groups, capabilities) may not be updated

    // If this is forking to execute external code, still may have issues
    execve("/user/provided/path", args, env);
}

void vulnerable_zone_transition(void) {
    // Process started in privileged zone

    // Vulnerable: Transitioning to restricted zone without clearing state
    chroot("/restricted/environment");
    chdir("/");

    // Still running as root!
    // File handles from privileged zone still open
    // Capabilities not dropped

    // Attacker can escape chroot and access privileged resources
}
// Vulnerable: Java application with security context issues
public class VulnerableSecurityContext {

    private SecurityContext currentContext;

    public void processRequest(Request request, Callback callback) {
        SecurityContext requestContext = determineContext(request);
        SecurityContext originalContext = currentContext;

        // Switch to request context
        currentContext = requestContext;

        try {
            // Process in request context
            processInContext(request);

            // Vulnerable: Callback might have been registered in different context
            // but executes with current elevated context
            if (callback != null) {
                callback.execute();  // Runs with requestContext privileges
            }
        } finally {
            // Vulnerable: If exception occurs before finally, context not restored
            currentContext = originalContext;
        }
    }

    public void loadThirdPartyCode(String url, SecurityZone zone) {
        // Vulnerable: Third-party code loads in wrong zone
        if (zone == SecurityZone.TRUSTED) {
            // User intended untrusted zone but code runs as trusted
            // due to URL parsing vulnerability
            executeInTrustedContext(loadCode(url));
        }
    }
}

Fixed Code (JavaScript/Web Context)

// Fixed: Proper security context management
public class SecureSecurityContext {

    private final ThreadLocal<SecurityContext> currentContext =
        new ThreadLocal<>();
    private final Map<Callback, SecurityContext> callbackContexts =
        new ConcurrentHashMap<>();

    public void processRequest(Request request, Callback callback) {
        SecurityContext requestContext = determineContext(request);
        SecurityContext originalContext = currentContext.get();

        // Validate context transition is allowed
        if (!isTransitionAllowed(originalContext, requestContext)) {
            throw new SecurityException("Invalid context transition");
        }

        currentContext.set(requestContext);

        try {
            processInContext(request);

            // Fixed: Execute callback in its registered context
            if (callback != null) {
                executeCallbackInOriginalContext(callback);
            }
        } finally {
            // Always restore original context
            currentContext.set(originalContext);
        }
    }

    public void registerCallback(Callback callback) {
        // Capture context at registration time
        callbackContexts.put(callback, currentContext.get());
    }

    private void executeCallbackInOriginalContext(Callback callback) {
        SecurityContext callbackContext = callbackContexts.get(callback);
        SecurityContext executionContext = currentContext.get();

        if (callbackContext == null) {
            throw new SecurityException("Callback has no registered context");
        }

        // Switch to callback's original context
        currentContext.set(callbackContext);
        try {
            callback.execute();
        } finally {
            currentContext.set(executionContext);
        }
    }
}
// Fixed: Proper C privilege context switching
#include <unistd.h>
#include <sys/types.h>
#include <grp.h>
#include <sys/prctl.h>

int secure_context_switch(uid_t target_uid, gid_t target_gid) {
    // Clear all supplementary groups first
    if (setgroups(0, NULL) != 0) {
        return -1;
    }

    // Drop group privilege first (must be done while still root)
    if (setgid(target_gid) != 0) {
        return -1;
    }

    // Verify group change
    if (getgid() != target_gid || getegid() != target_gid) {
        return -1;
    }

    // Drop user privilege
    if (setuid(target_uid) != 0) {
        return -1;
    }

    // Verify user change - CRITICAL
    if (getuid() != target_uid || geteuid() != target_uid) {
        return -1;
    }

    // Ensure we can't regain privileges
    if (setuid(0) != -1) {
        // If this succeeds, privilege drop failed!
        _exit(1);
    }

    return 0;
}

int secure_zone_transition(const char* restricted_path) {
    // Close all unnecessary file descriptors before transition
    close_all_fds_except(STDERR_FILENO);

    // Change to restricted root
    if (chroot(restricted_path) != 0) {
        return -1;
    }

    if (chdir("/") != 0) {
        return -1;
    }

    // NOW drop privileges
    if (secure_context_switch(UNPRIVILEGED_UID, UNPRIVILEGED_GID) != 0) {
        return -1;
    }

    // Verify we're in restricted environment
    // (additional checks based on security requirements)

    return 0;
}

The fix ensures proper context capture for callbacks, validates context transitions, verifies privilege drops succeeded, and maintains context isolation across security boundaries.


Exploited in the Wild

Browser Cross-Domain Vulnerabilities (Multiple Browsers, Historical)

Web browsers have experienced numerous privilege context switching vulnerabilities where navigation actions like the "back" button caused scripts to execute with privileges from the wrong security zone. These vulnerabilities allowed malicious websites to access data from trusted zones or local files.

Zone Transition Exploits in Windows (Windows Systems, Historical)

Windows Internet Security Zones have been exploited through context switching errors where content loaded from untrusted zones could execute with Local Machine zone privileges. Attackers used these vulnerabilities to escape browser sandboxes and execute arbitrary code.

Container Escape Through Context Switching (Container Environments, Ongoing)

Container and sandbox technologies have been vulnerable to context switching errors where processes can retain capabilities or file handles from privileged contexts after transitioning to restricted containers, enabling container escape.


Tools to Test/Exploit

  • BurpSuite — Web security testing tool for identifying context switching vulnerabilities in web applications.

  • Browser Security Handbook — Reference for understanding browser security zone implementations and testing.

  • Container Security Scanner — Tools for identifying privilege context issues in containerized environments.


CVE Examples

  • CVE-2002-1688 — Web browser cross-domain vulnerability triggered by "back" button navigation.

  • CVE-2003-1026 — Similar browser cross-domain vulnerability in navigation handling.

  • CVE-2002-1770 — Third-party code executing in unsafe browser zone due to context error.

  • CVE-2005-2263 — Callback execution in changed security context after zone transition.


References

  1. MITRE Corporation. "CWE-270: Privilege Context Switching Error." Common Weakness Enumeration. https://cwe.mitre.org/data/definitions/270.html

  2. OWASP Foundation. "Broken Access Control." OWASP Top 10. https://owasp.org/Top10/A01_2021-Broken_Access_Control/

  3. Microsoft. "Security Zones in Internet Explorer." https://docs.microsoft.com/en-us/troubleshoot/browsers/security-zones