windowsautomated-testsbsod

Is there a way in windows to throw a BSOD on demand from python?


I am making a script to test some software that is always running and I want to test it's recovery from a BSOD. Is there a way to throw a bsod from python without calling an external script or executable like OSR's BANG!


Solution

  • Funny thing. There is an undocumented Windows kernel function that does just that.

    I'm assuming that this is intended behavior as the function has been there for a very long time.

    The following Python code will crash any Windows computer from usermode without any additional setup.

    from ctypes import windll
    from ctypes import c_int
    from ctypes import c_uint
    from ctypes import c_ulong
    from ctypes import POINTER
    from ctypes import byref
    
    nullptr = POINTER(c_int)()
    
    windll.ntdll.RtlAdjustPrivilege(
        c_uint(19),
        c_uint(1),
        c_uint(0),
        byref(c_int())
    )
    
    windll.ntdll.NtRaiseHardError(
        c_ulong(0xC000007B),
        c_ulong(0),
        nullptr,
        nullptr,
        c_uint(6),
        byref(c_uint())
    )
    

    Explanation:

    The reason this works is that the SE_SHUTDOWN_PRIVILEGE (ID 19) is first enabled for the current process. Without this, the following function may not work.

    The function NtRaiseHardError is then called with the error code 0xC000007B, which corresponds to STATUS_INVALID_IMAGE_FORMAT.

    Other error codes that work as well include STATUS_NO_MEMORY, STATUS_ILLEGAL_INSTRUCTION, STATUS_IN_PAGE_ERROR, STATUS_ASSERTION_FAILURE or STATUS_SYSTEM_PROCESS_TERMINATED. Their corresponding values can be found in Microsoft's NTSTATUS Values Documentation.

    The fifth parameter to this function (6) ensures that the system does not attempt to handle this error gracefully.