It's possible from .Net managed code to cause an arbitrary BSOD? - c#

I wonder whether from .Net managed code, or maybe p/invoking the needed NT dll, if I could generate a BSOD (Blue Screen Of Death) with specific bugcheck-code reason.
I know this is possible from a kernel-mode driver by calling KeBugCheck or KeBugCheckEx methods, but I think there is no way to call those methods from user-mode applications.
Someone could clarify me things, and bring an alternative way (if exists) for managed code?.

I had some code that did exactly that
here we go:
you might just need ntdll.dll but I used it without installing anything...
though the bug check codes don't seem to be the normal types
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
namespace bsod
{
class Program
{
private static uint STATUS_ASSERTION_FAILURE = 0xC0000420;
// private static uint KMODE_EXEPTION_NOT_HANDLED=0x0000008E;
static void Main(string[] args) {
while (Console.ReadKey(true).Key == ConsoleKey.W)
{
crash();
}
}
static void crash()
{
bool previousValue=false;
// Console.WriteLine("Adjusting privileges");
RtlAdjustPrivilege(19, true, false, out previousValue);
// Console.WriteLine("Triggering BSOD");
uint oul = 0;
IntPtr sptr = Marshal.StringToHGlobalAnsi("");
NtRaiseHardError(STATUS_ASSERTION_FAILURE, 0, 0, IntPtr.Zero, 6, out oul);
}
[DllImport("ntdll.dll")]
private static extern uint RtlAdjustPrivilege(
int Privilege,
bool bEnablePrivilege,
bool IsThreadPrivilege,
out bool PreviousValue
);
[DllImport("ntdll.dll")]
private static extern uint NtRaiseHardError(
uint ErrorStatus,
uint NumberOfParameters,
uint UnicodeStringParameterMask,
IntPtr Parameters,
uint ValidResponseOption,
out uint Response
);
}
}
let me clarify that this can be very dangerous, as you are one step away from an infinite loop constantly crashing your computer...

You can kill the csrss process, pretty simple:
System.Diagnostics.Process.GetProcessesByName("csrss").Single().Kill();
Even if that requires administrator rights

I can't say for certain that the kernel does not provide some means of invoking KeBugCheck with arbitrary arguments from user mode, even if just for highly privileged processes, but I very much hope none does and I certainly sympathise with anyone who wonders why on earth you would want something like this to exist let alone to use it.
Of course, even if the kernel doesn't already expose it for calling from user mode, it is readily available in kernel mode, i.e., to be called by drivers. Even there, however, drivers are strongly discouraged from resorting to it in any code that's ever released. Though a driver could expose a user-mode interface, e.g., through Device I/O Control, for calling KeBugCheck on behalf of a user-mode client, even an unprivileged one, doing so would be incredibly irresponsible of a driver writer (except, perhaps, for private testing).
As for CSRSS, some of you may want to know as background (and perhaps know already) that the architecture has long allowed that CSRSS needn't be critical (in the sense that killing it kills Windows) and also that it needn't be the only one. There is an undocumented function RtlSetProcessIsCritical which programs such as CSRSS call to register themselves as being so vital that when the kernel sees them exit then the kernel should raise either of two particular bug checks.

Related

Detecting that the user is away from the PC with .NET

I have a desktop application in which I would like to know two things:
Is the user currently on the PC (more specifically, is he giving any input to the PC), so I can change his state to "away" if needed; and
Is the screensaver running right now, so I can perform more CPU intensive work during that time.
I'm using C#/.NET. How would you suggest to tackle these two tasks?
NOTE: WIN32 invocation will be just as good, as well as any unmanaged code solution.
http://dataerror.blogspot.com/2005/02/detect-windows-idle-time.html
^ Detect Windows Idle Time. :)
The enabler for this feature is the GetLastInputInfo() Win32 API and the LASTINPUTINFO Win32 structure.
Here is the code to detect if a screen saver is running. See this for more details
const int SPI_GETSCREENSAVERRUNNING = 114;
[DllImport( "user32.dll", CharSet = CharSet.Auto )]
private static extern bool SystemParametersInfo(
int uAction, int uParam, ref bool lpvParam,
int flags );
// Returns TRUE if the screen saver is actually running
public static bool GetScreenSaverRunning( )
{
bool isRunning = false;
SystemParametersInfo( SPI_GETSCREENSAVERRUNNING, 0,
ref isRunning, 0 );
return isRunning;
}
Rather than figuring out when to run more intensive work... Consider doing your "intensive work" as early as you can, but at a lower thread priority.
I don't think your questions have an answer in pure C#, unless you poll the mouse position and observe movements... Or something like that.
You could use a global keyboard/mouse hook and just reset your "counter" to 0 when you receive an event from either. When your counter reaches the idle time that you're looking for, perform your background actions.
There is some code here that allows you to easily do the hooking in .NET: http://www.codeproject.com/KB/cs/globalhook.aspx

