Tuesday, July 20, 2010

Static ARP script for OSX

For security reasons, you may wish to set a static ARP entry for your gateway. This script automates this step. Note that this doesn't prevent DHCP or MAC spoofing however.
The script runs whenever a network connection is made or broken by using the launchd feature to check a path for changes. In this case, I used resolv.conf.
The scripts determines the default gateway IP address and then keep trying to find the corresponding MAC address in the ARP table. Then it sets up the static ARP entry.
Two files are needed: one launchd configuration file and a shell script file. You need to give execute rights on the shell script with chmod +x. Copy the files in place and rename/edit the filenames. You need to restart to make the configuration active.

The contents of /Users/darkfader/static-arp.sh:

#!/bin/bash
# if the resolv.conf file was deleted, create an empty one to enable file watch again
touch /var/run/resolv.conf
while true; do
        IP=$(netstat -rn | grep -m 1 default | tr -s ' ' | cut -d' ' -f 2)
        if [ "$IP" == "" ]; then
                exit 0
        fi
        MAC=$(arp -an | grep -m 1 $IP | tr -s ' ' | cut -d' ' -f 4)
        if [ "$MAC" == "" ]; then
                sleep 1
                continue
        fi
        arp -S $IP $MAC
        exit 0
done

The contents of /Library/LaunchDaemons/net.darkfader.static-arp.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>net.darkfader.static-arp</string>
        <key>ProgramArguments</key>
        <array>
                <string>/Users/darkfader/static-arp.sh</string>
        </array>
        <key>QueueDirectories</key>
        <array/>
        <key>WatchPaths</key>
        <array>
                <string>/var/run/resolv.conf</string>
        </array>
</dict>
</plist>

Wednesday, April 28, 2010

Windows on Intel Mac and AHCI mode

My configuration:
single internal hard drive in iMac with a single NTFS partition. This is BIOS identifier (hd0,1). In linux, this will be SATA device /dev/sda. The SATA controller is from ICH8M and has PCI identifier 8086:2828. Please change these references to your system configuration.
Don't worry, I still have OS X on an external FW800 drive but that's not relevant here.

First of all, I tried loading Windows 7 on my Intel Mac and then came to a few conclusions:
  • BIOS mode boot has the negative side-effect that it disables AHCI mode in the SATA controller. This leads to degraded performance of hard drive access.
  • EFI mode boot of Windows 7 requires EFI 2.0 which isn't included in the firmware.
  • Macs don't like to boot from external devices. Windows doesn't like to be installed on external drives.
So I swapped my OS X drive with Windows drive in the process of undusting my iMac. It now can boot both OSes.
This post is all about getting the SATA controller back into AHCI mode after the compatibility layer in the intel Mac changed it. AHCI gives NCQ and might be somewhat faster so I really wanted to try that after my younger brother nagged me about it during our dayly Mac-vs-PC argues.

