POC || GTFO, issue 10

  • Upload
    fraggle

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

  • 8/19/2019 POC || GTFO, issue 10

    1/88

    PoC GTFO

    IN THE THEATER OF LITERATE DISASSEMBLY,

    PASTOR MANUL LAPHROAIGAND HIS MERRY BAND OF

    REVERSE ENGINEERSLIFT THE WELDED HOOD FROM

    THE ENGINE THAT RUNS THE WORLD!

    10:3 Exploiting Pokémon in a Super GameBoy

    10:4 Pokéglot!

    10:5 Cortex M0 Marionettes with SWD

    10:6 Reversing a Pregnancy Test

    10:7 Apple ][ Copy Protections

    10:8 Jailbreaking the Tytera MD380

    Washington, District of Columbia

    Funded by Single Malt as Midnight Oil and theTract Association of PoCGTFO and Friends,to be Freely Distributed to all Good Readers, andto be Freely Copied by all Good Bookleggers.

    Это самиздат. He who has eyes to read, let him read!0, $0 USD,  £0, 0 RSD, 0 SEK, $50 CAD.  pocorgtfo10.pdf. January 16, 2016.

    1

  • 8/19/2019 POC || GTFO, issue 10

    2/88

    Legal Note:   The buying party agrees that Pastor Manul Laphroaig and his merry band of Reverse Engi-neers lift the hood from the Engine That Runs the World  must be copied and shared with all neighbors, asdefined by previously agreed-upon language, until the year 2104. The buying party also agrees that, at anytime during the stipulated 88 year period, the seller may legally plan and attempt to execute one (1) heistor caper to steal back this issue of PoCGTFO, which, if successful, would return all ownership rights tothe seller. Said heist or caper can only be undertaken by currently active clergy of the Church of the Weird

    Machines and/or neighbor Dan Kaminsky, with no legal repercussions.

    Reprints:   Bitrot will burn libraries with merciless indignity that even Pets Dot Com didn’t deserve. Pleasemirror–don’t merely link!–pocorgtfo10.pdf and our other issues far and wide, so our articles can help fightthe coming robot apocalypse. We like the following mirrors.https://pocorgtfo.hacke.rs/

    https://www.alchemistowl.org/pocorgtfo/

    http://www.sultanik.com/pocorgtfo/

    http://openwall.info/wiki/people/solar/pocorgtfo

    Technical Note:   The polyglot file   pocorgtfo10.pdf   is valid as a PDF, as a ZIP file, and as an LSMVrecording of a Tool Assisted Speedrun (TAS) that exploits Pokémon Red in a Super GameBoy on a SuperNES. The result of the exploit is a chat room that plays the text of PoCGTFO 10:3.

    Run it in LSNES with the Gambatte plugin, the Japanese version of the Super Game Boy ROM and theUSA/Europe version of Pokémon Red.

    . / l s n e s   −− l i br a r y=g a mba tte/ co r e . s o

    Printing Instructions:   Pirate print runs of this journal are most welcome! PoCGTFO is to be printedduplex, then folded and stapled in the center. Print on A3 paper in Europe and Tabloid (11” x 17”) paperin Samland. Secret government labs in Canada may use P3 (280 mm x 430 mm) if they like. The outermostsheet should be on thicker paper to form a cover.

    # This is how to convert an issue for duplex printing.

    sudo apt-get install pdfjampdfbook --short-edge --vanilla --paper a3paper pocorgtfo10.pdf -o pocorgtfo10-book.pdf

    Preacherman Manul LaphroaigEthics Advisor The GrugqPoet Laureate Ben Nagy

    Editor of Last Resort MelilotLATEXnician Evan SultanikEditorial Whipping Boy Jacob TorreyFunky File Formats Polyglot Ange AlbertiniAssistant Scenic Designer Philippe TeuwenMinister of Spargelzeit Weights and Measures FX

    2

  • 8/19/2019 POC || GTFO, issue 10

    3/88

    1 Please stand; now, please be seated.

    Neighbors, please join me in reading thiseleventh release of the International Journal of Proof of Concept or Get the Fuck Out, a friendly little col-lection of articles for ladies and gentlemen of distin-

    guished ability and taste in the field of software ex-ploitation and the worship of weird machines. Thisis our eleventh release, given on paper to the fineneighbors of Washington, D.C.

    If you are missing the first ten issues, we the edi-tors suggest pirating them from the usual locations,or on paper from a neighbor who picked up a copy of the first in Vegas, the second in São Paulo, the thirdin Hamburg, the fourth or eighth in Heidelberg, thefifth in Montŕeal, the sixth in Las Vegas, the sev-enth from his parents’ inkjet printer, the ninth inMontŕeal, or the tenth in Novi Sad or Stockholm.

    Our sermon today, to be found on page 4, is a

    sordid tale in the style of a Dickensian ghost story.Pastor Laphroaig invites us to the anatomical the-ater, where helpless tamagotchis are disassembled infront of an audience, for  FUN !

    Page 7 contains a delightfully sophisticated andreliable exploit for Pokémon Red on the SuperGameBoy, starting from a save-game glitch, thenworking forward through native Z80 code executionto native 65C816 code on the host Super NES. Theydo all of this on real hardware with scripted accessto only the gamepad and the reset switch!

    Keeping up our tradition of shipping in funkyfile formats, this PDF is a new polyglot! Page 24

    contains the details for how this PDF is also an ex-ploit, loading Pokémon Plays Twitch in the Lsnesemulator.

    Micah Elizabeth Scott is becoming a regular con-tributor to this journal, and we eagerly await eachof her submissions. Page 26 contains her notes onARM’s replacement for JTAG, called Single WireDebug or SWD. Driving SWD from an Arduino,she’s able to move the target machine like a mari-onette, scripted from literate HTML5 programmingwith powerful new elements such as  swd-hexedit.

    When we heard that Amanda Wozniak was con-tracted to reverse engineer a pregnancy test, butnever paid for the work, we quickly scrounged up fiveCanadian loonies to buy the work as scrap. Page 32contains her notes, and we’ll happily pay five moreloonies to the first use of this technology in a Hack-aday marriage proposal or shotgun wedding.

    On page 39, Peter Ferrie shares tricks for break-ing the copy protection of dozens of Apple ][ games.When we told Peter to keep his notes to six pages,he laughed and dared us to find tricks worth cut-

    ting from his article. Accordingly, our cutting-roomfloor is empty and this article is the most completecollection of Apple ][ cracking techniques in modernpublication.

    Travis Goodspeed has been playing with Dig-ital Mobile Radio (DMR) lately, a competitor toTETRA and P25 that is used for amateur ra-dio, as well as trunked radio for businesses andcash-strapped police departments. Page 76 con-tains his notes for jailbreaking the Tytera MD380’sbootloader, dumping all of protected memory, thenpatching its application to enable promiscuousmode. These tricks should also work on the CS700,CS750, and a variety of other DMR handhelds.

    On page 88, the last and most important page,we pass around the collection plate. We don’t needyour dimes, but we’d love some nifty proofs of con-cept.

    3

  • 8/19/2019 POC || GTFO, issue 10

    4/88

    2 Three Ghosts and a Little, Brown Dog

    a sermon by Pastor Manul Laphroaig 

    Rise, neighbors, and in the tradition of the sea-son, let’s have a conversation with spirits of the past,the present, and the future. We will head to a dis-reputable place, a place of controversy where, ac-cording to the best moral authorities, irresponsiblepeople do foul things for funa place of scandalous,wholesale wickedness which must be stopped!

    Yes, neighbors, we are heading to an   anatom-ical theater , to observe its grim denizens at theirgrisly pastime. While some dissect carcasses, therest watch from rows of seats. They call it learn-ing and finding things outeven though most of what meets the eye looks like merely breaking thingsapart. They say they are making things bettereven curing diseases!though there are highly titledauthorities with certified diplomas and ethically ap-proved methodologies who make it their business toimprove things “holistically,” without all this discon-

    certing breakage and cutting things off. Truly, if thisdoesn’t beg the question of “How is this allowed?” then what does?

    There was a time, neighbors, when   anatomy didn’t mean trying to guess how a thing functionedby dissecting a specimen. When Andreas Vesal-ius published his classic human anatomy atlas withits absolute priority of dissection for learning whatwas and what was not true about the human body,his fixation on biological disassembly was a scandal.A proper anatomy book was understood to includeAristotle’s four humors and a fair bit of astrology;imagine how regressive Vesalius’ fixation on cuttingthings apart to find their function must have looked!Even when he became a royal court physician, otherlearned physicians called him a barberfor everyoneknew that only barbers and sawbones used blades.Until Victorian times, a doctor was a gentleman,

    4

  • 8/19/2019 POC || GTFO, issue 10

    5/88

    and a surgeon wasn’t. Testing the patient’s urinewas fine, but taking knives to one was simply belowa proper doctor’s station.

    Vesalius’ dissection-bound atlas became an in-stant hit, though. It turned out that going into spe-cific techniques of dissectionplace a rope here and

    a pulley thereso that others would replicate it wasexactly what was needed; the venerable signs and el-ements, on the other hand, not so much. Which didnot save Vesalius from having to undertake an emer-gency trip to far-away lands for an obscure reason,dying in abject poverty on the way. He died beforethe first dedicated anatomical theater was built in1594, by which time anatomy finally meant what hehad made it mean.

    Ah, but that was then and now is now! Theyear is 1902, and   physiology   is the latest scandal.Again, moral delinquents and their supporters are

    doing something loathsome: vivisection. Again,they come up with excuses: it’s all about findingout how things work, they say; some kind of knowl-edge that makes them different from the uninitiated,we hear. And even if there was knowledge to begained, could it really be trusted to such an imma-ture and irresponsible crowd? Stuck to theirnotso innocenttoys and narrowly focused views, theycan’t even see the bigger ethical picture! They caterto and are occasionally catered by truly objection-able charactersand then have the gall to shrug itoff. They talk about education, but who in theirright mind would let them near children? Too bad

    there isn’t a general law against them yet, and theestablishment is dragging its feet (or even has itsown uses for them, no doubt disgusting)but thestride of social progress is catching up with them,and, with luck, there soon will be!

    That was the year of high court drama, a pitchedbattle between people who each believed to em-body “social progress” against “superstition” on bothsides. It saw rallies by socialists and riots by medi-cal students, scientists and suffragettes, British lordsand Swedish feministsand a lot more, includingits own commemorative handkerchief merchandise.It is immortalized in history as  The Brown Dog af-

     fair , one so dramatic that even the Wikipedia arti-cle about it makes for good reading. Incidentally,the experiment involved led to the discovery of hor-mones.

    So says the Ghost of Science Past, but we bidhim to haunt us no longer. There is another, morecheerful Spirit to occupy our attentionthe Spirit of the Present. This is a more cheerful Spirit, involv-ing pets only as cute pictures thereofand lots of them!much to the relief of those who think neither

    Schrödinger nor Pavlov would make good friends.But this Spirit isn’t left without attention from

    our moral betters. What about the children? Whatabout the lowlives and the criminals whom we em-power by our so-called knowledge? What aboutthe bullies, the haters, the thieves, the spies, thedespots, and eventhe terrorists? Would a goodthing be called  exploitation   or  pwnage ? This newreality is so scary to some people that their responsegoes straight to nuclear; they call for a  Manhattan project , but what they really mean is “nuke it fromorbit.” To some, it’s even about evil “techno-priests” hijacking “true social progress”or at least it sells

    their books.Nor is this Spirit’s domain devoid of court

    drama, even in our enlightened timesalthoughlooking where we tend to fall on the scale betweenVesalius and Lord Alverstone’s Old Bailey, one be-gins to wonder just where the light is going. Nowonder the Spirit of the Hacking Present looks some-what frayed around the edges.

    Why wait for the Specter of the Future to makean appearance? I say, neighbors, let’s make like 1594at the University of Paduaback when a universityused to have quite a different place in this game of ghostsand have our own Anatomical Theater, a

    Theater of Literate Disassembly!Just as Knuth described Adventure with Liter-

    ate Programming,1 we’ll weave together the disas-sembled code of a live subject with expert explana-tions of its deeper meaning. (Of course the best partmight well be a one liner, but we’ll save the readerhours of effort!) We’ll weave a log and a transcriptinto an executable script that reproduces the cuts of a Master Surgeon, stroke by stroke.

    It is high time. We have been doing our dissec-tions alonewith none or few to watch and learnlong enough. Let other neighbors watch your disas-sembly, show them your technique, and let them geta good view and share the fun.

    As the good old U. of Padua preserved its the-ater, so shall we! And then perhaps the Specter of the Future will smile upon us.

    1unzip pocorgtfo10.pdf adventure.pdf

    5

  • 8/19/2019 POC || GTFO, issue 10

    6/88

    6

  • 8/19/2019 POC || GTFO, issue 10

    7/88

    3 Pokémon Plays Twitch

    by Allan Cecil (dwangoAC), Ilari Liusvaara (Ilari) and Jordan Potter (p4plus2)

    For the Awesome Games Done Quick (AGDQ)2015 charity marathon we exploited a chain of un-modified Nintendo game console components con-sisting of a Pokémon Red Game Boy cartridge in aSuper Game Boy running in a Super Nintendo. Weplugged the latter into custom hardware posing asa normal controller. In this  seven -stage exploit, wecorrupted a save file to give ourselves 255 Pokémon,swapped Pokémon, and tossed items to plant shell-code. We committed a series of atrocities usingdocumented command packets and ultimately broke

    into the Super Nintendo’s working RAM, where wewrote our own chat interface to display live contentsof the Twitch chat and even a representation of a de-faced website.

    3.1 TAS’ing a Game to execute Ar-bitrary Code

    TASVideos2 hosts Tool-Assisted Speedruns of games that are created using an emulator with speed

    controls such as slow motion and frame advance,along with the ability to save and restore the state

    of the game (or, rather, of the entire console) at anytime. TAS movie files consist of a list all of the but-ton presses sent to the console every frame from thetime it is powered on until the game is beaten. Itaids our poor human reflexes, but it can do a lotmorelike arbitrary code execution!

    The first run on the site to use this ability toexecute arbitrary code to jump to the credits of a game was Masterjun’s Super Mario World run.Later, Bortreb used arbitrary code execution in arun of Pokémon Yellow, marking the first time ex-ternal content was added to an existing game.

    In late 2013, dwangoAC worked with Ilari and

    Masterjun to present a run at AGDQ 2014 thatprogrammed the games Snake and Pong into SuperMario World on a real console using a replay device(also known as a “bot”) from True.3 This was a hugesuccess and was covered by Ars Technica, but weknew that we could do even more, which ultimatelyled us to the project described in this article.4

    3.2 The Game Choice

    We started with an end-goal of executing arbi-trary code on a Super Nintendo (SNES) using aSuper Game Boy (SGB) cartridge as the entry

    point. We initially planned to use Pokémon Yel-low based on Bortreb’s exploit in that game, butquickly discovered that the SGB detection routineused by Pokémon Yellow is extremely broken andonly worked on a real SGB by pure chance.5 Af-ter looking at other options, we chose to use thePokémon Red version, which uses a more reliableSGB detection routine that gets us access to thefull SGB palette, a custom border, and consistenttiming benefits we’ll discuss later.6 Using Pokémon

    2http://tasvideos.org3http://truecontrol.org4It should also be noted that all recent AGDQ events have directly benefited the Prevent Cancer Foundation which was a

    huge motivator for several of us who worked on this project. The block we presented this exploit in at AGDQ 2015 helped raiseover $50K and the marathon as a whole raised more than $1.5M toward cancer research, making this project a huge success onmultiple levels.

    5In brief, the detection routine is extremely sensitive to how many DMG clock cycles various operations take; the emulatoris likely slightly inaccurate, which causes the detection to fail, but from looking at the behavior it seems like it “just works” onthe real hardware. This is sheer luck, and the game developers likely never even knew it was so fragile.

    6If the SGB BIOS does not find the special codes in the DMG game header that indicate it’s an SGB-enabled game ( $146equal to  $03), it locks up the command channel until the game is reset, rendering any SGB based exploitation impossible. Seehttp://gbdev.gg8.se/wiki/articles/The_Cartridge_Header   for more details.

    7

  • 8/19/2019 POC || GTFO, issue 10

    8/88

    Red also has another added benefit in that the entiregame has been skillfully disassembled.7

    3.3 The Emulator

    When we started this project in August 2014, theonly emulator capable of emulating an SGB inside of an SNES at a low enough level for our needs was theBSNES emulator. Unfortunately, although BSNESis very accurate at emulating an SNES, it doesn’t doa very good job of emulating an SGB. The GambatteDot-Matrix Game Boy (DMG) emulator is likewisevery accurate, but is unable to emulate an SGB onits own. Ilari was able to create a hybrid emulationcore using BSNES to emulate the SNES↔DMG in-

    terface chip while using Gambatte for DMG emula-tion. This was a considerable undertaking, but inthe end the emulator was very usable, albeit some-what slow, as properly emulating the synchroniza-tion between the SNES CPU and the DMG CPUis a challenge. Ilari continued to provide emulatordevelopment and scripting support throughout theproject.

    3.4 The Hardware

    We didn’t just want to exploit a game in the sandboxof a console emulator and call it a Proof of Concept.We wanted to do the job properly and create an ac-tual exploit that would work on real hardware. Onlyone member of our team (dwangoAC) had all of the required hardware in one place, namely a SNESconsole, a SGB cartridge, a copy of Pokémon Red,and the replay device posing as a controller, alsoknown as a “bot.” 8 Because we wanted to streamdata from an attached computer, we opted to usean older, serial-over-USB connected device, namely

    True’s NES/SNES Replay Device. This choice of hardware had a few limitations but worked out wellfor the project in the end.

    Figure 1 – The legendary TASBot

    3.5 The Plan

    We were initially unsure what kind of payload tocreate once we had gained the ability to executearbitrary code on the SNES. Initially we investi-

    gated methods of showing crude video, but aban-doned it after spending far too much time failing toincrease the datarate and running into limits withthe processing speed of the SNES’s 65C816 CPU.An IRC discussion about Twitch Plays Pokémon9

    led dwangoAC and p4plus2 to brainstorm what itwould take to incorporate similar elements into ourpayload, and the concept of  Pokémon Plays Twitch was hatchedwhere a Pokémon character enters aTwitch chat room and “plays” Twitch. In the end,we took it to the next level by giving Red a voice ina chat interface on the SNES and giving TASBot,the robot holding the replay board, the ability to

    speak through espeak  and argue with Red. There’smuch more to say about that, but let’s first get tothe point where we can execute arbitrary code!

    7unzip -j pocorgtfo10.pdf pokemon_plays_twitch/pokered-master.zip8The term “bot” was originally used because it’s as if you have a robot playing the game for you; dwangoAC later attached

    one of these replay devices to a R.O.B. robot as shown in Figure 1 and after presenting Pong and Snake on SMW, the nameTASBot came to be associated with the combination as described at   http://tasvideos.org/TASBot.

    9A way of crowdsourcing gameplay by parsing commands sent over IRC.

    8

  • 8/19/2019 POC || GTFO, issue 10

    9/88

    Figure 2 – A strange rival

    3.6 Stage 0: Corrupting a save game.

    (3–7 bytes per minute.)

    We start the game by creating a save file, givingourselves the default name of Red and naming ourrival RxRx as shown in Figure 2. We then save thegame as in Figure 3, but reset the console directly af-ter it starts writing to the cartridge’s SRAM. Thereis checksumming on most of the values in the save

    file but at least one value has no checksum at all,namely the byte at the start of the “party data” that stores the number of Pokémon that have beencaught. By some chance, this value in SRAM (at0xAF2C, or   0x2F2C   when paged) is initially set toFF, so we wait long enough for valid name data anda save file header to be written before resetting. It ispossible to do this with human reflexes as the win-dow is approximately 20 ms but we opted to runa wire from our replay device to pin 19 on the ex-pansion port on the underside of the SNES. Thisallowed us to trigger a reset by shorting the pin toground, as shown in Figure 3.10

    3.7 Stage 1: Writing Z80 assemblyby swapping Pokémon and toss-ing items.

    (30 bytes per second.)After loading the game but before changing any-

    thing, the initial state of the GBBUS memory mapis as follows:11

    1 0xD163 Number of Pokemon caught ,c o r r up t e d t o 0 xFF i n S t ag e 0 .

    3 0 x D1 64 Pokemon I Ds ( 1 b y t e e a ch ) ,c o r r u p t e d t o 0 xFF .

    5 0xD16A S e n t i n e l b y te ( 0 xFF )0 xD16B Po kemo n Data (4 4 bytes ea ch) ;

    7 a l l a r e c o r r u p t e d to 0xFF .0 xD273 Pokemon o r i g i n a l t r a i n e r s ;

    9 a l l a r e c o r r u p t e d to 0xFF .0xD2B5 Pokemon nick names ;

    11 a l l a r e c o r r u p t e d to 0xFF .0xD2F7 Pokemon owned bitmap (19 byt es ) ;

    13 a l l z e r o e s .

    0 xD30A Po kemo n s een bitma p (1 9 bytes ) ;15 a l l z e r o e s .0xD31D Number o f i t em s ; i n i t i a l l y 0

    17 0 xD31E I t em s a r r ay ; e ac h e n t r y i s 2 b y te s ,a n i t e m I D a nd i t e m c o u nt .

    19 A f t e r t he l a s t item , th e r e i s an FF .( I n i t i a l l y l o c a t e d a t 0xD31E . )

    21 0 xD3 47 Money a s B ina ry−Coded Decimal .( I n i t i a l l y 00 30 0 0 , $30 00 . )

    23 0 xD34A R i v a l ’ s name . ( S e t d u r i ng S t ag e 0 ,i n i t i a l l y

    25 91 F1 91 F1 E1 50 00 00 00 00 00 . )0 xD3 55

    27 0xD36E Map l e v e l s c r i p t p o i n t e r .( I n i t i a l l y B0 4 0. )

    We want to adjust some of these values to cre-ate a payload described in the next section, and thegame conveniently provides three ways to arrangethe state of memory.

    •   Swapping Pokémon: The game implementsmoving Pokémon around the list by swappingthe raw contents of entries in the ID, Data,Original trainer, and nickname tables, whichhappens to offset data by an odd amount.Since we have 255 Pokémon instead of the 141the game was originally limited to we can swap

    10As with many exploits, the seed for this came from Bortreb’s Pokémon Yellow exploit, which itself came from earlierdiscoveries of others. Masterjun adapted the exploit for Pokémon Red using the BizHawk DMG emulator and dwangoAC tookthis information and made the Stage 0 and Stage 1 movie file in LSNES.

    11The same values can be found in the GBWRAM region at an offset of   -0xC000, so the value for   0xD163  in GBBUS (whichisn’t visible in the LSNES memory editor) can instead be found at  0x1163 in GBWRAM. GBBUS addressing is used throughoutfor consistency with existing resources such as the pokered disassembly.

    12This means the Poḱemon data now extends past end of WRAM, and in fact the WRAM should in effect loop around,although this isn’t used.

    9

  • 8/19/2019 POC || GTFO, issue 10

    10/88

  • 8/19/2019 POC || GTFO, issue 10

    11/88

    Figure 4 – Pokémon and items are re-arranged in memory to create shellcode.

    11

  • 8/19/2019 POC || GTFO, issue 10

    12/88

    Figure 5 – Item IDs can double as Z80 opcodes.

    codeas it would be quite tedious to use this methodto do anything longer.13 Here’s a disassembly of what we’ve been able to write so far, starting from0xD361.

    Everything up to this point has been the processof writing Stage 1, but now it’s time to walk through

    executing it, although some of the shortcuts we tookrequire a bit of explanation.

    First, the reason  0xD361   contains  30  is becausethe beginning of the Stage 1 data is mostly copiedfrom the field that holds the rival namewhich hap-pens to be directly preceded by the player’s money.Of this quantity we see the last two out of threebytes represented here in BCD format; the full value00 30 00  starts at   0xD360. It would take extra ef-fort to eliminate the 30 00 portion, but because thatsequence is effectively a  NOP, we leave it be.

    To reduce the number of bytes that needed tobe modified, we used several clever tricks. The codethat jumps to this point sets  HL  to the jump targetaddress, and  HL  is a canonical pointer register thatcan be written to. We reused  0xD36E (the map levelscript pointer) as the loop jump address; upon exit-

    ing the menu, the map level script pointer is loadedand called, so it loads the value in   0xD36E   into   HLand jumps to it.

    1041 LD HL, 0xD36E2 1 0 4 4 LD A,(HL+)1 0 45 LD H,( HL)

    4 1 04 6 LD L , A1 0 47 LD DE , 0 x10 4C

    6 104A PUSH DE1 04B JP ( HL ) ; [ D 36E ]

    Stage 1’s purpose is to read the buttons beingheld down on the controller and write them some-where, eventually executing what we’ve written us-ing this slightly more efficient method than twid-dling with Pokémon and items. At a high level,

    this code will read a byte from the controller on oneframe, read another byte from the controller on thenext frame, subtract the two, store the result at agiven memory offset and repeat, successively storingvalues one byte at a time in order in memory, andultimately executing said bytes.

    The game’s NMI (Non-Maskable Interrupt) rou-tine writes a bitmap of the current buttons be-ing held down during each frame (mapped as thebuttons ABsSRLUD from lowest to highest bit)to   0xFFF8, and   HALT   is used to wait for the nextframe. Unfortunately, the SGB BIOS cancels outLEFT+RIGHT or UP+DOWN if they are pressedsimultaneously and instead converts those bits to0’s. To work around it, our short routine readstwo frames and combines the values in a way thatcan yield arbitrary bytes. Because of restrictions on

    item and   190modFF  =  91  is stored as the remainder in the other.14There is no working way to  ADD  the two reads because we can’t write that opcode. Due to byte restrictions, we can’t use

    JP either, but  CALL  is close enough. See Figure 5.

    12

  • 8/19/2019 POC || GTFO, issue 10

    13/88

    which bytes we can create, we use   LD C,A  to storethe first value and then   SUB C  to combine them.14

    Using this method, we write the following datato 0xD338, which is executed every frame; that is tosay, it is repeatedly executed even before it is fullywritten!

    1 1 8 27

  • 8/19/2019 POC || GTFO, issue 10

    14/88

  • 8/19/2019 POC || GTFO, issue 10

    15/88

    We need to send two separate command pack-ets, described below.17 The packets aren’t a full 16bytes in length like they appear to be, but 11 and 7bytes; the tails of the packets are ignored, so we letthe packet payloads overrun into whatever happensto be next. After sending the packets, we have no

    use for the DMG anymore, so we hang the Z80 byentering a tight loop.

    The following Stage 2 assembly code is loadedinto  0xD33AD360.

    1 ; The g a dg e t t a k e s a n ew b a nk n umber i n A .3E 1C LD A, #$1C

    3 ; C a l l t he b an ks wi t ch g ad ge t .CD AF 00 CALL $00af 

    5 ; The a dd re s s o f t he f i r s t p ac ke t t o s en d .2 1 4 D D3 LD HL , p a c k e t 1

    7 ; C a l l p ac k et s en d r o u t i n e .CD EB 5F CALL $5fe b

    9; The l ow b yt e o f a d d re s s o f t h e 2 nd p ac k et .

    11 ; u se d t o c om pe ns at e i n pu t s l i p p i n g .2E 58 LD L , 0 x58

    13 00 NOP; C a l l p ac k et s en d r o u t i n e .

    15 CD EB 5F CALL $5fe b

    17 18 FE JR   −2 ; Hang t he DMG.

    19 p a c k e t 1 : ; 0 x d3 4dDB 0 x79 , 0 x00 , 0 x18 , 0 x00 , 0 x06 , 0 xad ,

    21 0 x12 , 0 x42 , 0 x30 , 0 xf b , 0 x40

    23 p a c k e t 2 : ; 0 x d3 58DB 0 x91 , 0 x18 , 0 x42 , 0 x00 , 0 x00 , 0 x18 ,

    25 0 x00 , 0x00 , 0x00

    Originally, the   LD L, 0x58 ; NOP  sequence wasLD HL, 0xD358  but we discovered that the transferroutine leaves the upper eight bits of the address inthe  H  register at the end of the transfer. The trans-fer end of the packet at  0xD34D  will be   0xD35D, sothe  H  register will be  D3, which is exactly the valuewe want for the next packet, so we can save one byteby just loading the   L   register. The saved byte cantaken to be   NOP (00).

    The repeated input can land on two inputs of the same byte, or the last input of one byte andfirst input of next. The latter is much better, sincefor any byte pair, it is possible to construct threevalid inputs. However, the first is much worse: Thebyte will be forced to   00, and even more unfortu-nately, the frame rules always cause the duplication

    to occur in a bad way. The   00   freed from onlyloading L is close enough to the middle that thisbyte can be targeted for duplication. It turned outthat the emulator doesn’t emulate the input slippingquite accurately and we (dwangoAC) had to do a lotof tedious trial and error testing to time the input

    correctly.18

    The offset between emulator and realhardware turned out to be eight frames, which weadjusted by adding eight frames of no input into thefile sent to the bot prior to exiting the menu.

    3.9 Exploiting DMG→SGB com-mand packets for gaining afoothold on SNES

    The Super Game Boy command packet protocol hastwo nifty commands for gaining control of the SNES.0x79 writes arbitrary data to an arbitrary memory

    location, while  0x91 sets the NMI vector and jumpsto an arbitrary address. Both commands are real,documented command packets; they are not undoc-umented debug commands.

    Since the Stage 2 executing on the DMG is sosmall we needed to minimize the number of pack-ets required. The SNES’s controller registers arememory-mapped I/O registers that automaticallyupdate each video frame when enabled. It is possibleto execute code from those registers but it isn’t par-ticularly easy to do so, largely because it is very un-safe to execute anything from those registers whenthey are in the middle of an update. (There are all

    sorts of intermediate stages.)The solution is to find some way for the SNES

    CPU to waste time during that update elsewhere.The NMI vector and the NMI handler are perfectfor this: when enabled, it starts running just beforethe register starts updating, so we just need an NMIhandler that wastes somewhere between roughly 4and 260 scanlines so it hits after the current NMIreturns but before the next NMI starts. Scanningdescriptions of various SNES I/O registers, a usefulone seems to be   $4212, which has bit 7 set whenthe console is performing a vertical retrace. TheNMI occurs immediately after the vertical retracestarts and the retrace lasts for about 40 scanlines,so waiting for   $4212  bit 7 to clear works out per-fectly. Since the retrace bit is bit 7 and the SNESCPU happens to be in a mode where the   A  regis-

    18Each blind test took about 5 minutes, as we had to play back the entire movie before reaching the point where we coulddetermine if it worked and we weren’t entirely certain it would work at all, but eventually we discovered the correct offset.

    19Based on the setting of a flags register bit that selects between an 8– and 16–bit  A  register.

    15

  • 8/19/2019 POC || GTFO, issue 10

    16/88

    ter is 8 bits wide,19 numbers with bit 7 set show asnegative, so it’s trivial to branch on those using  BMIinstruction. Handily enough, the   LDA   instructionthat loads the memory address into the   A  registersets the condition flags, so we can just loop aroundthat one instruction using  BMI.

    After the loop, we must return from the NMI.This is done using the   RTI  instruction, so the finalNMI handler looks like:

    1 l o o p :AD 12 42 LDA $4212 ; Read 0x4212 .

    3 30 FB BMI l oo p ; Loop   while   b i t 7 i s s et .40 RTI ; Return from NMI .

    This handler trashes the  A  register, which is gen-erally considered bad style, but we can get awaywith doing that.

    We send two packets; the first one writes sixbytes (AD 12 42 30 FB 40) into the memory ad-dress   0x001800. This is the NMI routine.

    79 ; Write Memory2 00 18 00 ; Target Address

    06 ; S i z e4 AD 12 4 2 3 0 FB 4 0 ; C on te nt

    Figure 8 – Inception

    The second one jumps to  0x004218 (which is thestart of the controller registers), with the NMI vec-tor set to 0x001800 (which points to the routine we

     just wrote).20

    91 ; Jump2 18 4 2 0 0 ; Jump T ar ge t

    00 1 8 0 0 ; NMI V ec to r

    3.10 Stage 3: From stable loop in au-topoller registers to loading pay-loads.

    (480 bytes per second; 60 payload bytes per second.)We have transferred control flow to controller

    registers, but we aren’t done just yet. The controllerregisters are only eight bytes in size, and normallynot all bits are even controllable. However, there are

    some tricks we can play to control all the bits. First,even though a standard SNES controller only has 12buttons, the autopoller reads all 16 bits. Normallythe last four bits are controller type identificationbits. Since those bits are read from the controller,the controller can set those bits to whatever it likes,including changing those bits every frame. Second,the last four bytes of the register are read from thesecond data line that is normally not connected toanything unless there is a multitap device. It isn’tpossible to just connect a multitap device wheneverwe like as the game will softlock. Fortunately, it ispossible to just connect the second controller so that

    it shares all the other pins (+5V, ground, latch andclock), but use the second data pin instead the first.

    These two tricks allow controlling all 128 bits inthe controller registers which gives us 8 bytes of dataper frame. While this is a huge improvement overour Stage 1 effective data rate of a nibble per frameit still only amounts to a datarate of 300 bytes perframe because three of those 8 bytes need to be usedfor looping in the controller registers, leaving onlyfive bytes usable. (Although, as you’ll see, only onebyte of payload data can be sent per frame.)

    Specifically, to loop successfully in the controllerregisters we need to wait for the NMI induced in-terrupt in order to avoid the NMI happening at anunpredictable instruction (because the NMI trashesA) and then jump to the start of the controller reg-ister. Then there is issue that NMI is not initially

    20We considered putting the NMI code into the SGB packet receive buffer, which is a memory-mapped I/O register (andpresumably can be executed by the CPU). We decided against this since the SGB emulation in BSNES is quite questionableand we didn’t know if it would work, largely due to the difficulty of testing it.

    16

  • 8/19/2019 POC || GTFO, issue 10

    17/88

    enabled, even if the handler is set, so the first framehas to enable the NMI handler. Fortunately, thiscan be done rather compactly:

    1 l o o p :A9 81 LDA #$81

    3 8D 00 42 STA $ 42 00 ; S e t 0 x 42 00 = 0 x81 (a u t o p o l l e r e n a bl e d , IRQ d i s a b l e d , NMIena bled )

    CB WAI5 80 F8 BRA l oo p

    Since the code is idempotent, this is good time toswitch from sending input in once per frame to send-ing input in once per latch poll. The way the SGBBIOS polls the controllers is completely crazy, oftenpolling more than once per frame, polling too manybits, trying to poll but leaving the latch held high,etc. Because this is a somewhat common problemeven in other games, the bot connected to the con-

    troller ports has a mode where it synchronizes whatinput to send based on the edge of each video frame(i.e. 60ths of a second in a polling window) by keep-ing track of how much time has elapsed; if the gameasks for input more than once on the same framewe give it that frame’s input again until we knowit is time for the next frame’s polls, which meanswe can follow the polling no matter how crazy it is.The obvious tradeoff is that this mode is limited to8 bytes per frame with 4 controllers attached, so weneed to switch the bot’s mode to one that is strictlypolling based, sending the next set of button presseson each latch. Making that transition can be a bitglitchy considering it was added as a firmware hackbut because this piece of code is idempotent we can

     just spam the same input several times as we onlyneed it to hit in the range. This happens from frame12117 to 12212 in the movie.

    We now have a stable loop in the controller reg-isters that we can use to poke some code into RAM.The five bytes per frame is enough to write one byteper frame into an arbitrary address in first 8kB of the SNES’s RAM:

    1 LDA #$xxSTA $yyyy

    This assembles to five bytes,   A9 xx 8D yy yy.Finally, after the writes, we can use  JML (four bytes)

    to jump to the desired address. Since the DMG isstill playing some annoying tunes, the first order of business is to try to crash it. Writing  00 to the clockcontrol/reset register at   0x6003  should do the trickby stopping the DMG clock, and in fact this worksin the LSNES emulator, but on a real console the an-

    noying tunes keep playing until the DMG corruptsitself enough to crash completely.21

    3.11 Stage 4: Increasing the datarateeven further.

    (3840 bytes per second.)

    One byte per frame is rather slow as it would takeus several minutes to write our payload at that speedso we poke the following routine (Stage 4) that reads8 bytes per frame from the autopoller registers andwrites it sequentially to RAM, starting from  0x1A00

    until  0x1B1F into address  0x19000.SEP #$30 ; S et 8−bi t A a nd X/Y

    2 LDA #$ 01 ; S e t 0 x 4 20 0 = 0x 01; ( a u t o p o l l e r e n , NMI d i s )

    4 STA $4200REP #$ 10 ; S et 16−b i t X/Y , k ee p A 8−b i t .

    6 LDY #$ 1A 00 ; L oa d a d d r e s s t o w r i t e t o .w a it_vbla nk_s ta r t :

    8 LDA $4 21 2 ; W ait u n t i l v bl an k s t a r t s .BPL wait_vbl ank_start

    10 wait_vblank_end :LDA $4 21 2 ; W ait u n t i l v bl an k e nd s , s o t h e

    12 ; new c o n t r o l l e r v a l u e a r r i v e s .BMI wait_ vblank_ end

    14 LDX #$ 42 18 ; S t a rt a d dr e ss o f c o n t r o l l e r r e g

    .LDA #$ 00 ; MVN c o p i e s 1 6−b i t a mo un t o f  b yt es , e ve n w it h A b e in g 8 b i t .

    16 XBA ; So en su re th at the hi gh b i ts a rezer o .

    LDA #$07 ; A = 7 , copy 8 b yt es .18 PHB ; MVN c ha ng es t h e da ta bank

    r e g i s t e r   , s o s av e i t .MVN $7E , $ 00 ; Copy t h e 8 b y t es f ro m 0

    x4 2 18 to RAM. Y is   auto−incr emented .20 PLB ; Re st or e t he dat a bank   r e g i s t e r .

    CPY #$ 1B 20 ; H av e we r e a c h e d 0 x 18 20 ?22 BNE w a it _ vb l an k _s t ar t ; I f no , w a it a f r am e

    a nd r e a d a g a i n .JML $7E1A08 ; Jump t o r e ad p a yl o ad .

    As machine code,   e2 30 a9 01 8d 00 42 c210 a0 00 1a ad 12 42 10 fb ad 12 42 30 fb

    21It’s not a surprise that it behaves differently in the emulator, as the SGB emulation accuracy in BSNES is questionablein a lot of places; it’s possible that the emulator is triggered on a different edge of the clock than real hardware or somethingsimilar. Regardless, on real hardware the DMG eventually crashes in a way that makes it stop producing sound and while it’sabout the equivalent of driving a car into a brick wall instead of hitting the brakes it at least gets the job done.

    17

  • 8/19/2019 POC || GTFO, issue 10

    18/88

    a2 18 42 a9 00 eb a9 07 8b 54 7e 00 ab c0

    20 1b d0 e4 5c 08 1a 7e.Why jump to eight bytes after the start of the

    payload? It turns out that code loads some junkfrom what is previously in the controller registerson the first frame, so we just ignore the first few

    bytes and start the payload code afterwards. Eightbytes per frame still isn’t fast enough, so the rou-tine this code pokes into RAM is another loader rou-tine that uses serial controller registers to read eightbytes eight times per frame, for total of 64 bytes perframe.

    Let’s take a look at the Stage 5 payload:

    1 ; 0 00 0 => C u rr e nt t r a n s f e r a d d r e s s .; 0 00 2 => T r a n s f e r e nd a d d r e s s .

    3 ; 0 00 4 => B l o ck s t o t r a n s f e r .; 0 00 6 => C u r r en t t r a n s f e r b an k .

    5 ; 0 00 8 => 0 : T r an s f er n ot i n p r o g r es s .; 1 : T r a n s f e r i n p r o g r e s s .

    7 ; 0 00C => B l o c k s t r a n s f e r r e d .

    ; 0 01 0 => Jump v e c t o r t o n e xt i n c h a i n .9 ; 0020−0027 => Buf fe r

    ; 0 08 0−00BF => Bu ff er .11

    S t a r t :13 NOP ; 8 NOPs ,   f o r   t h e j un k a t s t a r t .

    NOP15 NOP

    NOP17 NOP

    NOP19 NOP

    NOP21 SEI

    LDA #$ 00 ; A u t op o l l o f f , NMI an d IRQ o f f .23 STA $420 0

    25 REP #$30 ; 16−bi t A/X/Y.

    27 LDA #$0000 ; I n i t i a l l y no t r a n sf e r .STA $0008

    29frame_loop :

    31

    SEP #$2033 n o t_ i n_ v bl a nk : ; W ai t u n t i l n e x t v b l a nk e n d s

    LDA $421235 BPL not_in_vblank

    in_vblank :37 LDA $4212

    BMI in_vbl ank39 REP #$20

    41 LDA #$0008STA $0004

    43 LDA #$0000STA $000C

    45rx_block :

    47 LDA #$0001

    STA $401649 LDX #$0003

    latch_high_wait :51 DEX

    BNE latch_high _wait53 STZ $4016

    LDX #$000455 latch_low_wait :

    DEX57 BNE latch _low_wai t

    59 LDA #$0000STA $0020

    61 STA $0022STA $0024

    Figure 9 – Now using four controllers!

    18

  • 8/19/2019 POC || GTFO, issue 10

    19/88

    63 STA $002 6

    65 LDY #$00 10read_loop :

    67 LDA $401 6PHA

    69 ; B i t 0 => 0 0 2 0 , B i t 1 => 0 0 2 4 ,; B i t 8 => 0 0 2 2 , B i t 9 => 0 02 6

    71 BIT #$0001BNE b0n z

    73 LDA $002 0ASL A

    75 BRA b0db0nz :

    77 LDA $002 0ASL A

    79 EOR #$00 01b0 d:

    81 STA $002 0

    83 PLAPHA

    85 BIT #$0002BNE b1n z

    87 LDA $002 4ASL A

    89 BRA b1db1nz :

    91 LDA $002 4ASL A

    93 EOR #$00 01b1 d:

    95 STA $002 4

    97 PLAPHA

    99 BIT #$0100BNE b8n z

    101 LDA $002 2ASL A

    103 BRA b8db8nz :

    105 LDA $002 2ASL A

    107 EOR #$00 01b8 d:

    109 STA $002 2

    111 PLABIT #$0200

    113 BNE b9n zLDA $002 6

    115 ASL ABRA b9d

    117 b9nz :LDA $002 6

    119 ASL AEOR #$0001

    121 b9d:STA $002 6

    123DEY

    125 BNE rea d_l oop

    127 ; Move t h e b l oc k f ro m 0 02 0 t o i t s f i n a l p l a c e

    LDA $000C129 ASL A

    ASL A131 ASL A

    CLC133 ADC #$0080

    TAY135 LDX #$00 20

    LDA #$0007137 MVN $00 , $00

    139 ; I n cr e me n t t h e c o u n te r a t 0 00C ,; d ec re me nt t he c ou nt a t 0 0 04 .

    141 ; I f no more b l oc k s , e x i t .LDA $000C

    143 INASTA $000C

    145 LDA $0004DEA

    147 STA $0004BEQ exit_rx _loop

    149 JMP rx_bl ockexit_rx_loop :

    151

    LDA $0008153 BNE do in g _tr a ns fe r

    ; Okay , s e tu p t r a n s f e r .155 LDA $0082

    CMP #$FF157 BMI not_jump

    ; T hi s i s jump , c op y t h e a d dr e s s .159 STA $12

    LDA $0080161 STA $10

    BRA ou t163 not_jump :

    LDA $0 080 ; S t a rt i n g a dd re ss .165 STA $0000

    LDA $0 082 ; Bank .167 STA $0006

    LDA $ 00 84 ; E nd in g ad d re s s .169 STA $0002

    171 ; S e l f  −m o di f y t h e mov e .LDX #move_inst ructi on

    173 LDA $0006AND #$FF

    175 STA $01 ,X

    177 ; E nt er t r a n s f e r .LDA #$0001

    179 STA $0008

    181 ; S e e y ou n e xt f ra me .JM P no _r es et_tr a ns fer

    183

    d o i n g _ t r a n s f e r :185

    ; Copy t h e s t u f f t o i t s f i n a l p l a c e i n WRAM.187 LDY $0000

    LDX #$0080189 LDA #$003 F

    PHB191 mo ve_ins tr ucti o n :

    MVN $ 40 , $ 00 ; B og us b ank , w i l l b e

    19

  • 8/19/2019 POC || GTFO, issue 10

    20/88

    m o d i f i e d .193 PLB

    TYA195 STA $000 0

    CMP $00 02197 BNE no _r es et_t r a ns fe r

    STZ $0 00 8 ; End t r a n s f e r .199 no _r es et_tr a ns fe r :

    ; N ex t f r am e .201 JMP fram e_l oop

    out :203 JMP [ $10 ]

    3.12 Stage 5: Transfers of data inblocks with headers.

    (3,840 bytes per second.)This routine is rather complex, so let’s review

    some of its trickier parts.

    The serial protocol works by first setting thelatch bit (bit 0) in   0x4016, then clearing it, thenreading the appropriate number of times from0x4016  (port #1) and  0x4017   (port #2). Bit 0 of the read result is the first data line value, while bit1 is the second data line value. After each read, theline is automatically clocked so the next bit is read.The two port latch lines are connected together; bit0 of  0x4016 controls both.

    The bot is slow, so we wait after setting/clearingthe latch bit. We properly reassemble the input inthe usual order of the controller registers, since wehave CPU time available to do that. Since we read

    16-bit quantities, port 0x4017 is read as high 8 bits,so the data lines there appear as bits 8 and 9.

    To handle large payloads, the payload is dividedinto blocks with headers. Each header tells wherethe payload is to be written, or, if it is the last block,where to begin execution.

    The routine uses self-modifying code: The sourceand destination banks in MVN are fixed in code, butthis code is dynamically rewritten to refer to correcttarget bank.

    3.13 Automating the Movie Creation

    Since manually editing, recompiling and transform-ing inputs gets old very fast when iterating payloadROMs, tools to automate this are very useful. Thisis the whole reason for having Stage 5 use blockheaders. Furthermore, to not have one person do-ing the work every time, it’s helpful to have a toolthat even script-kiddies can run. The tool to do this

    is a Lua script that runs inside the emulator (TheLSNES emulator has built-in support for runningLua scripts, with all sorts of functions for manipu-lating the emulator.)

    1 d o f i l e ( " sgb−a r b i t r a r y w r i t e . l u a " ) ;

    3 make_mo vie = fun cti o n ( f i l ena m e )w r ite_s g b_da ta ( " s ta g e4 . da t" ) ;

    5 wri te _8by te s_d at a (" s ta ge 5 . dat " ) ;w r i t e _ x f e r _ bl o c k ( f i l e n a m e , 0 x 80 00 , 0

    x7E8000 , 0x4000 , 8) ;7 w ri te _x fe r_ bl oc k ( f il en am e , 0x10000 ,

    0x7F8000 , 0x7A00 , 8) ;write_jump_block(0 x7E8051 , 8) ;

    9 p r i n t ( "Done" ) ;en d

    This code, the main Lua script, refers to fourexternal files. “stage4.dat” contains the memorywrites to load the Stage 4 payload from Section 3.11while executing in the controller registers.

    This file contains the Stage 4 payload, plus theill-fated attempt to shut up the DMG. (As notedpreviously, it dies on its own later.) The first linecontaining  0x001900 is the address to jump to afterall bytes are written.

    2) “ stage5.dat”, which is the machine code cor-responding to the Stage 5 loader.

    3) A filename taken as a parameter, which is thepayload ROM to use. As you can see, the Lua scriptfixes the memory mappings, but this is okay, as thoseare not difficult to modify.

    The specified memory mappings copy a sixteenkilobyte byte region starting from file offset   0x8000into   0x7E8000, and the   0x7A00  byte region start-ing from offset  0x10000   into  0x7F8000. (The first32kB is assumed to contain initialization code forstand-alone testing, but we don’t care about that.)

    4) “sgb-arbitrarywrite.lua”, which is just afunction library.

    −−sg b−a r b i t r a r y w r i t e . l u a2 l o = f u n c t i on ( a )   return   bi t .ba nd( a , 0 xFF) ;

    en dmid = f u n c t i o n ( a )   return   bi t . band( bi t .

    l r s h i f t ( a , 8 ) , 0xFF ) ; e nd4 h i = f u n c t i on ( a )   return   b i t . b and ( b i t . l r s h i f t

    ( a , 1 6 ) , 0 xFF ) ; e nd

    6 s e t 8 = f u n c t i o n ( o b j , p or t , c o n t r o l l e r , i nd ex, v a l )

    f o r   i =0,7   do   o bj : s et_butto n( po r t ,c o n t r o l l e r , i n de x + i , b i t . t e s t _ a l l ( b i t .l s h i f t ( v a l , i ) , 1 28 ) ) ; en d

    8 e n d

    20

  • 8/19/2019 POC || GTFO, issue 10

    21/88

    10a dd _f ra me= f u n c t i o n ( a , b , c , d , e , f , g , h ,

    s y n c )12 l o c a l f r am e = m o vi e . b l an k _f r am e ( ) ;

    fr a me : s et_butto n (0 , 0 , 0 , s ync ) ;14 s e t 8 ( f ram e , 1 , 0 , 0 , b ) ;

    s e t 8 ( f ram e , 1 , 0 , 8 , a ) ;16 s e t 8 ( f ram e , 1 , 1 , 0 , f ) ;

    s e t 8 ( f ram e , 1 , 1 , 8 , e ) ;18 s e t 8 ( f ram e , 2 , 0 , 0 , d ) ;

    s e t 8 ( f ram e , 2 , 0 , 8 , c ) ;20 s e t 8 ( f ram e , 2 , 1 , 0 , h ) ;

    s e t 8 ( f ram e , 2 , 1 , 8 , g ) ;22 mo vie . a ppend_fra me( fr a me) ;

    en d24

    w r ite_s g b_da ta = fun cti o n ( f i l ena m e )26 l o c a l j um p_ ad dr es s = n i l ;

    l o c a l f i l e , e r r = i o . o pe n ( f i l e n am e ) ;28   i f    n o t f i l e t h e n e r r o r ( e r r ) ; e nd

    f o r   i i n f i l e : l i n e s ( )   do30   i f    i == " " t h e n

    e l s e i f n ot j um p_ ad dr es s t h e n32 j um p_ ad dre ss = t onu mb er ( i ) ;

    e l s e34 l o c a l a , b = s t r i n g . m atch ( i , "(%w+)%s

    +(%w+)" ) ;a = to number (a ) ;

    36 b = tonumber (b ) ;a dd _f ra me ( 0 x A9 , b , 0 x8D , l o ( a ) , m id ( a )

    , 0xCB , 0 x 80 , 0 xF 8 , t r u e ) ;38 end

    en d40 a dd _f ra me ( 0 x 5C , l o ( j u m p_ ad dr es s ) , m id (

     ju mp _a dd re ss ) , h i ( ju mp _a dd re ss ) , 0 , 0 , 0x 80 , 0 xF 8 , t r u e ) ;

    f i l e : c l o s e () ;42 end

    44 w r i te _ 8b y t e s_ d at a = f u n c t i o n ( f i l e n a m e )l o c a l f i l e , e r r = i o . o pe n ( f i l e n am e ) ;

    46   i f    n o t f i l e t h e n e r r o r ( e r r ) ; e ndwhile   t r u e   do

    48 l o c a l d at a = f i l e : r ea d ( 8 ) ;i f    n o t d a ta t h en   break ; en d

    50 l o c a l a , b , c , d , e , f , g , h = s t ri ng .b yt e ( d at a , 1 , 8 ) ;

    add_f rame ( a , b , c , d , e , f , g , h , t r u e ) ;52 end

    f i l e : c lo s e () ;54 end

    56 w r i t e _ x f e r _b l o c k = f u n c t i o n ( f i l e n a m e ,f i l e o f f s e t , t a rg e ta d dr e ss , s i z e , s pe ed )

    l o c a l f i l e , e r r = i o . o pe n ( f i l e n am e ) ;58   i f    n o t f i l e t h e n e r r o r ( e r r ) ; e nd

    f i l e : see k (" se t " , f i l e o f f s e t ) ;60   while   s i z e % ( 8   ∗   s p e e d ) ~ = 0   do   s i z e =

    s i z e + 1 ; endl o c a l e nd ad dr = b i t . b an d ( t a r g e t a d d r e s s +

    si ze , 0xFFFF) ;62   −−W ri t e t h e h e a d e r .

    a dd_fra me( lo ( ta r g et a dd r es s ) , mid(

    t a r g e t a d d r e s s ) , h i ( t a r g e t a d d r e s s ) , 0 , l o( e n d a dd r ) , m id ( e n da d dr ) , 0 , 0 , t r u e ) ;

    64   f o r   i = 2 , s p e e d   do   a dd _f ra me ( 0 , 0 , 0 , 0 , 0 ,0 , 0 , 0 , f a l s e ) ; end

    66   −−W ri te a c t u a l d at a .f o r   i = 0 , s i z e /8−1   do

    68 l o c a l d at a = f i l e : r ea d ( 8 ) ;i f    d at a == n i l t he n d at a = s t r i n g . char( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0) ; end

    70   while   #da ta < 8   do   d at a = da ta . . s t r i n g. char ( 0 ) ; e ndl o c a l a , b , c , d , e , f , g , h = s t r i n g .b yt e ( d at a , 1 , 8 ) ;

    72 add_frame ( a , b , c , d , e , f , g , h , i %

    Figure 10 – Why should we wait for next frame? Go sub-frame! (in green)

    21

  • 8/19/2019 POC || GTFO, issue 10

    22/88

    speed == 0) ;en d

    74 f i l e : c l o s e ( ) ;en d

    76w ri t e_ j um p _b l oc k = f u n c t i o n ( a d d r e s s , s p e e d )

    78 a dd_fra me( lo ( a ddr es s ) , mid( a ddr es s ) , hi (a dd re s s ) , 1 , 0 , 0 , 0 , 0 , t r ue ) ;

    f o r   i = 2 , s p e e d   do   a dd _f ra me ( 0 , 0 , 0 , 0 , 0 ,0 , 0 , 0 , f a l s e ) ; end

    80 end

    This script assumes that the loaded movie causesthe SNES to jump into controller registers and thenenable NMI, using the methods described earlier. Itappends the rest of the stages and payload to themovie. Also, since it edits the loaded input, it ispossible to just load state near the point of gainingcontrol of the SNES and then append the payloadfor very fast testing. (Otherwise it would take abouttwo minutes for it to reach that point when execut-ing from the start.)

    3.14 Stage 6: Twitch Chat Interface

    After successfully transferring our payload, execu-tion of the exploit payload (created by p4plus2) canofficially begin. There are three primary states tothe final payload: (1) Reset, (2) the Chat Interface,and (3) a TASVideos Webview.

    3.14.1 The Reset

    Because much of the hardware state is either un-known or unreliable at the point of control transferwe need to initialize much of the system to a knownstate. On the SNES this usually implies setting amyriad of registers from audio to display state, butalso just as important is clearing out WRAM suchthat a clean slate is presented to the payload. Oncewe have a cleared state it is possible to performscreen setup.

    In the initial case we set the tile data and tilemapVRAM addresses and set the video made to   0x01,which gives us two layers of 4–bit depth (Layers 1

    and 2) and a single layer of 2–bit depth, Layer 3.Layer 1 is used as a background which displays

    the chat interface, while Layer 2 is used for emojiand text. Layer 3 is unused. A special case for thetext and emoji however is Red’s own text which isactually present on the sprite layer, allowing code toeasily update that text independently.

    3.14.2 The Chat Interface

    Now that we have the screen itself set up and ableto run we need to stream data from Twitch chatto the SNES. But we only have 64 bytes per frameavailable to support emoji as well as the alphabet,

    numbers, various symbols, and even special triggersfor controlling the payload execution. This complex-ity quickly bogged down our throughput per frame,so we created special encodings for performance! Onaverage the most common characters will be  a-z  inlower case, which conveniently fit into a 5–bit en-coding with several more character to spare.

    The SNES has both 16–bit and 8–bit modes, soin 16–bit mode we can easily process three charac-ters with a bit to spare! But what about the rest of our character space? Well, we have a single bit re-maining and can set it to allow the remaining char-

    acters to be alternatively encoded. The alternateencoding allowed for two 7 bit characters, with anadditional toggle bit on the second character.

    BXXXXXXX XXXXXXXX2   i f  ( E)   goto   s p e c i a l _ e n c o d i n g

    i f  ( ! E )   goto   normal_encoding4 n or mal _e nc odi ng :

    0AAAAABB BBBCCCCC6 A = f u l l c h a r a c t e r 1

    B = f u l l c ha ra ct er 28 C = f u l l c h a r a c t e r 3

    s p e c i a l _ e n c o d i n g :10 1XXXXXXX SXXXXXXX

    i f  ( S )   goto   special_command

    12   i f  ( ! S )   goto   read_two_charactersread_two_characters :

    14 1AAAAAAA 0BBBBBBBA = f u l l c h ar ac t er 1

    16 B = f u l l c h a r a c t e r 2 ( used   f o rRed ’ s t e x t )

    special_command :18 1AAAAAAA 1BBBBBBB

    A = f u l l c h ar ac t er 120 B = Command byte

    22

  • 8/19/2019 POC || GTFO, issue 10

    23/88

    Figure 11 – Twitch chat!

    The most important command was   EE, cho-sen very arbitrarily, which meant “transition state.” The state transition would then toggle between theTASVideos website and chat interface. Also worthnoting is that any character with a value of  00 wasconsidered a null character and was not displayedfor synchronization purposes.

    3.15 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–colorimage, rather than the standard 16–color imagesfrom the prior section. The only caveat was that wehad to make a quick tool to remove duplicate tiles tooptimize the tile data to fit in VRAM. Backgroundcolors were controlled by tweaking the palette datarather than the image itself, as the SNES is verypoor at manipulating raw tile data due to its planarpixel format.

    3.16 Outside of the SNES

    The bot was connected to the console through thecontroller ports and a single wire going to the resetpin on the expansion board, meaning that from an

    external perspective the hardware was completelyunmodified. The bot itself was connected by a USBserial interface to a MacBook Pro running Linux.The source of the button presses being sent to thebot was in the form of a continuous bitstream repre-senting the state of all buttons for each frame. Once

    the payload was fully written and the Twitch chatinterface was complete the bitstream transitionedfrom being pre-created movie content to a bitstreamin the format the chat interface payload needed itin, with 5-bit and 7-bit encodings for characters andemoji. This was controlled by the python scripts22

    that relied on a script to identify when Red, theplayer inside of the Pokémon Red game, said var-ious things. The script also triggered things thatTASBot, the robot holding the replay device, wouldsay via the use of espeak, which allowed us to createa conversation between TASBot and Red.

    Finally, as part of the script we predefined pe-

    riods where we would “deface” the TASVideos web-site by changing it to different colors; this workedby showing an image on the SNES as well as liter-ally defacing the actual website. Finally, the scriptwas built with the ability to send commands to aserial-controlled camera, but truth be told we ranout of time to test it so we used a bit of stage magicto pretend like Twitch chat was interacting with thecamera by typing directions to move it, and we hada helpful volunteer running the camera for us.

    3.17 Live Performance

    These exploits were unveiled at AGDQ 2015. Theywere streamed live to over 100,000 people on Jan-uary 4th with a mangled Python script that didn’ttrigger the text for Red properly, then again on Jan-uary 11th with the full payload. The run was verywell received and garnered press coverage from ArsTechnica23 among others and resulted in substan-tially more interest in TASBot and the art of arbi-trary code execution on video games than had ex-isted previously. Most importantly, the TAS por-tions of the marathon where the exploit was fea-tured helped raise over fifty thousand dollars di-rectly to the Prevent Cancer Foundation. Overall,the project was a resounding success, well worth thesubstantial effort that our team put into it.

    22https://github.com/TheAxeMan301/PptIrcBot23Pokémon Plays Twitch: How a Robot got IRC Running on an Unmodified SNES by Kyle Orland

    23

  • 8/19/2019 POC || GTFO, issue 10

    24/88

    4 This PDF is also a Gameboy exploit that displaysthe “Pokémon Plays Twitch” article!

    The idea for this polyglot is to embed the con-tents of the previous article in this fine issue of 

    PoCGTFO in such a way that it shows on whenplayed as an LSNES movie. So now you can useyour copy of the journal to exploit your hardwareand read “Pokémon Plays Twitch” on your TV. Thisway, we hope to start a tradition of articles beingviewable on the hardware of the article!

    LSNES supports two kinds of movie files, whichmight better be thought of as input recording files.The older format is ZIP based and formally speci-fied, while the new one is binary and custom. Thenew binary format has no official specs, but start-

    ing a PDF with a ZIP signature would now triggerAdobe’s blacklistclearly, someone at the companymust have disliked something about one of our pre-vious releases. So the new, non-ZIP LSMV binaryformat is the one that we’ll use.

    The buffers for read and write calls for moviedata are straight out of the movie data in memory.One unintended benefit of the new format is thatit is much easier to write from SIGSEGV or similarsignal handlers. (The memory allocator cannot betrusted.)

    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 con-tent must be added in a dummy chunk early in theLSMV, and the ZIP and PDF footer must be addedat the end of the file, in another dummy chunk (seeincluded diagram).

    A clean version of the LSMV file has been sub-mitted to TASVideos.24 You can play this polygloton a modified LSNES with the hybrid emulationcore using BSNES and Gambatte or, if you havethe required hardware, on the real stuff!

    Be warned that none of these approaches is triv-ial. We include detailed howtos with the zip con-tents of this issue.25

    24http://tasvideos.org/4947S.html25unzip -j pocorgtfo10.pdf pokemon_plays_twitch/sgbhowto.pdf

    24

  • 8/19/2019 POC || GTFO, issue 10

    25/88

    25

  • 8/19/2019 POC || GTFO, issue 10

    26/88

    5 SWD Marionettes; or,The Internet of Unsuspecting Things

    by Micah Elizabeth Scott 

    Greetings, neighbors! Let us today gather to cel-

    ebrate the Internet of Things. We live in a worldwhere nearly any appliance, pet, or snack food cantalk to the Cloud, which sure is a disarming name forthis random collection of computers we’ve managedto network together. I bring you a humble PoC to-day, with its origins in the even humbler networkingconnections between tiny chips.

    5.1 Firmware? Where we’re going,we don’t need firmware.

    I’ve always had a fascination with debugging inter-faces. I first learned to program on systems withno viable debugger, but I would read magazines inthe nineties with articles advertising elaborate andpricey emulator and in-circuit debugger systems.Decades go by, and I learn about JTAG, but it’shard to get excited about such a weird, wasteful, andunder-standardized protocol. JTAG was designedfor an era when economy of silicon area was critical,and it shows.

    More years go by, and I learn about ARM’s Se-rial Wire Debug (SWD) protocol. It’s a tantalizing

    thing: two wires, clock and bidirectional data, giveyou complete access to the chip. You can read orwrite memory as if you were the CPU core, in factconcurrently while the CPU core is running. This isall you need to access the processor’s I/O ports, itson-board serial ports, load programs into RAM or

    flash, single-step code, and anything else a debug-

    ger does. I took my first dive into SWD in order todevelop an automated testing infrastructure for theFadecandy LED controller project. There was muchyak shaving, but the result was totally worthwhile.

    More recently, Cortex-M0 microcontrollers havebeen showing up with prices and I/O features com-petitive with 8-bit microcontrollers. For example,the Freescale MKE04Z8VFK4 is less than a dollareven in single quantities, and there’s a feature-richdevelopment board available for $15. These microsare cheaper than many single-purpose chips, andthey have all the peripherals you’d expect from anAVR or PIC micro. The dev board is even compat-ible with Arduino shields.

    In light of this economy of scale, I’ll even con-sider using a Cortex-M0 as a sort of I/O expanderchip. This is pretty cool if you want to write micro-controller firmware, but what if you want somethingwithout local processing? You could write a sortof pass-through firmware, but that’s extra complex-ity as well as extra timing uncertainty. The SWDport would be a handy way to have a simple remote-controlled set of ARM peripherals that you can drivefrom another processor.

    Okay! So let’s get to the point. SWD is neat,

    we want to do things with it. But, as is typicalwith ARM, the documentation and the protocols arefiercely layered. It leads to the kind of complexitythat can make little sense from a software perspec-tive, but might be more forgivable if you considerthe underlying hardware architecture as a group of tiny little machines that all talk asynchronously.

    The first few tiny machines are described in the250-page ARM Debug Interface Architecture Spec-ification ADIv5.0 to ADIv5.2 tome.26 It becomesapparent that the tiny machines must be so tiny be-cause of all the architectural flexibility the designerswanted to accommodate. To start with, there’s the

    Debug Port (DP). The DP is the lower layer, clos-est to the physical link. There are different DPs forJTAG and Serial Wire Debug, but we only need tobe concerned with SWD.

    We can mostly ignore JTAG, except for the pro-cess of initially switching from JTAG to SWD on

    26http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ihi0031c/index.html

    26

  • 8/19/2019 POC || GTFO, issue 10

    27/88

    Figure 12 – JTAG-to-SWD sequence timing

    systems that support both options. SWD’s clockmatches the JTAG clock line, and SWD’s bidirec-tional data maps to JTAG’s TMS signal. A magicbit sequence in JTAG mode on these two pins willtrigger a switch to the SWD mode, as shown in Fig-ure 12.

    SWD will look a bit familiar if you’ve used SPIor I2C at all. It’s more like SPI, in that it uses afast and non-weird clocking scheme. Each proces-sor’s data sheet will tell you the maximum SWDspeed, but it’s usually upwards of 20 MHz. Thishints at why the protocol includes so many asyn-chronous layers: the underlying hardware operateson separate clock domains, and the debug port maybe operating much faster or slower than the CPUclock.

    Whereas SPI typically uses separate wires fordata in and out, SWD uses a single wire (it’s inthe name!) and relies on a “turnaround” period toswitch bus directions during one otherwise wasted

    clock cycle that separates groups of written or re-turned bits. These bit groups are arranged into tinypackets with start bits and parity and such, usingturnaround bits to separate the initial, data, andacknowledgment phases of the transfer. For exam-ple, see Figures 13 and 14 to execute read and writeoperations and for all the squiggly details on thesepackets, the tome has you covered starting with Fig-ure 4-1.

    These low-level SWD packets give you amemory-like interface for reading and writing reg-isters; but we’re still a few layers removed from thekind of registers that you’d see anywhere else in the

    ARM architecture. The DP itself has some registersaccessed via these packets, or these reads and writescan refer to registers in the next layer: the AccessPort (AP).

    The AP could really be any sort of hardware thatneeds a dedicated debug interface on the SoC. Thereare usually vendor specific access ports, but usually

    you’re talking to the standardized MEM-AP whichgives you a port for accessing the ARM’s AHB mem-ory 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 tohave a handshaking scheme that looks much like

    any other memory mapped I/O operation. Writeto a register, wait for a bit to clear, that sort of thing. The lower level communications between DPand AP needs to be more efficient, though, so readsare pipelined. When you issue a read, that trans-action will be returning data for the previous readoperation on that DP. You can give up the extrathroughput in order to simplify the interface if youwant, by explicitly reading the last result (withoutstarting a new read) via a Read Buffer register inthe DP.

    This is where the Pandora’s Box opens up. With

    the MEM-AP, this little serial port gives you full ac-cess to the CPU’s memory. And as is the traditionof the ARM architecture, pretty much everything ismemory-mapped. Even the CPU’s registers are in-directly accessed via a memory mapped debug con-troller while the CPU is halted. Now everythingin the thousands of pages of Cortex-M and vendor-specific documentation is up for grabs.

    27

  • 8/19/2019 POC || GTFO, issue 10

    28/88

    Figure 13 – Serial Wire Debug successful read operation

    Figure 14 – Serial Wire Debug successful write operation

    5.2 Now I’m getting to the point.

    I like making tools, and this seems like finally theperfect layer to use as a foundation for somethinga bit more powerful and more explorable. Combin-ing the simple SWD client library I’d written earlierwith the excellent Arduino ESP8266 board supportpackage, attached you’ll find  esp8266-arm-swd,27

    an Arduino sketch you can load on the $5 ESP8266Wi-Fi microcontroller. There’s a README with

    the specifics you’ll need to connect it to any ARMprocessor and to your Wi-Fi. It provides an HTTP

    GET interface for reading and writing memory.Simple, joyful, and roughly equivalent security tomost Internet Things.

    These little HTTP requests to read and writememory happen quickly enough that we can builda live hex editor that continuously scans any visiblememory for changes, and sends writes whenever anyvalue is edited. By utilizing all sorts of delightfulHTML5 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

    27unzip pocorgtfo10.zip esp8266-arm-swd.zip

    28

  • 8/19/2019 POC || GTFO, issue 10

    29/88

    2 < l i>

    Turn the LED4 red ,

    g r een ,6 blue , cyan ,8 pink , w hi tei s h , or10 o f f

    12 < l i>Now ha l t the CPU a n d l e t ’ s h av e s om e

    sc ra tc h RAM:

    14 <p

    >16

    18 < l i>

    20 Load a s m a l l program

    22 i nt o t he s c r a t c h RAM

    24 < l i> Set the pr og ra m

    c o u n t e r 26 ()

    t o t h e t o p o f o ur p ro gr am28

    < l i>30 The PC sample r e g i s t e r ()

    t e l l s you whe re t he running CPU i s32

    < l i>34 Let th e CPU

    run ! ( o r t ry a

    s i n g l e s t ep )36

    < l i>38 While th e program i s r un ni ng , you can modi fy i t s d el ay v al ue :

    40

    Figure 15 – Single Wire Debug from HTML5

    29

  • 8/19/2019 POC || GTFO, issue 10

    30/88

    be used for a kind of   literate  reverse engineering anddebugging, in the way Knuth imagined literate pro-gramming. When trying to understand a new plat-form, the browser can become an ideal sandbox forboth investigating and documenting the unknownhardware and software resources.

    The included HTML5 web app, served by the Ar-duino sketch, uses some Javascript to define customHTML elements that let you embed editable hexdumps directly into documentation. Since a registerwrite is just an HTTP GET, hyperlinks can causehardware state changes or upload small programs.

    There’s a small example of this approach on the “Memory Mapped I/O” page, designed for the $15Freescale FRDM-KE04Z board. This one is handyas a prototyping platform, particularly since the I/O

    is 5V tolerant and compatible with Arduino shields.Figure 15 contains the HTML5 source for that demo.

    This sample uses some custom HTML5 ele-ments defined in  /script.js:   swd-async-action,swd-hexedit, and  swd-hexword. The  swd-async--action   isn’t so exciting, it’s really just a spe-cial kind of hyperlink that shows a pass/fail re-sult without navigating away from the page. Theswd-hexedit   is also relatively mundane; it’s justa shell that expands into many  swd-hexword   ele-ments. 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 thecontent is editable by default. These become simplebut powerful tools.

    5.3 Put a chip in it!

    While the practical applications of  esp8266-arm-swdmay be limited to education and research, I thinkit’s an interesting Minimum Viable Internet Thing.With the ESP8266 costing only a few dollars, any-thing with an ARM microcontroller could becomean Internet Thing with zero firmware modification,assuming you can find the memory addresses orhardware registers that control the parts you careabout. Is it practical? Not really. Secure? Defi-nitely not! But perhaps take a moment to considerwhether it’s really any worse than the other so-lutions at hand. Is ARM assembly and HTML5your kind of fun? Please send pull requests. Happyhacking

    30

  • 8/19/2019 POC || GTFO, issue 10

    31/88

    31

  • 8/19/2019 POC || GTFO, issue 10

    32/88

    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 pintsof IPA. An serial entrepreneur plied me with com-pliments, alcohol and assurances of a budget wor-thy of my hourly rate to take an off-the shelf deviceand build a sales-pitch demo in support of his natalcompany’s fund-raising and growth plan. The goalwas to take approximately zero available fabricationresources other than myself and spend a couple of months to make a universally approachable, easy touse demonstration prototype for a (now utterly de-funct) startup’s flow strip technology with a hack-a-thon patented Internet-of-Things interface. The tar-get was an entry straight out of PC Magazine’s  The Secret World of Embedded Computers , the thing noactive neighbor should be withouta handy-dandyoff the shelf CVS digital pregnancy test.

    6.1 Fast, Cheap, and Easy

    Head on down to your local pharmacy, and virtuallyevery store will carry a nifty brand of digital preg-nancy tests. All of these tests are basically iden-tical (inside and out), and the marketing strategyis simple. Humans are bad at reading analog in-puts, so when your time comes, let technology easeyour mind whether you, the user is stressed to thebreaking point trying to get pregnant or if you’re inthe boat of desperately hoping you’re sterile. “Ohgod, 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 pregnantwith mutant fish babies.” 28

    Now, it doesn’t matter which brand you buy forthis exerciseas far as I can tell, they’re all basedon the same two-chip solution built around a HoltekHT48C06 microprocessor. And you can guess at thefunction without cracking the case – just go buy one(for extra bonus points, look as underaged as possi-ble) and look at the test strips themselves.

    Remember, this OTS technology is extra cool be-cause back in the day, instead of peeing on a stick,women suspected of pregnancy29 had to have theirurine injected into a rabbit in order to assess preg-

    nancy before the onset of “the quickening.” If youthink it’s hard telling the difference between ‘+’and ‘–’, you definitely haven’t had to divine yourfuture livelihood from the appearance of leporid en-trails. And for extra bonus by the Theory Of Cyber-Extension, every time you use a digital pregnancytest, a cute bunny Tamagotchi is saved from certaindeath.

    6.2 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’ (changescolor) in any liquid from water to bourbon, and theother one is a test stripe that only fires when suffi-cient concentrations of the hormone hCG are present

    28The mutant fish baby thing is kind of true according to developmental biology, but that’s not really our focus today.29Fun fact : Eve was the first hacker and Cain was her first 0-day. Humankind is the ultimate Trojan. Since Cain was such

    a dick in the Biblical sense, the hacking community has carried his mark of social stigma until this very day.

    32

  • 8/19/2019 POC || GTFO, issue 10

    33/88

    in the fluid sample. (hCG stands for Human Chori-onic Gonadotropin, named because scientists snickerat words like “gonad.”) You can use the strips with-out the digital tester, because all you’re being soldis 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. Itturns out that $50 and getting at least one pregnantwoman to pee on a test strip can end up for an en-tertaining couple of evenings at the old workbench.

    Following these instructions, with enough time,patience and abstinence, you’ll be able to make yourown legitimate-looking pregnancy test that works onmen and women alike! Or jazz it up to say “HI MOM” in no time.

    6.3 Teardown

    To open the case of a digital pregnancy test (DPT),take a nickel or quarter, place it in the detent in theinjection molded case, and gently twist. The modelof DPT I did most of my work with was the generic

     “CVS Clear Results,” test – the mechanical specificsmay vary from brand to brand, but the nicest part of the cheap injection-molded plastic is that the shellparts are universally thin-walled and toleranced tosnap-fit together, which makes it easy to snap themapart without visibly damaging the case.

    Inside that case, there will be a circuit boardthat has another multi-piece injection-molded as-sembly of ABS plastic, press-fitted into mounting

    holes on the PCB. This is the test strip alignment/e- jection mechanism.30 For my purposes, I removedthis semi-destructively, by twisting off the retentionpins on the back side of the PCB. I wanted to save

    the housing for when I rebuilt the test with my owninternal electronics, to be virtually indistinguish-able from the stock pregnancy test but with addedentrepreneurial functions. This strategic re-use of injection molded parts and hard-to-design mecha-nisms adds that special professional flair to demon-

    stration prototypes.Once you’ve got the holder off, you’ll uncover

    an activation switch and the analog optical sen-sor (made of two photodiodes and three LEDs), aPLL (used only for its voltage-controlled oscillator)IC, the aforementioned Holtek HT48C06, a 3V bat-tery and a custom LCD. You can either look upthe battery type to confirm it’s 3V, or just readthe CE-mark label on the outside of the DPT thatlists the part number, lot data, confirmation thatthis test is made by SPD GmbH out of Geneva,Switzerland (made in China), and that the test runson 3V DC. Safety first, kids. Also convenient: if 

    you peel up this label, you’ll see holes in a pat-tern of the case that line up with un-tinned pads onthe PCB. These are the calibration and test pointsfor the Holtek, which means if you prefer firmwarereverse-engineering to hardware reverse-engineering,you can go fiddle with the insides  from  the outside.

    By the by, that label isn’t tamper-evident. Youcan easily replace it. Don’t get any ideas!

    6.4 Schematic

    Flick the little button, and you’ll see the whole test

    light up (with or without a strip). The LEDs strobe,the LCD thoughtfully blinks its “thinking” icon, anda scope or DMM will show plenty of pin activityuntil the test errors out because you just set it off 

    30unzip pocorgtfo10 pregpatent.pdf

    33

  • 8/19/2019 POC || GTFO, issue 10

    34/88

    without a valid test strip. I could have started prob-ing there, but I realized that an optical test requiresa dark environment, and I wanted to bring my testwires out through the conveniently placed unit-test-and-programming holes on the case. My ultimategoal was to test the unit under multiple conditionsto determine the internal logic. That meant makinga schematic.

    I don’t enjoy tracing out circuits with dark sol-dermask, and the DPTs are relatively cheap, so Igathered up the pinouts for each IC and then didmy physical net trace using graphic design tools.

    Step 1. Desolder all components from the PCB.Step 2: Scrub the pads with solder wick to get

    them nice and flat.Step 3. Using a razor blade or fine-grit sandpa-

    per, sand off the soldermask with loving attentionon both sides of the PCB.

    Step 4. Scan the PCB with high contrast.Step 5. Import the scans into an illustration tool

    of your choice. Color code the top vs. bottom scansto match your preferred layout scheme. Drop circleson the vias first . Then add the IC and passive pins.

    Then add your traces. Use the vias to register thetwo images on top of one another for a single layouttrace.

    Step 6. Annotate the trace with the referencedesignators from an intact PCB. Add your own netnames and pin labels. Use this to build a referenceschematic.

    6.5 Let’s Skip the Firmware

    Let’s walk through what this sweet little circuit isup to.

    First off, the Holtek micro is always on, albeitin sleep mode. The battery is sized for the shelf lifeof the device plus a couple of uses (three strips shipwith each one). When a test strip is placed in thetester, it mechanically triggers the switch which a)flags an interrupt to the microcontroller to wake itup out of sleep mode and b) enables power to thePLL and sense circuitry that would not otherwisebe powered. If you remove the test strip mid-test,it cuts power to the PLL and the micro will errorout, making it a bit of a pain to work with. Meh,

    34

  • 8/19/2019 POC || GTFO, issue 10

    35/88

    meh, power-saving feature and fault reporting dur-ing foreseeable misuse.

    Once all supplies are up, the Holtek samples thestate of the optical sensor four times a second fortwenty iterations, averaging the samples. In orderto sample the test strip, the Holtek drives the LEDs

    and then reads back the output state of the photode-tector, using the voltage-controlled-isolator (VCO)sub-function of that phase-lock-loop IC. The roleof the VCO is to convert the analog voltage fromthe photodetector into a square wave for easy edgecounting. Higher voltage implies a higher frequencyof edges. Because the micro controls the LED exci-tation timing, it can easily tell by edge counts whatcolor test strip the LEDs might be illuminating. It’spretty nifty.

    Because I wanted to build new electronics tofit inside the case of the original DPT and repro-duce a function similar to the original hardware andfirmware, I dove into the deeper specifics of how theDPT detects whether one or two blue stripes showup in that plastic clear-view window. The secret isstereoscopic vision enabled by time-division multi-plexing and the physical layout of the optosensor.The three LEDs are interdigitated with two parallelphotodiodes that are the base current sources in aPNP common emitter amplifier (D4, D5, Q2). TheHoltek enables each of the 3 LEDs (D1, D2, D3) se-quentially using a 25% LOW duty cycle waveformat 10kHz. The LEDs are strobed in a round-robinfashion and the Holtek samples the result via the

    VCO.When any one of the three LEDs is strobing, theinduced current in the photodiode causes the filtercap on the output of Q2 to charge. The LED’s lightcauses charging, while discharging occurs while theLED is off. Because the Holtek excites the LEDsintermittently, the output of the photodetector is asawtooth wave. The period of the sawtooth is theLED drive interval, while the peak and trough of the sawtooth wave correspond to the colorimetricintensity of the test stripe that appears and/or theamount of mis-alignment between the photodetectorand the LED array.

    But how does this produce stereoscopic vision,you ask?

    For the same background test strip, when D1 ison, the sawtooth peak-to-peak amplitude will be dif-ferent than when D3 is on, giving the sensor someability to resolve spatial light sources. Because theLEDs are independently addressable, it also means

    that the Holtek can discriminate between a coloredstripe hanging over D5 (stripe #1) versus one hang-ing over D4 (stripe #2). Also, all apologies forthe fact that the reference designator order for thediodes makes no physical sense. It’s not how I’d de-sign the board, but it apparently took eight revisions

    for the manufacturer to get this far.

    6.6 Schrödinger’s Rabbit

    Okay, so if you’re pregnant, it works like this.

    Just kidding, folkshere’s what the DPT is doing.Photodetectors Test StripeD3 D1 D2 ST1 ST2

    PREGO L H L CNTRL PREGOCNTRL L H H CNTRL . . .ERROR H H L . . . PREGOBLANK H H H . . . . . .

    Remember that a high PD voltage implies moreedges counted by the Holtek per excitation cycle.The Holtek uses this  and  sequencing to tell if you’repregnant. Based on the chemistry of the test stripe,the test expects the CNTRL stripe to fire first.

    If only the CNTRL stripe firescongratulations,you aren’t pregnant! Again, due to chemistry, thePREGO stripe ought to always fire second, if at all.If the stripes fire out of order, that’s an error. If thePREGO stripe fires but the CNTRL stripe doesn’t,that’s an error. If no stripe fires, that’s an error.

    The factors that contribute to setting the DE-TECT vs. NO-DETECT threshold for “how manyedges do I expect to count if the rabbit died” are(1) the distance from each of the three LEDs to eachof the two sensors, (2) the intensity of the LEDs,(3) the color of the LEDs (as that corresponds tothe sensitivity of the sensors for a given wavelength

    of light), (