Getting System Idle Time with Qt

I'm new to Qt as of a few weeks ago. I'm trying to rewrite a C# application with C++ and have a good portion of it figure now. My current challenge is finding a way to detect the system idle time.
With my C# application, I stole code from somewhere that looks like this:
public struct LastInputInfo
{
public uint cbSize;
public uint dwTime;
}
[DllImport("User32.dll")]
private static extern bool GetLastInputInfo(ref LastInputInfo plii);
/// <summary>
/// Returns the number of milliseconds since the last user input (or mouse movement)
/// </summary>
public static uint GetIdleTime()
{
LastInputInfo lastInput = new LastInputInfo();
lastInput.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInput);
GetLastInputInfo(ref lastInput);
return ((uint)Environment.TickCount - lastInput.dwTime);
}
I haven't yet learned how to reference Windows API functions through DLL Imports or whatever the C++ equivalent is. Honestly, I would prefer to avoid them if possible. This application is moving to Mac OSX and possibly Linux in the future as well.
Is there a Qt specific, platform-independent way to get the system idle-time? Meaning the user has not touched the mouse or any keys for X amount of time.
Thanks you in advance for any help you can provide.
Since no one seems to know, and I'm not sure that this is even possible, I decided to setup a low interval polling timer to check the current X, Y of the mouse. I know it's not a perfect solution, but...
It will work cross platform without me doing platform specific things (like DLL imports, yuck)
It serves the purpose I need it for: determining if someone is actively using the system or not
Yes, yes, I know there could be situations where someone may not have a mouse or whatever. I'm calling that a "low activity state" for now. Good enough. Here is the code:
mainwindow.h - Class declaration
private:
QPoint mouseLastPos;
QTimer *mouseTimer;
quint32 mouseIdleSeconds;
mainwindow.cpp - Constructor method
//Init
mouseTimer = new QTimer();
mouseLastPos = QCursor::pos();
mouseIdleSeconds = 0;
//Connect and Start
connect(mouseTimer, SIGNAL(timeout()), this, SLOT(mouseTimerTick()));
mouseTimer->start(1000);
mainwindow.cpp - Class body
void MainWindow::mouseTimerTick()
{
QPoint point = QCursor::pos();
if(point != mouseLastPos)
mouseIdleSeconds = 0;
else
mouseIdleSeconds++;
mouseLastPos = point;
//Here you could determine whatever to do
//with the total number of idle seconds.
}

.NET Minimize to Tray AND Minimize required resources