I can talk about what I did wrong during those attempts but I will try to keep it short:
  • Start regedit and locate the following key: HKLM\System\CurrentControlSet\Services\msahci
    Change the "Start" value to "0". This will make Windows attempt to load the AHCI driver stack when it boots.
  • Download a Linux live-CD with GRUB 1.98. (others might indicate 0.xx as grub and 1.xx as grub2). I decided on the latest Ubuntu live-CD. Older versions just won't do unless you want ugly patches. You want to have the setpci grub module.
  • Download the "Rapid Storage Technology" manager software (includes the driver) and the "RST Driver Files for F6 Install" from the Intel website.
    In my case the latest version for x64 Windows was iata96enu.exe and f6flpy96x64.zip
    The manager software will not install yet but you have to install at least the driver by unpacking it and force a device installation:
    Go to Device Manager, select Serial ATA Storage Controller, Update driver software, Browse, Pick from list, Have disk, Ignore the warning. This should be ok since the next time you'll boot Windows, the device will be different anyway.
  • Boot the Linux CD :-)
    Hold option key when booting the Mac to see it as a boot option. Load the System until you can start a terminal. Get root access:
    sudo -i
  • Because it booted from CD, it doesn't know much about the hard drive. Therefore create a device map file that maps (hd0) to /dev/sda.
    vi /boot/grub/device.map
    i(hd0)[tab]/dev/sda[esc]:wq
    If you know some linux, you know what I mean.
  • Mount your Windows partition in Linux.
    mkdir /mnt/win
    ntfs-3g /dev/sda1 /mnt/win
  • Install grub to the MBR and copy the data files too.
    grub-install --no-floppy --modules=ntfs --root-directory=/mnt/win /dev/sda
    This should report no error.
  • If you already had a Boot directory on your Windows partition (most likely), you'll now have two boot directories (-.-); Fix it by moving the contents.
    mv /mnt/win/boot/grub /mnt/win/Boot

    rmdir /mnt/win/boot
  • reboot
    reboot (duh)
  • At the grub prompt you should now be able to try some commands.
    lspci
    setpci -d 8086:2828 90.b=40
    lspci (should now show 2829 instead of 2828)
    root (hd0,1)
    chainloader +1
    boot
  • If Windows now boots, it should be in AHCI mode and hopefully go ask for the drivers.
    You can install the RST manager or just check the Device Manager to see if it's working as intended.
  • You can create a C:\Boot\grub\grub.cfg file to automate the booting process. (Note: 'Manual editing of /boot/grub/grub.cfg is not encouraged')
    set timeout=10
    set default=0
    menuentry "Windows 7 with AHCI" {
    setpci -d 8086:2828 90.b=40
    set root=(hd0,1)
    chainloader +1
    }
  • PS: If somehow Windows booting was not working in the first place or you don't want any of this anymore, you can use the Windows 7 DVD. Some recovery commands you then can use:
    bootrec /FixBoot

    bootrec /RebuildBcd

    bootrec /FixMbr
    (should erase grub again but I don't know why you would want that)
I this I have all my notes into this post and hope that besides me remembering how to do it, also will help you and other Mac fans :P

Wednesday, January 13, 2010

Atmel production file

Atmel has implemented a so called 'production file' in its programmer software. It's a simple ELF file containing sections for Flash, EEprom and fuses. You can create these sections from your C code too.
The board I developed for contains an Atmega128 attached to an ethernet controller. Also, it contains a bootloader that can program and dump the flash and eeprom memory.
What I wanted is a complete snapshot of a working board for production use (special bootloader/firmware version without final encryption keys). It will also have the default MAC and IP address and checksum information in EEprom.

So, first I prepare a complete working board and start dumping the program memory in encrypted format by using a special bootloader function. The tool automatically writes out a special format complete with checksums etc.
bootload -m 00-01-23-45-67-89 -d -i dump.img -b 172.16.0.0
Then I call the encryption/decryption tool to turn it into a plain binary.
imgtool -d -b dump.bin -i dump.img

I do the same with the bootloader that is located at 0x1E000.
bootload -m 00-01-23-45-67-89 -d -i bldump.img -s 0x1E000 -b 172.16.0.0
And decrypt that as well:
imgtool -d -b bldump.bin -i bldump.img -s 0x1E000

Then comes the EEprom dump which is already in plain binary form:
bootload -m 00-01-23-45-67-89 -e -b 172.16.0.0
You might want to crop it down to a reasonable working size since programming the EEprom is terribly slow.
srec_cat eeprom.bin -binary -crop 0x0 0x80 -o eeprom.bin -binary

We also need small files containing the (lock-)fuses and the CPU signature that needs to match before programming. The order of bytes need to be reversed.
You could also compile this data with your project.
signature.bin (3 bytes): 02 97 1E for atmega128.
fuse.bin (3 bytes): BF D8 FF
lock.bin (1 byte): DC blocks programming cable and user-mode reads of bootloader area. The lock is written last and will activate the bootloader boot process.

There are various ways to combine it all together. I chose to combined the flash sections first:
srec_cat dump.bin -binary bldump.bin -binary -offset 0x1E000 -o combined_dump.hex -intel
and then add the extra sections:
avr-objcopy -O elf32-avr -I ihex combined_dump.hex --gap-fill 0xFF --add-section .eeprom=eeprom.bin --add-section .fuse=fuse.bin --add-section .lock=lock.bin --add-section .signature=signature.bin --rename-section .sec1=.text --rename-section .sec2=.text --set-section-flags=.eeprom="alloc,load" --set-section-flags=.fuse="alloc,load" --set-section-flags=.lock="alloc,load" --set-section-flags=.signature="alloc,load" temp.elf
The final step is assigning the section addresses and turning the file into executable ELF format.
avr-ld -s -mavr5 -o ProductionFile.elf temp.elf --section-start .eeprom=0x810000 --section-start .fuse=0x820000 --section-start .lock=0x830000 --section-start .signature=0x840000
The section offsets don't mean very much but the programming tool might check for them.
After this, you can delete all other intermediate files.

Ready to test to production file...
Stk500 -cUSB -datmega128 -ipProductionFile.elf -e -pafeb
And there you have it.
I hope you stumbled upon this post and found it useful.

Monday, October 05, 2009

iPhone OS upgrade to 3.1

Since I have my (3GS) 3.0 ECID SHSH on file with Cydia, I decided a while ago to update to 3.1. So I Pwnagetool-ed a ipfw and installed. Now, I wanted to try out the new modem firmware too and updated to official 3.1 firmware, only to come to conclusion it makes things more difficult and fixes nothing. Anyways, I went back to 3.0 and had to redsn0w it because it doesn't work with the new modem firmware. Then I installed the pwned 3.1 again and it works again.
Again, AptBackup gave an error but was easily fixed by duping the list files, press backup, restore list files, restore.

Security tips:
vim /Library/LaunchDaemons/com.openssh.sshd.plist
Remove <key>Bonjour</key><array>...</array> to hide from bonjour (local net).
If you want to change the portnumber from 22 to 443 or so, you can change SockServiceName from ssh to https or perhaps some number.
Connect with -p option: ssh root@your-iPhone.local -p 443
After changing, toggle SSH off and on and then connect with a 2nd terminal to try it out before closing the 1st.
And as always, don't forget to change password for mobile and root.

Tuesday, June 23, 2009

Xcode 3.1.3

With the new OS installed on the iPhone, Xcode complains it needs an update. So it updated to 3.1.3.
Again, I applied the modifications to skip provisioning profile.
In terminal, type open /Developer/Platforms/iPhoneOS.platform/Info.plist (opens with Property List Editor)
Under defaultProperties add/edit rows:
PROVISIONING_PROFILE_ALLOWED = NO;
PROVISIONING_PROFILE_REQUIRED = NO;
This works however only with Xcode for iPhone OS 2.x.
But you can replace the iPhoneRemoteDevice executable with one one from the older Xcode.
After that, Xcode initially crashed and disconnected the cable and removed an invalid entry in the Organizer. I get some internal errors but it can be skipped by holding the return key.
I also had a problem with my project. product-pkg-utility reported that CFBundleIdentifier cannot have illegal characters (e.g. underscore).
Anyways, I can debug again.

Update: Copying the whole iPhoneRemoteDevice.xcodeplugin directory seems to work now too.
Update2: Still seems to crash, although after "Reset and relaunch" it does not crash. Weird...
Whoa... starting "/Developer/Applications/Xcode.app/Contents/MacOS/Xcode &" from Terminal seems to work in any case.

Other links: here, here here and here

Monday, June 22, 2009

iPhone OS upgrade to 3.0

Taking my chances to upgrade to the latest OS version 3.0 for iPhone.
So, first needed to backup some things: AptBackup, SpringBack and finally, a backup with iTunes.
Then create a custom ipsw with Pwnagetool. To install this ipsw, I put the iPhone into recovery mode (did not need the DFU mode, since it was already hacked) by holding both buttons on the iPhone and release the sleep button when screen goes black. Installation went fine, but...

AptBackup icon was hidden because I used the Categories app. No sweat on that, but after unhiding, AptBackup failed on me since it wasn't tested with 3.0 yet.
Solution: Installed OpenSSH and APT again and ran the following command:
for p in `cut -f 1 /User/Library/Preferences/aptbackup_dpkg-packages.txt`; do apt-get -y --force-yes install $p; done
Any packages not for 3.0 won't be installed (like mobileinstallation patch), so you need to find a newer version for them.

I seemed to have lost most settings of Cydia apps since iTunes only backs up managed settings. This includes categories, spbk files, whatever. The only items in /User where Applications, Documents, Library and Media.
So next time, I'll copy the other items manually. Also /Library/Themes for custom themes.
Tip: Get Macfusion/FUSE to mount the iPhone volume on your Mac. Or use Cyberduck.

Replace yellown0w with ultrasn0w if you updated the baseband firmware (Pwnagetool does that by default btw!). At the time of me writing it wasn't released yet though... oops.

Friday, June 19, 2009

UIProgressView custom draw method

Code snippet of a UIProgressView subclass that implements custom draw method.
This example uses four images for the left side, right side and ten sections that can be either on/off or partially filled.
My images included edge and shadow and named: pb_left.png (9x32), pb_right.png (9x32), pb_on.png (28x32). pb_off.png (28x32)

- (void)awakeFromNib
{
[self setBackgroundColor:[UIColor clearColor]];
}

// allow non-clear background color in Interface Builder, but do not draw it
- (BOOL)getClearsContextBeforeDrawing
{
return NO;
};

// draw left and right edge of progress bar with filled sections between
- (void)drawRect:(CGRect)rect
{
const int numParts = 10;
UIImage *pb_left = [UIImage imageNamed:@"pb_left.png"]; // "["
UIImage *pb_right = [UIImage imageNamed:@"pb_right.png"]; // "]"
UIImage *pb_on = [UIImage imageNamed:@"pb_on.png"]; // "X"
UIImage *pb_off = [UIImage imageNamed:@"pb_off.png"]; // " "
CGPoint p = {0,0};
[pb_left drawAtPoint:p];
p.x = pb_left.size.width;
int q = (int)(self.progress * numParts);
for (int i=0; i<numParts; i++)
{
if (i == q) // partial on/off section. works with semi-transparent images too
{
float w = truncf(pb_on.size.width * fmodf(self.progress * numParts, 1.0f));
[pb_on drawInRect:CGRectMake(p.x, p.y, w, pb_on.size.height)];
[pb_off drawInRect:CGRectMake(p.x + w, p.y, pb_on.size.width - w, pb_on.size.height)];
}
else if (i < q)
{
[pb_on drawAtPoint:p];
}
else // (i > q)
{
[pb_off drawAtPoint:p];
}
p.x += pb_on.size.width;
}
[pb_right drawAtPoint:p];
}

Wednesday, June 17, 2009

Semi-transparent overlay for UIButton subclass

A little snippet for subclassed UIButton that adds an UIImageView overlay.
You can then animate the alpha property.
- (void)awakeFromNib
{
UIImage *img = [self imageForState:UIControlStateSelected];
overlayImage = [[UIImageView alloc] initWithImage:img];
overlayImage.alpha = 0.0f;
[self addSubview:overlayImage];
// [self addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
// you could call custom highlight handler
}

- (void)setHighlightedByAlpha:(BOOL)highlighted
{
[UIView beginAnimations:nil context:@"hmm"];
[UIView setAnimationCurve: UIViewAnimationCurveLinear];
[UIView setAnimationDuration:0.2f];
overlayImage.alpha = highlighted ? 1.0f : 0.0f;
[UIView commitAnimations];
}

Saturday, July 05, 2008

Gbit card, modem, HDD

Ok, I had it for now with this r8169 kernel driver. I even tried a suggested newer kernel version but even that didn't help. I put in a new Intel card and it seems to work fine.

Because I switched ISP, I have to return my modem (not my property; Sagem BASE F@ST 3202). I still wanted to know if I could get access to superuser account again. It is still accessible by serial port for which there is no connector unfortunately. An phone data cable with some soldering helps in these cases.
Well.. I just cleaned up the pads I probed and screwing it back together.
Since I can't remember what cables it came with, I just put in the ones in worst condition :)

I also bought a WD MyBook 1TB disk.

Wednesday, June 04, 2008

My network

New SSH keys generated to login without password on my server, macbook, imac and website. Works nicely. I have set MacFusion to mount automatically.

I've put back the r8169 network card in my server and it now appears to be running stable. Perhaps it's also because I upgraded the kernel version again to 2.6.24-gentoo-r3. Oh and I soldered 3 capacitors on it. They always leave out some to make it cheaper.
[edit]Shit.. still problematic[/edit]

After fiddling with MAC address in Time Machine to backup over firewire target disk mode, I found out that Apple added a hidden feature that enables network disks. With this gigabit network, that should go speedy although it still could be buggy or cause system hiccups. I wouldn't try backing up with my disk or imac turned/turning off though.
This method does not use the filesystem feature with hardlinks etc. but creates one big file: "{machine name}_{MAC address}.sparsebundle". It's probably more optimal for network links.

Btw, my macbook is named Diana and my imac Morte. From Noir-et-Blanc, which I have not seen yet but do have the Morte figurine. The internal HDDs are also called like that to prevent confusion when mounting them over the network.