The most important command was EE, chosen very arbitrarily, which meant “transition state.” The state transition would then toggle between the TASVideos website and chat interface. Also worth noting is that any character with a value of 00 was considered a null character and was not displayed for synchronization purposes.
Figure 10.12: Twitch Chat!
The Website
The website itself is not very complicated, rather just interesting to mention to take advantage of mode 0x03 which allowed us to render a 256–color image, rather than the standard 16–color images from the prior section. The only caveat was that we had to make a quick tool to remove duplicate tiles to optimize the tile data to fit in VRAM. Background colors were controlled by tweaking the palette data rather than the image itself, as the SNES is very poor at manipulating raw tile data due to its planar pixel format.
Outside of the SNES
The bot was connected to the console through the controller ports and a single wire going to the reset pin on the expansion board, meaning that from an external perspective the hardware was completely unmodified. The bot itself was connected by a USB serial interface to a MacBook Pro running Linux. The source of the button presses being sent to the bot was in the form of a continuous bitstream representing the state of all buttons for each frame. Once the payload was fully written and the Twitch chat interface was complete the bitstream transitioned from being pre-created movie content to a bitstream in the format the chat interface payload needed it in, with 5-bit and 7-bit encodings for characters and emoji. This was controlled by the python scripts that relied on a script to identify when Red, the player inside of the Pokémon Red game, said various things.21 The script also triggered things that TASBot, the robot holding the replay device, would say via the use of espeak, which allowed us to create a conversation between TASBot and Red.
As part of the script we predefined periods where we would “deface” the TASVideos website by changing it to different colors; this worked by showing an image on the SNES as well as literally defacing the actual website. Finally, the script was built with the ability to send commands to a serial-controlled camera, but truth be told we ran out of time to test it so we used a bit of stage magic to pretend like Twitch chat was interacting with the camera by typing directions to move it, and we had a helpful volunteer running the camera for us.
Live Performance
These exploits were unveiled at AGDQ 2015. They were streamed live to over 100,000 people on January 4th with a mangled Python script that didn’t trigger the text for Red properly, then again on January 11th with the full payload. The run was very well received and garnered press coverage from Ars Technica22 among others and resulted in substantially more interest in TASBot and the art of arbitrary code execution on video games than had existed previously. Most importantly, the TAS portions of the marathon where the exploit was featured helped raise over fifty thousand dollars directly to the Prevent Cancer Foundation. Overall, the project was a resounding success, well worth the substantial effort that our team put into it.
10:4 This PDF is a Gameboy exploit!
by Philippe Teuwen
The idea for this polyglot is to embed the contents of the previous article in such a way that it shows when played as an LSNES movie. So now you can use your copy of the journal to exploit your hardware and read “Pokémon Plays Twitch” on your TV. This way, we hope to start a tradition of articles being viewable on the hardware of the article!
LSNES supports two kinds of movie files, which might better be thought of as input recording files. The older format is ZIP based and formally specified, while the new one is binary and custom. The new binary format has no official specs, but starting a PDF with a ZIP signature would now trigger Adobe’s blacklist. Clearly, someone at the company must have disliked something about one of our previous releases. So the new, non-ZIP LSMV binary format is the one that we’ll use.
The buffers for read and write calls for movie data are straight out of the movie data in memory. One unintended benefit of the new format is that it is much easier to write from SIGSEGV or similar signal handlers. (The memory allocator cannot be trusted from inside a signal handler, of course.)
The binary LSMV format is chunk-based. The “lsmv” magic must be at offset 0; we can’t have any appended data. So the PDF header and content must be added in a dummy chunk early in the LSMV, and the ZIP and PDF footer must be added at the end of the file, in another dummy chunk (see included diagram).
A clean version of the LSMV file has been submitted to TASVideos.23 You can play this polyglot on a modified LSNES with the hybrid emulation core using BSNES and Gambatte or, if you have the required hardware, on the real stuff!
Be warned that none of these approaches is trivial. We include detailed howtos with the zip contents of this issue.24
10:5 SWD Marionettes; or, The Internet of Unsuspecting Things
by Micah Elizabeth Scott
Greetings, neighbors! Let us today gather to celebrate the Internet of Things. We live in a world where nearly any appliance, pet, or snack food can talk to the Cloud, which sure is a disarming name for this random collection of computers we’ve managed to network together. I bring you a humble PoC today, with its origins in the even humbler networking connections between tiny chips.
Firmware?
Where we’re going, we don’t need firmware.
I’ve always had a fascination with debugging interfaces. I first learned to program on systems with no viable debugger, but I would read magazines in the nineties with articles advertising elaborate and pricey emulator and in-circuit debugger systems. Decades go by, and I learn about JTAG, but it’s hard to get excited about such a weird, wasteful, and under-standardized protocol. JTAG was designed for an era when economy of silicon area was critical, and it shows.
More years go by, and I learn about ARM’s Serial Wire Debug (SWD) protocol. It’s a tantalizing thing: two wires, clock and bidirectional data, give you complete access to the chip. You can read or write memory as if you were the CPU core, in fact concurrently while the CPU core is running. This is all you need to access the processor’s I/O ports, its on-board serial ports, load programs into RAM or flash, single-step code, and anything else a debugger does. I took my first dive into SWD in order to develop an automated testing infrastructure for the Fadecandy LED controller project. There was much yak shaving, but the result was totally worthwhile.
More recently, Cortex-M0 microcontrollers have been showing up with prices and I/O features competitive with 8-bit micro-controllers. For example, the Freescale MKE04Z8VFK4 is less than a dollar even in single quantities, and there’s a feature-rich development board available for $15. These micros are cheaper than many single-purpose chips, and they have all the peripherals you’d expect from an AVR or PIC micro. The dev board is even compatible with Arduino shields.
In light of this economy of scale, I’ll even consider using a Cortex-M0 as a sort of I/O expander chip. This is pretty cool if you want to write microcontroller firmware, but what if you want something without local processing? You could write a sort of pass-through firmware, but that’s extra complexity as well as extra timing uncertainty. The SWD port would be a handy way to have a simple remote-controlled set of ARM peripherals that you can drive from another processor.
Okay! So let’s get to the point. SWD is neat; we want to do things with it. But, as is typical with ARM, the documentation and the protocols are fiercely layered. It leads to the kind of complexity that can make little sense from a software perspective, but might be more forgivable if you consider the underlying hardware architecture as a group of tiny little machines that all talk asynchronously.
The first few tiny machines are described in the 250-page ARM Debug Interface Architecture Specification ADIv5.0 to ADIv5.2 tome. It becomes apparent that the tiny machines must be so tiny because of all the architectural flexibility the designers wanted to accommodate. To start with, there’s the Debug Port (DP). The DP i
s the lower layer, closest to the physical fink. There are different DPs for JTAG and Serial Wire Debug, but we only need to be concerned with SWD.
We can mostly ignore JTAG, except for the process of initially switching from JTAG to SWD on systems that support both options. SWD’s clock matches the JTAG clock line, and SWD’s bidirectional data maps to JTAG’s TMS signal. A magic bit sequence in JTAG mode on these two pins will trigger a switch to the SWD mode, as shown in Figure 10.13.
Figure 10.13: JTAG-to-SWD sequence timing
SWD will look a bit familiar if you’ve used SPI or I2C at all. It’s more like SPI, in that it uses a fast and non-weird clocking scheme. Each processor’s data sheet will tell you the maximum SWD speed, but it’s usually upwards of 20 MHz. This hints at why the protocol includes so many asynchronous layers: the underlying hardware operates on separate clock domains, and the debug port may be operating much faster or slower than the CPU clock.
Whereas SPI typically uses separate wires for data in and out, SWD uses a single wire and relies on a turnaround period to switch bus directions during one otherwise wasted clock cycle that separates groups of written or returned bits. These bit groups are arranged into tiny packets with start bits and parity and such, using turnaround bits to separate the initial, data, and acknowledgment phases of the transfer. For example, see Figures 10.14 and 10.15 for read and write operations. For all the squiggly details on these packets, the tome has you covered starting with Figure 4-1.
These low-level SWD packets give you a memory-like interface for reading and writing registers, but we’re still a few layers removed from the kind of registers that you’d see anywhere else in the ARM architecture. The DP itself has some registers accessed via these packets, or these reads and writes can refer to registers in the next layer, the Access Port (AP).
Figure 10.14: Serial Wire Debug successful read operation
Figure 10.15: Serial Wire Debug successful write operation
The AP could really be any sort of hardware that needs a dedicated debug interface on the SoC. There are usually vendor specific access ports, but usually you’re talking to the standardized MEM-AP which gives you a port for accessing the ARM’s AHB memory bus. This is what gives the debugger a view of memory from the CPU’s point of view.
Each of these layers are of course asynchronous. The higher levels, MEM-AP and above, tend to have a handshaking scheme that looks much like any other memory mapped I/O operation. Write to a register, wait for a bit to clear, that sort of thing. The lower level communications between DP and AP needs to be more efficient, though, so reads are pipelined. When you issue a read, that transaction will be returning data for the previous read operation on that DP. You can give up the extra throughput in order to simplify the interface if you want, by explicitly reading the last result (without starting a new read) via a Read Buffer register in the DP.
This is where the Pandora’s Box opens up. With the MEM-AP, this little serial port gives you full access to the CPU’s memory. And as is the tradition of the ARM architecture, pretty much everything is memory-mapped. Even the CPU’s registers are indirectly accessed via a memory mapped debug controller while the CPU is halted. Now everything in the thousands of pages of Cortex-M and vendor-specific documentation is up for grabs.
Now I’m getting to the point.
I like making tools, and this seems like finally the perfect layer to use as a foundation for something a bit more powerful and more explorable. Combining the simple SWD client library I’d written earlier with the excellent Arduino ESP8266 board support package, attached you’ll find esp8266-arm-swd, an Arduino sketch you can load on the $5 ESP8266 Wi-Fi microcontroller.25 There’s a README with the specifics you’ll need to connect it to any ARM processor and to your Wi-Fi. It provides an HTTP GET interface for reading and writing memory. Simple, joyful, and roughly equivalent security to most Internet Things.
These little HTTP requests to read and write memory happen quickly enough that we can build a live hex editor that continuously scans any visible memory for changes, and sends writes whenever any value is edited. By utilizing all sorts of delightful HTML5 modernity to do the UI entirely client-side, we can avoid overloading the lightweight web server on the ESP8266.
This all adds up to something that’s I hope could be used for a kind of literate reverse engineering and debugging, in the way Knuth imagined literate programming. When trying to understand a new platform, the browser can become an ideal sandbox for both investigating and documenting the unknown hardware and software resources.
The included HTML5 web app, served by the Arduino sketch, uses some Javascript to define custom HTML elements that let you embed editable hex dumps directly into documentation. Since a register write is just an HTTP GET, hyperlinks can cause hardware state changes or upload small programs.
There’s a small example of this approach on the “Memory Mapped I/O” page, designed for the $15 Freescale FRDM-KE04Z board. This one is handy as a prototyping platform, particularly since the I/O is 5V tolerant and compatible with Arduino shields. Figure 10.16 contains the HTML5 source for that demo.
Figure 10.16: Single Wire Debug from HTML5
This sample uses some custom HTML5 elements defined in /script.js: swd-async-action, swd-hexedit, and swd-hexword. The swd-async-action element isn’t so exciting, it’s really just a special kind of hyperlink that shows a pass/fail result without navigating away from the page. The swd-hexedit is also relatively mundane; it’s just a shell that expands into many swd--hexword elements. That’s where the substance is. Any swd--hexedit element that’s scrolled into view will be refreshed in a continuous round-robin cycle, and the content is editable by default. These become simple but powerful tools.
Put a chip in it!
While the practical applications of esp8266-arm-swd may be limited to education and research, I think it’s an interesting Minimum Viable Internet Thing. With the ESP8266 costing only a few dollars, anything with an ARM microcontroller could become an Internet Thing with zero firmware modification, assuming you can find the memory addresses or hardware registers that control the parts you care about. Is it practical? Not really. Secure? Definitely not! But perhaps take a moment to consider whether it’s really any worse than the other solutions at hand. Is ARM assembly and HTML5 your kind of fun? Please send pull requests.26 Happy hacking
10:6 Reversing a Pregnancy Test; or, Bitch better have my money!
by Amanda Wozniak
The adventure started like most adventures do—in a dark bar near a technical institute over pints of IPA. An serial entrepreneur plied me with compliments, alcohol and assurances of a budget worthy of my hourly rate to take an off-the shelf device and build a sales-pitch demo in support of his natal company’s fund-raising and growth plan. The goal was to take approximately zero available fabrication resources other than myself and spend a couple of months to make a universally approachable, easy to use demonstration prototype for a (now utterly defunct) startup’s flow strip technology with a hack-a-thon patented Internet-of-Things interface. The target was an entry straight out of PC Magazine’s The Secret World of Embedded Computers, the thing no active neighbor should be without—a handy-dandy off the shelf CVS digital pregnancy test.
Fast, Cheap, and Easy
Head on down to your local pharmacy, and virtually every store will carry a nifty brand of digital pregnancy tests. All of these tests are basically identical (inside and out), and the marketing strategy is simple. Humans are bad at reading analog inputs, so when your time comes, let technology ease your mind whether you, the user is stressed to the breaking point trying to get pregnant or if you’re in the boat of desperately hoping you’re sterile. “Oh god, it’s been three seconds. Or minutes? Wait? What happened to space time. Is there one blue line? Two? I feel faint. Fish? Fuck! I’m pregnant with mutant fish babies.”27
Now, it doesn’t matter which brand you—buy for this exercise as far as I can tell, they’re all based on the same two-chip
solution built around a Holtek HT48C06 microprocessor. And you can guess at the function without cracking the case – just go buy one and look at the test strips themselves. For bonus points, look as underaged as possible.
Remember, this OTS technology is extra cool because back in the day, instead of peeing on a stick, women suspected of pregnancy had to have their urine injected into a rabbit in order to assess pregnancy before the onset of “the quickening.” If you think it’s hard telling the difference between + and —, you definitely haven’t had to divine your future livelihood from the appearance of leporid entrails. (By the Theory of Cyber-Extension, every time you use a digital pregnancy test, a cute bunny Tamagotchi is saved from certain death.)
Basics of the Test
Each strip has an absorbent area (that you pee on) and a clear window where the test results show up. One stripe is a control stripe that fires (changes color) in any liquid from water to bourbon, and the other one is a test stripe that only fires when sufficient concentrations of the hormone hCG are present in the fluid sample. (hCG stands for Human Chorionic Gonadotropin, named because scientists snicker at words like “gonad.”) You can use the strips without the digital tester, because all you’re being sold is a device that will load in one of the basic strips, and monitor the control and test stripes, and return three results: ERROR, NOT or PREGNANT. It turns out that $50 and getting at least one pregnant woman to pee on a test strip can end up for an entertaining couple of evenings at the old workbench.
PoC or GTFO, Volume 2 Page 10