I have a WinForms application (I'm using VB) that can be minimized to the system tray. I used the "hackish" methods described in multiple posts utilizing a NotifyIcon and playing with the Form_Resize event.
This all works fine aesthetically, but the resources and memory used are unaffected. I want to be able to minimize resources when minimizing to system tray, just like Visual Studio does. If you are coding in Visual Studio, the memory usage can creep up (depending on project size) to above 500 MB, but when minimizing Visual Studio to the taskbar, the memory drastically decreases to (what I'm assuming) is the minimal amount.
Does anyone have any clue as to how to accomplish this?
Here's a short description of the application, if anyone finds it relevant: I have a windows form with a ListView that contains Work Orders for my IT department. The application has a "listener" that notifies when a new Work order is submitted. So, when the application is running in the system tray, all I really do is compare the count of items in the ListView to a count of rows in a SQL table every couple of minutes.
EDIT: To be more specific, a windows form intrinsically has threads and resources being used by means of the controls, when the form is invisible (in the system tray) these resources are still being used. What can I do to minimize these resources, short of killing all the controls and redrawing them when the form is restored.
Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap.
public static void MinimizeMemory()
{
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
SetProcessWorkingSetSize(
Process.GetCurrentProcess().Handle,
(UIntPtr)0xFFFFFFFF,
(UIntPtr)0xFFFFFFFF);
IntPtr heap = GetProcessHeap();
if (HeapLock(heap))
{
try
{
if (HeapCompact(heap, 0) == 0)
{
// error condition ignored
}
}
finally
{
HeapUnlock(heap);
}
}
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetProcessWorkingSetSize(
IntPtr process,
UIntPtr minimumWorkingSetSize,
UIntPtr maximumWorkingSetSize);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetProcessHeap();
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool HeapLock(IntPtr heap);
[DllImport("kernel32.dll")]
internal static extern uint HeapCompact(IntPtr heap, uint flags);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool HeapUnlock(IntPtr heap);
You're probably looking for this function call: SetProcessWorkingSetSize
If you execute the API call SetProcessWorkingSetSize with -1 as an argument, then Windows will trim the working set immediately.
However, if most of the memory is still being held by resources you haven't released minimizing the working set will do nothing. This combined with the suggestion of forcing Garbage Collection might be your best bet.
From your application description, you might want to also verify how much memory the ListView is consuming as well as the database access objects. I'm also not clear on how you're making those monitoring database calls. You might want to isolate that into a separate object and avoid touching any of the forms while minimized, otherwise the program will be forced to keep the controls loaded and accessible. You could start a separate thread for monitoring, and pass the ListView.Count as a parameter.
Some sources:
.NET Applications and the Working Set
How much memory does my .Net Application use?
To clean up unused memory, use GC.Collect()... though you should read up on why to do it and why its usually a bad idea to use it often.
If you mean other resources, you will need to be more specific.
While this is in C#, look at the source code, it will solve any issues you have:
http://www.codeproject.com/KB/cs/NotifyIconExample.aspx

How do I shutdown the computer?

How to shutdown my computer using C#?
An easy way: Use Process.Start to run shutdown.exe.
shutdown /s /t 0
Programmatic way: P/Invoke a call to ExitWindowsEx
This would be the P/Invoke signature:
[DllImport("aygshell.dll", SetLastError="true")]
private static extern bool ExitWindowsEx(uint dwFlags, uint dwReserved);
Under all circumstances, the user running the code will need shutdown system privileges (normally not a problem, but an important point to remember).
Different methods:
A. System.Diagnostics.Process.Start("Shutdown", "-s -t 10");
B. Windows Management Instrumentation (WMI)
http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=36953
http://www.dreamincode.net/forums/showtopic33948.htm
C. System.Runtime.InteropServices Pinvoke
http://bytes.com/groups/net-c/251367-shutdown-my-computer-using-c
D. System Management
http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html
After I submit, I have seen so many others also have posted...
WindowsController is a c# wrapper class around ExitWindowsEx.
Sometimes you need to restart or
shutdown the operating system from
your applications (for instance, after
the installation of a program). The
.NET framework offers you an indirect
way to restart the computer through
the Windows Management Instrumentation
(WMI) classes in the System.Management
namespace, however, there seem to be
some problems in their implementation.
That's why we created the
WindowsController class that
implements some API functions to
restart and shutdown Windows. It
supports all the ExitWindowsEx modes
and it can also hibernate and suspend
the system.
This class is available in C# and
VB.NET version. It can be compiled to
a .NET module or to a library to be
used from other .NET languages. Since
it relies on the Windows API, it will
not work on Linux or FreeBSD.
(mentalis.org)
Use a variation of the "user logoff" code shown here.
That code uses the ExitWindowsEx API call.
At a guess (untested):
Process.Start("shutdown", "-s -t 0");
The hard way, works on laptops perfectly, although it takes some time:
Spawn a couple endless loops in more threads than cpu cores.
Wait for overheat which will automatically shutdown a computer.
:)
You could also use InitiateSystemShutdown
http://www.pinvoke.net/default.aspx/advapi32.initiatesystemshutdown
using System;
using System.Runtime.InteropServices;
using System.Text;
public class Program
{
[DllImport( "advapi32.dll" ) ]
public static extern bool InitiateSystemShutdown( string MachineName , string Message , uint Timeout , bool AppsClosed , bool Restart );
[DllImport( "kernel32.dll" ) ]
public static extern uint GetLastError();
[DllImport( "kernel32.dll" ) ]
public static extern uint FormatMessage( uint Flags , IntPtr Source , uint MessageID , uint LanguageID , StringBuilder Buffer , uint Size , IntPtr Args );
public static void Main()
{
InitiateSystemShutdown(System.Environment.MachineName, "hello", 0, false, false);
//InitiateSystemShutdown("localhost", "hello", 0, false, false);
}
}

Prevent Pocket PC device from Shutting down application on power off

How can I prevent the pocket PC device from shutting down from my application when the power button pressed? I am using C#.
You could use the Microsoft.WindowsCE.Form.MessageWindows class to intercept the Power Button event. This solution will not be portable, as the hardware key will be different in different machines.
I recommend however that you don't disable power down completely. Have a look at my answer in another question here. You could also use openetcf to easily create power down events handlers and register wake up events. You should implement the application logic based on what you are trying to achieve, for instance wake up every one minute to run a process.
You can try changing the power requirements for the device "BLK1:", which is the blacklight device. Be aware that the behavior may not be the same on all devices and version of the OS or Vendor specific Extensions.
To do this, you can write something like :
[DllImport("coredll")]
private extern static IntPtr SetPowerRequirement(string pvDevice, int deviceState,
int deviceFlags, IntPtr pvSystemState, int stateFlags);
[DllImport("coredll")]
private extern static int ReleasePowerRequirement(IntPtr handle);
and call it this way :
IntPtr handle = SetPowerRequirement("BLK1:", 0 /* D0, Full On */, 1, IntPtr.Zero, 0);
// Do something that requires the device to stay on ...
ReleasePowerRequirement(handle);
But this is generally not a good practice, leaving a device with the backlight on for extended periods might reduce dramatically its autonomy.

Categories