C++ - writing directly to memory(Kernel) - c++

I have asked pretty much the same thing before, but my post got deleted for some reason.
Anyway, I'm trying to use C++ and write a program that allows me to access directly to the memory and write stuff to it. I heard I need to do something with the kernel as that is a "bridge" that connects the OS and application (I think). Is there anyway I can download some sdk for the kernel?
I've said this in my previous post (which got deleted after some time) that the reason to this is because I want to try and crash windows 7 as my professor at university asked me to. (so please don't ask me stuff like "why do you want to crash windows?" or something along those lines...)
Any help will be greatly appreciated.

If you're interesting in working with the kernel, you're likely looking for the Windows Driver Kit, found here:
http://msdn.microsoft.com/en-us/windows/hardware/gg487428
It has a variety of lower-level tools and headers to help you write drivers and other kernel-mode code.
Typical programs obviously don't have carte blanche access to memory, while drivers have more control (although I would guess they use the system's memory management as well, not entirely sure). You'll find more information in the WDK.

Write a driver, make it crash. Of course, in only very specific circumstances will this actually make Windows 7 crash (because, unlike the public opinion, it wasn't written by total idiots).

You can use the RtlSetProcessIsCritical function in order to flag that your process is critical for system operations.
If your process is terminated (for example if your application calls ExitProcess) a bluescreen will appear. In order to use this function you need to enable the SE_DEBUG_NAME privilege.

Related

Is it possible to directly run C++ at assembly level?

Recently I have been learning how to program in C++, and was wandering, if compiler languages are translated to machine code is it possible to just simply run the code as if it was an assembly code? Or in another example I load just the compiled code onto a formatted flash drive and nothing else and plug up that flash drive into a computer with no OS on it what so ever, and boot from the flash drive to make the computer run the compiled code, and nothing else. Is something like this even possible? Is the language not supported directly by the processor or is some sort of interpreter/execution environment for the language needed to run the program?
Sorry if what im asking is a bit abstract, tbh I don't know exactly how to explain it beyond providing examples.
Almost.
You will probably need some initialization before you can hand execution over to compiled C++. For example you would maybe need to initialize the stack pointer and other low level initialization that can't be done in C++.
After that you should be aware that there are some initialization that needs to be done before main is being run, but that could normally be done in C++, especially if you want a reasonable set of the features of the language (memory allocation, exception handling etc) available.
You should also be aware that much of the functionality that are taken for granted are normally handled by the operating system. Without an OS the executable would have to have libraries that handles that functionality if needed (like for example stream output functionality, file system etc).

How to Prevent I/O Access in C++ or Native Compiled Code

I know this may be impossible but I really hope there's a way to pull it off. Please tell me if there's any way.
I want to write a sandbox application in C++ and allow other developers to write native plugins that can be loaded right into the application on the fly. I'd probably want to do this via DLLs on Windows, but I also want to support Linux and hopefully Mac.
My issue is that I want to be able to prevent the plugins from doing I/O access on their own. I want to require them to use my wrapped routines so that I can ensure none of the plugins write malicious code that starts harming the user's files on disk or doing things undesireable on the network.
My best guess on how to pull off something like this would be to include a compiler with the application and require the source code for the plugins to be distributed and compiled right on the end-user platform. Then I'd need an code scanner that could search the plugin uncompiled code for signatures that would show up in I/O operations for hard disk or network or other storage media.
My understanding is that the STD libaries like fstream wrap platform-specific functions so I would think that simply scanning all the code that will be compiled for platform-specific functions would let me accomplish the task. Because ultimately, any C native code can't do any I/O unless it talks to the OS using one of the OS's provided methods, right??
If my line of thinking is correct on this, does anyone have a book or resource recommendation on where I could find the nuts and bolts of this stuff for Windows, Linux, and Mac?
If my line of thinking is incorrect and its impossible for me to really prevent native code (compiled or uncompiled) from doing I/O operations on its own, please tell me so I don't create an application that I think is secure but really isn't.
In an absolutely ideal world, I don't want to require the plugins to distribute uncompiled code. I'd like to allow the developers to compile and keep their code to themselves. Perhaps I could scan the binaries for signatures that pertain to I/O access????
Sandboxing a program executing code is certainly harder than merely scanning the code for specific accesses! For example, the program could synthesize assembler statements doing system calls.
The original approach on UNIXes is to chroot() the program but I think there are problems with that approach, too. Another approach is a secured environment like selinux, possible combined with chroot(). The modern approach used to do things like that seems to run the program in a virtual machine: upon start of the program fire up a suitable snapshot of a VM. Upon termination just rewind to tbe snaphot. That merely requires that the allowed accesses are somehow channeled somewhere.
Even a VM doesn't block I/O. It can block network traffic very easily though.
If you want to make sure the plugin doesn't do I/O you can scan it's DLL for all it's import functions and run the function list against a blacklist of I/O functions.
Windows has the dumpbin util and Linux has nm. Both can be run via a system() function call and the output of the tools be directed to files.
Of course, you can write your own analyzer but it's much harder.
User code can't do I/O on it's own. Only the kernel. If youre worried about the plugin gaining ring0/kernel privileges than you need to scan the ASM of the DLL for I/O instructions.

How to change a value in memory space of another process

If you could help me with this dilemma I have. Now, I know C \ C++, I know asm, I know about dll injection, I know about virtual memory addressing, but I just can't figure out how
software like CheatEngine, and others, manage to change a variable's value in another process.
For those who don't know, 3rd party cheat engine tools can scan for values in the memory space of a program and identify the location of a variable with a given value and change it.
My question is, how do they do it?
Given an address, if I were to write C code, how could I change the value at that address belonging to another process without getting an invalid addressing error?
Thanks.
I'm fairly certain those programs are pretending to be debuggers. On Windows, I would start with DebugActiveProcess() and go from there.
Oh, and the very useful looking ReadProcessMemory() function (and WriteProcessMemory()).
On unix: ptrace()
You can't do this with Standard C or C++ - you have to use operating system specific features. So you need to tell us which OS you are interested in.
You may also be interested in Detours:
Software packaged for detouring Win32 and application APIs.

How do I program an offline form of the crucial memory scanner

I like the memory scanner you can get from crucial (http://www.crucial.com/systemscanner/index.aspx) however it only works with an online computer.
I would like to be able to do as much as possible of what it does, but off-line.
I would like to produce sufficient info to be able to take this info to another online computer and use that to order a memory upgrade.
I would like to program this making minimum assumptions about what is on the target computer.
My language of choice would be C++.
(C# is my current favorite language but using this would require the .Net environment which is an assumption too far for my liking.)
WMI (in the root\cimv2 namespace) has the Win32_MemoryArray, Win32_MemoryDevice, Win32_MemoryDeviceArray, Win32_PhysicalMemory and Win32_PhysicalMemoryArray classes (and a couple of others). These might help.

Super Robust as chrome c++ and portable - tips - help - comments [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
We are producing a portable code (win+macOs) and we are looking at how to make the code more rubust as it crashes every so often... (overflows or bad initializations usually) :-(
I was reading that Google Chrome uses a process for every tab so if something goes wrong then the program does not crash compleatelly, only that tab. I think that is quite neat, so i might give it a go!
So i was wondering if someone has some tips, help, reading list, comment, or something that can help me build more rubust c++ code (portable is always better).
In the same topic i was also wondering if there is a portable library for processes (like boost)?
Well many Thanks.
I've developed on numerous multi-platform C++ apps (the largest being 1.5M lines of code and running on 7 platforms -- AIX, HP-UX PA-RISC, HP-UX Itanium, Solaris, Linux, Windows, OS X). You actually have two entirely different issues in your post.
Instability. Your code is not stable. Fix it.
Use unit tests to find logic problems before they kill you.
Use debuggers to find out what's causing the crashes if it's not obvious.
Use boost and similar libraries. In particular, the pointer types will help you avoid memory leaks.
Cross-platform coding.
Again, use libraries that are designed for this when possible. Particularly for any GUI bits.
Use standards (e.g. ANSI vs gcc/MSVC, POSIX threads vs Unix-specific thread models, etc) as much as possible, even if it requires a bit more work. Minimizing your platform specific code means less overall work, and fewer APIs to learn.
Isolate, isolate, isolate. Avoid in-line #ifdefs for different platforms as much as possible. Instead, stick platform specific code into its own header/source/class and use your build system and #includes to get the right code. This helps keep the code clean and readable.
Use the C99 integer types if at all possible instead of "long", "int", "short", etc -- otherwise it will bite you when you move from a 32-bit platform to a 64-bit one and longs suddenly change from 4 bytes to 8 bytes. And if that's ever written to the network/disk/etc then you'll run into incompatibility between platforms.
Personally, I'd stabilize the code first (without adding any more features) and then deal with the cross-platform issues, but that's up to you. Note that Visual Studio has an excellent debugger (the code base mentioned above was ported to Windows just for that reason).
The Chrome answer is more about failure mitigation and not about code quality. Doing what Chrome is doing is admitting defeat.
Better QA that is more than just programmer testing their own work.
Unit testing
Regression testing
Read up on best practices that other
companies use.
To be blunt, if your software is crashing often due to overflows and bad initializations, then you have a very basic programming quality problem that isn't going to be easily fixed. That sounds a hash and mean, that isn't my intent. My point is that the problem with the bad code has to be your primary concern (which I'm sure it is). Things like Chrome or liberal use to exception handling to catch program flaw are only distracting you from the real problem.
You don't mention what the target project is; having a process per-tab does not necessarily mean more "robust" code at all. You should aim to write solid code with tests regardless of portability - just read about writing good C++ code :)
As for the portability section, make sure you are testing on both platforms from day one and ensure that no new code is written until platform-specific problems are solved.
You really, really don't want to do what Chrome is doing, it requires a process manager which is probably WAY overkill for what you want.
You should investigate using smart pointers from Boost or another tool that will provide reference counting or garbage collection for C++.
Alternatively, if you are frequently crashing you might want to perhaps consider writing non-performance critical parts of your application in a scripting language that has C++ bindings.
Scott Meyers' Effective C++ and More Effective C++ are very good, and fun to read.
Steve McConnell's Code Complete is a favorite of many, including Jeff Atwood.
The Boost libraries are probably an excellent choice. One project where I work uses them. I've only used WIN32 threading myself.
I agree with Torlack.
Bad initialization or overflows are signs of poor quality code.
Google did it that way because sometimes, there was no way to control the code that was executed in a page (because of faulty plugins, etc.). So if you're using low quality plug ins (it happens), perhaps the Google solution will be good for you.
But a program without plugins that crashes often is just badly written, or very very complex, or very old (and missing a lot of maintenance time). You must stop the development, and investigate each and every crash. On Windows, compile the modules with PDBs (program databases), and each time it crashes, attach a debugger to it.
You must add internal tests, too. Avoid the pattern:
doSomethingBad(T * t)
{
if(t == NULL) return ;
// do the processing.
}
This is very bad design because the error is there, and you just avoid it, this time. But the next function without this guard will crash. Better to crash sooner to be nearer from the error.
Instead, on Windows (there must be a similar API on MacOS)
doSomethingBad(T * t)
{
if(t == NULL) ::DebugBreak() ; // it will call the debugger
// do the processing.
}
(don't use this code directly... Put it in a define to avoid delivering it to a client...)
You can choose the error API that suits you (exceptions, DebugBreak, assert, etc.), but use it to stop the moment the code knows something's wrong.
Avoid the C API whenever possible. Use C++ idioms (RAII, etc.) and libraries.
Etc..
P.S.: If you use exceptions (which is a good choice), don't hide them inside a catch. You'll only make your problem worse because the error is there, but the program will try to continue and will probably crash sometimes after, and corrupt anything it touches in the mean time.
You can always add exception handling to your program to catch these kinds of faults and ignore them (though the details are platform specific) ... but that is very much a two edged sword. Instead consider having the program catch the exceptions and create dump files for analysis.
If your program has behaved in an unexpected way, what do you know about your internal state? Maybe the routine/thread that crashed has corrupted some key data structure? Maybe if you catch the error and try to continue the user will save whatever they are working on and commit the corruption to disk?
Beside writing more stable code, here's one idea that answers your question.
Whether you are using processes or threads. You can write a small / simple watchdog program. Then your other programs register with that watchdog. If any process dies, or a thread dies, it can be restarted by the watchdog. Of course you'll want to put in some test to make sure you don't keep restarting the same buggy thread. ie: restart it 5 times, then after the 5th, shutdown the whole program and log to file / syslog.
Build your app with debug symbols, then either add an exception handler or configure Dr Watson to generate crash dumps (run drwtsn32.exe /i to install it as the debugger, without the /i to pop the config dialog). When your app crashes, you can inspect where it went wrong in windbg or visual studio by seeing a callstack and variables.
google for symbol server for more info.
Obviously you can use exception handling to make it more robust and use smart pointers, but fixing the bugs is best.
I would recommend that you compile up a linux version and run it under Valgrind.
Valgrind will track memory leaks, uninitialized memory reads and many other code problems. I highly recommend it.
After over 15 years of Windows development I recently wrote my first cross-platform C++ app (Windows/Linux). Here's how:
STL
Boost. In particular the filesystem and thread libraries.
A browser based UI. The app 'does' HTTP, with the UI consisting of XHTML/CSS/JavaScript (Ajax style). These resources are embedded in the server code and served to the browser when required.
Copious unit testing. Not quite TDD, but close. This actually changed the way I develop.
I used NetBeans C++ for the Linux build and had a full Linux port in no time at all.
Build it with the idea that the only way to quit is for the program to crash and that it can crash at any time. When you build it that way, crashing will never/almost never lose any data. I read an article about it a year or two ago. Sadly, I don't have a link to it.
Combine that with some sort of crash dump and have it email you it so you can fix the problem.