Write MBR Code

Chris picture Chris · Feb 20, 2009 · Viewed 23.1k times · Source

I am an electrical engineer who has recently discovered the need to modify the code in the MBR. Basically I need the ability to execute code on the HDD before, the OS starts up and takes over.

I fully understand that this will need to be written in Assembly and given the 446 bytes or so of code space in the MBR I just expect to call other code outside of the MBR. My question is what's the best way to write into the MBR ? If I want to alter the MBR of lets say disk HDD_1... Is it better to slave HDD_1 into another machine and then write to it, or write to it directly (outside of windows) in the current machine. Basically I figure I'll insert a call and leave the rest of the MBR alone.

Any suggestions would be appreciated

Chris

I am well aware that this is going to be difficult. My QUESTION is what's the best way to put an instruction in the MBR ? It goes without saying Windows doesn't allow direct access to the disk. How would you suggest I write instructions into the MBR ? Is maybe booting a live CD of *nix and writing to the MBR from there ?

Answer

Yannick Motton picture Yannick Motton · Feb 20, 2009

There are various ways of writing to the boot sector of a drive, and there is a general reference I used back when I was experimenting with homebrew OS development: http://wiki.osdev.org/

I personally just boot under linux and use dd:

  1. Backup first

    dd if=/dev/sda of=~/windows_bootloader.bin bs=512 count=1

  2. Disassemble the bootloader

    ndisasm -b16 -o7C00h ~/windows_bootloader.bin > ~/windows_bootloader.asm

  3. Make your modifications and reassemble

    nasm ~/windows_bootloader.asm -f bin ~/modified_bootloader.bin

  4. Overwrite the bootloader

    dd if=~/modified_bootloader.bin of=/dev/sda bs=512 count=1

This assumes your that 'sda' is the correct block device. And note that the step 4 doesn't just copy the file to /dev/sda (which it could, but then you might overwrite more than just the first sector if the output binary > 512 Bytes )

Obviously you're not going to want to debug this approach on a live system. It will save you a lot of headaches to use some kind of x86 emulator like bochs, qemu or VMWare Server.

However as Michael Burr has stated, this will probably be a bad idea. Modifying the Windows bootloader, will probably leave you with little or no room for your own code.