tags:

views:

319

answers:

3

How do I detect programmatically in which ring (-1, 0, 1, 2, 3) I am running?

+1  A: 

Unless you're a device driver, you'll always be running in Ring 3 (for systems that have "rings", per se).

John Saunders
Is that so? What about deamons and programs running as root?
Andrew J. Brehm
What if I am a device driver of an operating system running a hosted hypervisor? Wouldn't I be running in ring -1 together with the host system and the hypervisor?
Andrew J. Brehm
deamons are user mode programs running under another account. root is another account too. 'real' drivers run in kernel mode (mostly ring 0 because ring1 + ring2 are rarely used today.
Christopher
@Andrew: rude, rude. Yes, that's so.
John Saunders
+8  A: 

The easiest way is, to just run the (x86) command and catch the corresponding error.

E.g. (SEH, Windows, kernel mode)

bool ring_lower_0 = false;
__try
{
    __asm { <cmd> };
    ring_lower_0 = true;
}
__except( GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION )
{
    ring_lower_0 = false;
}

Notes:

cmd, is an assembler command. See the Intel Architecture Reference Manuals for a list of commands and their respective Ring levels.

Linux has a slightly different concept.

But remember that VMs residing on a lower level may mask the result by emulating the call.

(NB: The Job of the VM is to translate the invalid instruction into an meaningful call)


If you really want to check if your a virtualized and want to stop execution because of this, you should read what has been written about 'Red pill'.

Christopher
Thanks. That's a very good solution. I can work from here. Mask the result: I know. I just needed some point to begin.
Andrew J. Brehm
+2  A: 

Normally i would write that you should read about "protected mode programming". There is an article about how to intertact with ring 0 using windows XP SP2. Note that it will change for others windows versions and for sure others operational systems.

http://www.codeproject.com/KB/threads/MinimalisticRingZero.aspx

If you just want to detect if you are running inside of a virtual machine, to avoid that people debug your application, for example, you can check here:

http://www.codeproject.com/KB/system/VmDetect.aspx

VP