Wednesday, August 16, 2023

DEF CON 31 - Payments Village - Card Hacking Challenge Write-up

Payment Village Issued Credit Card
At DEF CON 31 this year the Payments Village put on a Card Hacking Challenge. You were provided with a working credit card, a point-of-sale terminal (physical, or as an Android APK), and the village was running a "bank" server at www.paymentvillageprocessing.com.

There were 3 main goals:

  1. Steal $100,000 from the card
  2. Commit other fraudulent operations
  3. Steal fifteen cards from the SoftPOS

Setup

With data flowing through 3 hops in this challenge, I had my choice of intercepting NFC traffic between the card and the POS, modifying the APK itself, intercepting traffic between the POS and the server, and/or directly attacking the server.

I chose to intercept (and modify) HTTP traffic between the POS client and bank server. First I setup the provided SoftPOS.apk on an Android phone (side loaded via adb). Then I setup the interception proxy using Burp Suite. 

SoftPOS main screen
Step-by-step:

  1. Phone 1: Setup WiFi tether to mobile network so all devices can talk to each other
  2. Laptop: Connect to WiFi tether on Phone 1
  3. Laptop: Listen with Burp Suite proxy on WiFi IP
  4. Laptop: Open up firewall to allow incoming connections
  5. Phone 2: Connect to WiFi tether
  6. Phone 2: Configure proxy on that WiFi connection
  7. Phone 2: Restart SoftPOS to pickup new proxy settings
  8. Phone 2: Run a payment through SoftPOS and it shows up in Burp Suite on laptop

Capture HTTP Traffic

With the HTTP proxy in place we can view what successful and unsuccessful payment attempts look like. A successful payment sends multiple fields as HTTP query args in a GET request.


These query parameters break down to:

amount
trans_type
9f15 (Merchant Category Code)
9f34 (Cardholder Verification Method Results - CVM)
9f36 (Application Transaction Counter)
9f26 (Transaction Cryptogram)
82 (Application Interchange Profile)
5a (Application Primary Account Number - PAN)
57 (Track2 Equivalent)
9f37 (Unpredictable Number)
5f2a (Transaction Currency)
9a (Date)
9f02 (EMV Amount Field)
type

Note: There are 2 different "type" fields and 2 different "amount" fields, which will be important later.

Here's a successful response:


💡 Thank you Payment Village organizers for keeping the traffic over HTTP so that I could learn about the EMV protocol and not spend half a day debugging TLS MitM issues!

Challenge 1 - Steal $100,000 from Card

Let's get hacking. We need to spend $100,000 so let's run a single transaction for that amount with the card on the POS.

Error: The POS app won't let us charge more than $10 at a time.

Ok, let's intercept the HTTP traffic of a successful $10 payment, then replay the payment packet to the server changing the amount from $10 to $100,000.

Error: The server won't let us replay packets.

Each request has an incrementing counter in field 9f36, so the server knows if a request is replayed. Let's increment that ourselves and replay it.

Error: Auth failure. We've changed a field that is signed by the cryptogram. i.e. the server can detect that the packet was tampered with.

We can recompute the cryptogram if we can extract some key material from the CHIP on the card. But we have a shortcut! The bank server, when receiving a bad cryptogram erroneously returns the expected cryptogram in the AC field of the error message.


We just have to make every request twice. Once with a failure to get the correct cryptogram, then a second time placing the returned cryptogram in our 9f26 field.

Now, replay the $10 transaction, but increment the counter, and update the cryptogram, and change $10 to $100,000 in the amount field.

Error: The server also detects this amount field being tampered with.

"We become safer than Visa or MasterCard! We do not allow random merchants to modify the final amount field from the amount, signed by the chip"

Let's try changing both the amount and 9f02 fields to $100,000 so that they match. 

Error: For that amount of money we need further verification from the client.

Our tampered amount is accepted, but there's additional verification required for that size of transaction.

This verification is done entirely between the card and the POS and is a simple boolean bit field when sent to the bank server. So we flip it to "verified". We claim that the POS verified the card pin by changing the 9f34 (Cardholder Verification Method Results - CVM) field from 1f0302 to 010302.

Changing 1f to 01 tells the server "Plaintext PIN verification performed by ICC". See the First Contact: New vulnerabilities in Contactless Payments whitepaper, page 18, for full details.

Error: Not enough money in the account to charge $100,000.

Ok, we can charge more than $10, but less than $100,000, let's try $10,000. 

Success$10,000 spent.

Now just repeat that 9 more times.

Success$100,000 spent.

Challenge 2 - Commit other fraudulent operations

While fuzzing various fields in the original request, an error is returned.

"Transaction type should be purchase or refund."

Alright, let's change "purchase" to "refund" in both type fields:

trans_type=EMV to trans_type=refund
and
type=purchase to type=refund

You must attempt a refund with a replay of a successful transaction (same ATC and amount) as we can only refund a charge that was made. But we can't refund immediately.

Error: Refund can't be issued at the moment

The server has some time delay before refunds are allowed. Wait ~1 hour and try again.

Success

Challenge 3 - Steal fifteen cards from the SoftPOS

Browsing to the directory base at www.paymentvillageprocessing.com, shows 3 other .php scripts.


Making a GET request on host_reset.php returns a MySQL input validation error indicating there's probably a SQL injection bug here that will allow us to dump stored card numbers. 

"Fatal error: Uncaught mysqli_sql_exception: Incorrect integer value: '' for column 'EUR_Trans' at row 1 in /var/www/www.paymentvillageprocessing.com/mysql.class.php:91 Stack trace: #0 /var/www/www.paymentvillageprocessing.com/mysql.class.php(91): mysqli_query() #1 /var/www/www.paymentvillageprocessing.com/host_reset.php(15): MySQL->execute() #2 {main} thrown in /var/www/www.paymentvillageprocessing.com/mysql.class.php on line 91"

But I'm at DEF CON and I'm sitting with a lot of nice, fun, hackers in the Payment Village AND I have an intercepting proxy on my personal POS. So I just walked around and asked folks nicely if I could scan their card, while my laptop grabbed their numbers, just like a real skimmer would. 18 folks said yes.

Skimmed payments captured over the WiFi

Success

PAN,Date
1016438914381100,230811
1016438914381118,230811
1016438914381126,230811
1016438914381134,230811
1016435898071137,230811
1016439201951142,230811
1016435898071079,230811
1016433175481186,230811
1016437680601097,230811
1016435539211100,230812
1016435656631130,230812
1016435898071137,230812
1016433175481038,230812
1016437112791045,230812
1016433175481053,230812
1016437112791060,230812
1016433175481186,230812
1016435656631098,230812

Gratitude

Thank you Leigh-Anne, Tim, and Ali for a realistic, engaging challenge. The whitepaper and write-ups from last year were very helpful to get started. And with no leaderboard, other hackers were really collaborative, and we could learn about payments together instead of competing.

See you again next year!

References

Tuesday, March 20, 2018

No Airline Handles Ticketing of Infants Well

I've flown with my young children multiple times on both domestic and international flights. We've flown on Alaska, Delta, American, and Qantas. None of them have been smooth and not because of the baby.

Most airlines let you have a child on your lap, without a booked seat, if the child is under the age of 2 during the flight. When flying within the United States this is free, but you still have to add your child’s name to your ticket. When flying international, the above listed carriers require the child have a ticket, which costs 10% of the published fare, but comes with no seat. I don't know the intricacies of this policy; I just know that nobody seems to care about this 10% until you're about to get on the airplane.

Applause to Alaska, the only carrier I’ve flown that lets you add your infant to your ticket via their web site. All the others require you call in and speak to an agent. As a software developer, waiting on hold for 45 minutes, being told by an automated message that I “really should use the website” is especially frustrating. I would LOVE to use the website. Please let me add my infant right on the booking screen instead of as a manual addendum after the fact!

Add in award travel and things get worse. My wife and I recently booked an international flight with Alaska miles, where the second leg was on American Airlines. Our infant was listed on our itinerary from the beginning. At our layover airport, at the gate, 20 minutes before departure, with two squirming babies in our arms, we're told we never paid the 10% infant ticket fee. We could pay it then, plus an additional $45 “airport fee” since we're buying a last minute ticket from a gate agent, or not get on the airplane. Ever since airlines started charging for checked bags I often feel like I'm being nickel and dimed, but this was full out extortion.

Even on a fairly recent domestic Alaska flight, where I was pleasantly surprised I could add my infant to my ticket on their mobile app, while checking in, on my way to the airport, it didn't actually work. I checked the whole family in with the app. Then we checked our bags with an agent, went through security, boarded the plane, and in our seats right before the airplane door closed were asked, "Who's this baby?" Our child was not on the flight manifest and apparently not recorded anywhere in their system. We somehow snuck a baby on an airplane with no questions through 4 checkpoints.

From a process perspective infants flying seems to be common enough that most airline staff have heard of it, but not everyone knows how it works. From a software perspective it is a special case, lower priority, less tested, execution path. And even from the parents perspective the kids are only under 2 for a few flights and then it's normal full fare tickets. So I somewhat understand why ticketing my child never quite works. But still, the hardest part about flying with an infant shouldn't be buying them a ticket.

Wednesday, January 25, 2017

HTC 10 Won't Connect to T-Mobile International Data Roaming

I bought an unlocked HTC 10 through a 3rd party vendor and have enjoyed the phone. I use T-Mobile service because of their great value and their free 2G international data roaming. Unfortunately, I ran into trouble connecting to cellular data the first time I traveled outside the USA with my new phone.

After arriving in Hong Kong, I received the helpful T-Mobile text message telling me I had data roaming available:

"Welcome to Hong Kong! Your T-Mobile plan gives you unlimited data at 2G speeds, calls at 20 cents/min and free texts."

Text messages and phone calls were working, but cellular data refused to connect.

Troubleshooting steps I tried:
  • Confirmed data roaming is on
  • Put phone in airplane mode for 1 minute
  • Restarted phone
  • Tried manually connecting to every carrier. Only the automatically selected one worked
  • Enabled roaming via USSD code: #766#
  • Tried manually specifying each network type (2G, 2G/3G, 2G/3G/4G)
  • Tried my T-Mobile SIM in a different phone (worked)
  • Tried a local SIM from the roaming carrier (Hutchinson 3) in my phone (worked)
  • Tried a different T-Mobile SIM, that I know works, in my phone (didn't work)
  • Asked T-Mobile if there was any block on my number for international roaming (nope)
Much of this was suggested by the very helpful T-Mobile support team and though we whittled down the problem to something specific with my phone, they never determined the exact issue. Finally, HTC customer support suggested I check my APN settings. Sure enough, they were different between my 2nd working phone and my HTC 10.

There's a known issue with the LG G3 phone not having and not automatically downloading the correct APN settings to allow T-Mobile international roaming to work. Apparently, this is also true with my HTC 10 phone, though no amount of Googling mentions it.

I believe the HTC 10 is supposed to read its APN settings from the SIM card, but instead, when a new SIM card is inserted, it prompts the user for the carrier associated with this SIM. From this user selection it populates the APNs. It appears, this hard coded list is outdated, even after an update to Android 7.0.





With the problem finally understood, several sites mention how to manually enter an APN which enables roaming. The steps are:
  1. Open Settings > Mobile Data > Access point names
  2. Copy down the settings of the currently selected Access Point
  3. Create a new Access Point with:
    1. Name = RoamingAPN
      • This can be any name
    2. APN = epc.tmobile.com
    3. APN protocol = IPv4
    4. All other settings the same as the currently selected APN
  4. Save (with the triple dot menu)
  5. Select the new "RoamingAPN"
My HTC 10 connected within 15 seconds and displayed the H icon in the notification tray.  Though, you may need to reboot after making this change.

This worked for me and hopefully will help other HTC 10 owners.

References:

Saturday, January 14, 2017

Sense Home Energy Monitor App Won't Connect

I'm very excited to learn about my personal electricity usage with my Sense Home Energy Monitor, now that it's working, but installation did not go smoothly.

The Story


I physically installed the device in my electric panel as described in the install guide:
  1. Connect the WiFi antenna external to the box
  2. Plug in the black and red wires to a 20A, 240V breaker
  3. Clip the two current sensors around my mains  
I turned on the breaker, got a happy little chime from the orange box after about 20 seconds, and saw an internal light blinking. Easy.

Unfortunately, using the app to make an initial connection is where the frustration began.

The short story is that the device refused to connect to my WiFi router, until after it upgraded its software version, which it does over the WiFi connection... Catch 22.  But figuring out this problem was painful, due to a highly simplified phone app, almost no other physical interface on the device, and very slow tech support.

First try, Android app continually fails at "Verifying Install":


Second try, iPad app continually fails at "Registering":


Both apps after failing in two different spots, with no helpful error messages, gave a page that says "Try Again".

I tried this about 15 times, power cycling the device each time, until finally it worked from the iPad.  I made no changes of any kind between the failures, except trying again. So it's still a mystery why the 15th time WiFi connected. I was able to create a log in, get the app past initialization, and then I'm given this:


The device is "Offline".

So it managed to join my WiFi network, but can't send any packets (which I confirmed from the router). More power cycling, and switching to 2 different WiFi networks, and still offline. Thankfully, a friend also has a working Sense, showed me his app, and we noticed that my device software version was older than his.

Mine: 1.0.1277-be639d4-master
His:    1.1.1353-d08ad0f-master

So guessing/hoping that "fixed in the next version" was true, I turned on tethering on my phone, and tried connecting the device to it from my iPad. This worked and he device got online. Then I left my phone sitting next to my electrical panel, checking back periodically, if it had auto-updated itself. There is no "Update Software" option in the app.  After 24 hours and 82MB of data, my device now showed version 1.1.135.  Switching back to my normal WiFi network... it still didn't work! But remembering the first rule of Windows tech support, I turned it off then back on again, and hallelujah it showed "Online" and connected to my home network.




So after 4 days of troubleshooting, my Sense is now happily measuring and learning my energy usage.  We'll see what insights it comes up with over the next few weeks.

Troubleshooting


If you're having a problem getting your Sense to initially register, or after registration connect to your WiFi network, here are some tips:
  1. Try setup with both the Android and iOS app.  Though they look the same, they obviously work a little differently with the iOS app being more mature it appears.
  2. Set up a separate WiFi network, with a different physical router. Tethering my phone worked best for me. The device likes some WiFi access points and not others. 
  3. Once connected to a temporary WiFi network, leave the device alone for 24 hours to download updates. There is no way to force an update, you just have to wait.
  4. After software update, turn it off and back on, and reconnect to your original home network.

Closing Thoughts


I contacted Sense customer support while having this issue and while they were very courteous and helpful with basic debugging steps, they were not very responsive. Support is only available over email, no phone, and it took 48 hours for my ticket to even be answered initially. I'm guessing the small team is overwhelmed with recent publicity.

Here's the start of my feature request list for the device:
  • Better/any error information in the app when something fails. "Can't connect to WiFi" would've been a lot more helpful than "Try Again".
  • There's no "Upgrade Now" button in the app. Having one would've saved me 24 hours.
  • There's no hard reset, or even factory reset option in the software. Having this *may* have helped when switching from Android to iOS setup.

Sunday, October 2, 2016

TUM CTF 2016 - totp writeup

Challenge Name: totp
Point Value: 100 Base + 100 Bonus
Description: It’s time to thank Google™ for making the Internet more secure for all of us.
Tags: web

The challenge is a website with a personal diary and user database.  We can create accounts and post messages to our diary.  A public Users page is listed, which shows the admin email address.  It's likely we need to login as an admin account and view their personal diary to find the flag.



The catch is that account logins use a Google Authenticator time-based one-time password (TOTP).  Usually, these are used in conjunction with a user selected password, but this site uses only the TOTP for login.


The Google Authenticator Wikipedia article, provided in the challenge description, explains how TOTP generates a secret key (displayed in the 2D barcode) at first creation, and that key is used along with the current time to generate 6 digit codes using HMAC every 30 seconds.  Looking at the source for the registration page, we see an example of one of these keys.

<div class="col-sm-9">
    <img src="https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=otpauth://totp/dairy?secret=6PP3WKGNATQYEV2V5ELFQPMD&choe=UTF-8">

    <input type="hidden" name="secret" value="6PP3WKGNATQYEV2V5ELFQPMD">
    <input type="password" id="password" placeholder="One Time Password" password="password" name="otp" required class="form-control">
</div>

Though a Google API is generating the barcode, the 120-bit (base32) secret key is being generated by the challenge site.  If we can guess what secret key was generated when the admin account was created, then we can create TOTP codes based off the current UTC time and log in as admin.  I believe this was the intent of the challenge designers, as they've conspicuously provided the time the admin account was created on the Users page.

Registered at: 2015-11-28 21:21

The key we eventually recover also gives a hint that a poor random number was used.  Without source code, there is still a lot of guessing involved in how the random numbers are generated by the site.  So while I continued to investigate that, I also setup a brute force password checker to run in the background, and that found the answer.

Brute Force


The TOTP number is 6 numeric digits, which gives 10^6 possible combinations, or 1,000,000.  Not a difficult brute force attack.  However, the correct number the server will accept changes ever 30 seconds.  But since that number is based off a SHA-1 HMAC, it has an even distribution. Each number in that 1,000,000 is just as likely to be correct for 30 seconds as any other number.  Let's say we can check 10,000 of the 1,000,000 keys within every 30 second period.  If we check the same 10,000 passwords every time (say 000 000 to 010 000) then after 50 attempts (1,000,000 / 10,000 / 2) we should have guessed the right password.  That's 50 attempts * 30 seconds, or 25 minutes, which is not long at all for an online brute force attack.

We could script this, but Burp Intruder has most of the tools we need already.  First, I benchmarked how fast Burp could send login requests from my connection to the web server.  I settled on 25 threads, which on my Internet connection, over 30 seconds could make about 3000 attempts.  Meaning an attack time closer to 84 minutes.  Next, it's not easy to script Burp to restart an Intruder attack every 30 seconds, exactly on the :00 and :30 marks.  So, I went the even lazier approach of trying all 1,000,000 passwords in a row.  But since the password the server picks is an even distribution, this shouldn't hurt our attack time too much in practice.

Lastly, playing with the site while using Burp Proxy showed no difference in the response from the "POST /?target=login.php" message on an unsuccessful login vs a successful login. Instead, the PHPSESSID returned in the cookie, has server side state, which marks the login as successful.  So we'd need to do an extra "GET /" request after every POST to check for success.  Well that would slow down the attack another 2x, so instead we'll check manually every 30 seconds or so.

So the simplified steps for the brute force attack are:

1) Generate a file of every possible TOTP possibility:

$ for i in {0..999999}; do printf "%06d\n" $i >> totp_999999.txt; done

2) Start Burp Intruder with POST login requests against the web server using the generated file:



3) Periodically refresh your web browser using the same PHPSESSID cookie as Burp:

I got lucky after about 75,000 request / 13 minutes.

4) Collect the flag:




Sunday, August 7, 2016

OpenCTF 2016 - diskomatic writeup

Challenge Name: diskomatic
Point Value: 200
Description: It slices, it dices, it juliennes fries!
Tags: forensics

The challenge is a binary file with a forensics tags, so I assumed it would be pulling some data out of some other file format.

Step 1:  Unpack

 

$ file diskomatic-98757b0043b8aea77e9014cff8ead7b1
diskomatic-98757b0043b8aea77e9014cff8ead7b1: gzip compressed data, last modified: Mon Jun 22 00:08:37 2015, max compression, from Unix

Simple enough.

$ zcat diskomatic-98757b0043b8aea77e9014cff8ead7b1 > diskomatic.dat

$ file diskomatic.dat diskomatic.dat: DOS/MBR boot sector, code offset 0x58+2, OEM-ID "mkdosfs", FAT  1, Media descriptor 0xf8, sectors/track 32, heads 64, sectors 250368 (volumes > 32 MB) , FAT (32 bit), sectors/FAT 1941, serial number 0x20550574, label: "DISKOMATIC "

 

Step 2:  Mount Filesystem

 

So we have a FAT filesystem image.  Let's try mounting it and seeing what's inside.

$ sudo mount -t vfat ./diskomatic.dat ~/mnt/dos/
$ ls -la ~/mnt/dos
total 5
drwxr-xr-x 2 root  root   512 Dec 31  1969 .
drwxr-xr-x 3 grind grind 4096 Aug  6 12:41 ..
$ df -h | grep dos
/dev/loop0      122M   512  122M   1% /home/grind/mnt/dos
$ sudo umount ~/mnt/dos

Interesting so from the filesystem's perspective there are no valid files, but we have 122MB of something.

 

Step 3: Analyze the Binary

 

$ binwalk -e diskomatic.dat

DECIMAL       HEXADECIMAL     DESCRIPTION
--------------------------------------------------------------------------------
17787904      0x10F6C00       PNG image, 1600 x 900, 8-bit/color RGB, non-interlaced
34088942      0x20827EE       Minix filesystem, V1, little endian, 30 char names, 23429 zones

binwalk found a PNG file, but was unable to extract it.  Interesting... perhaps it is corrupted somehow. I don't know where the Minix FS detection came from, but it's a false positive.

So let's open up the file in a hex editor and take a look at location 0x10F6C00.

 

Step 4:  Hex Editor



The beginning of the file is as `file` advertised, a FAT32 partition table.  Let's go to location 0x10F6C00.


Here's the PNG header, with the first IDAT section but it is noticeably quite short.  Searching for IDAT we find many more of these sections.  Each one is exactly 512B, which I believe is the block size for FAT32.  So it seems we have a PNG file which has been fragmented and we need to piece it back together.  Well let's try the naieve approach, and just concatenate all the chunks.  We can do this from within the hex editor by cropping the file from location 0x10F6C00 onward and then doing a find and replace on all the \x00\x00\x00\x00 words with nothing.

We'll save this file as diskomatic.png and open it.


Well that didn't work. But the CRC error is a great hint.  PNG is a simple format with chunks split into just 4 fields.

Length Chunk type Chunk data CRC
4 bytes 4 bytes Length bytes 4 bytes

But you don't have to take my word for it, you can read the Wikipedia article.

Looking at the 512B blocks in the hex editor again, we see that the PNG chunks are split in the middle of the data section, leaving some data and the CRC for that data at the front of the next block.  So we have a fragmented file, but we have a method of determining in which order the pieces are supposed to fit back together by combining two blocks and then checking whether the CRC for the PNG chunk is correct.  So now we have an idea of the problem and a solution, but first we'll need to extract each block of the PNG file.

 

Step 5: Programmatically Extracting FAT32 Blocks

 

At first I just selected a few blocks in the hex editor and saved them as new files.  But after about 6 of these, with the location not moving much, I realized I'd probably need to automate this.

$ grep -abc IDAT diskomatic.dat
4976

Yep, I definitely don't want to copy'n'paste 5000 times by hand.  So I wrote some Python:
FILE = "diskomatic.dat"

def get_parts():
    fh = open(FILE, 'rb')

    parts = []

    # we know the location of the first part from `binwalk`
    fh.seek(0x010F6C00)
    p_idx = 0
    part = ""

    try:
        while True:
            block = fh.read(512)
            if len(block) == 0:
                break
            if block[0:4] != "\x00\x00\x00\x00":
                fh2 = open("parts/p"+str(p_idx)+".png.part", "wb")
                fh2.write(block)
                fh2.close()
                p_idx += 1
            offset = fh.tell()
            if offset % 0x100000 == 0:
                print "0x%x" % offset
    except EOFError:
        fh.close()

This writes all the blocks/parts out, 1 per file, and puts them in a directory called parts. After running this code we have 6238 files.

$ cd parts
$ ls | wc
   6238   56144  354468

 

Step 6:  Reassemble the Blocks

 

First I tested my hypothesis that all the blocks we needed were present, by programmatically concatenating every block with the first block, and was successful finding one block.

From that code, I moved on to checking every block against every other block, and constructing the correct ordering of blocks in a dictionary.  Then writing that string of blocks out into a single PNG file.  The full code, excluding the get_parts() function is:
#!/usr/bin/env python

import binascii
import struct

FILE = "diskomatic.dat"
NUM_CHUNKS = 6238
FIRST_PART = 0

def tokenize_chunk(data):
    length = struct.unpack("!I", data[0:4])[0]
    chunk = data[0:4+4+length+4]

    return chunk


def png_chunk_verify_crc(chunk):
    length = struct.unpack("!I", chunk[0:4])[0]
    ctype = chunk[4:8]
    data = chunk[8:8+length]
    crc = struct.unpack("!I", chunk[8+length:8+length+4])[0]

    # The CRC is a network-byte-order CRC-32 computed over the chunk type and
    # chunk data, but not the length.
    crc_c = (binascii.crc32(chunk[4:-4]) &amp; 0xFFFFFFFF)

    valid = (crc == crc_c)

    return valid


def read_parts():
    parts = []

    # XXX: magic number: that's how many chunks were in the original file
    for i in xrange(0, NUM_CHUNKS):
        fh = open("parts/p"+str(i)+".png.part", "rb")
        data = bytearray(fh.read())
        parts.append(data)
        fh.close()

    return parts


def compare_parts(parts):
    parts_dict = {}

    for i in xrange(1, NUM_CHUNKS):
        first_two = parts[0] + parts[i]
        # XXX: magic number, for first one, because there's the PNG header
        chunk = tokenize_chunk(first_two[0x2E:])
        matched = png_chunk_verify_crc(chunk)
        if matched:
            print "Chunk 0 and %d matched!" % i
            parts_dict[0] = i
            break

    for i in xrange(1, NUM_CHUNKS):
        matched = False
        for j in xrange(1, NUM_CHUNKS):
            if i == j:
                continue
            two_parts = parts[i] + parts[j]
            # XXX: magic number, most other parts seem to have the same offset
            offset_to_chunk = 0x2E
            chunk = tokenize_chunk(two_parts[offset_to_chunk:]) 
            matched = png_chunk_verify_crc(chunk)
            if matched:
                if i % 100 == 0:
                    print "Chunk %d and %d matched!" % (i, j)
                parts_dict[i] = j
                break

        if not matched:
            print "Chunk %d had no match!" % (i)

    return parts_dict


def write_parts(parts, parts_dict):
    fh = open("final.png", "wb")

    next_key = 0
    for i in parts_dict.iterkeys():
        fh.write(parts[next_key])
        try:
            next_key = parts_dict[next_key]
        except KeyError:
            print "Hit KeyError"

    fh.close()


def main():
    parts = read_parts()
    parts_dict = compare_parts(parts)
    write_parts(parts, parts_dict)


if __name__ == "__main__":
    main()

The nested for loops do some unnecessary work, but the whole thing runs in under 5 minutes on my laptop.

 

Step 7:  Collect the Flag

 

Now we have a (hopefully) valid PNG. Let's open it.


Friday, June 3, 2016

Running IDA Evaluation Version on Kali Linux 2016.1 64-bit

The IDA Evaluation Version previously came installed with Kali Linux 1.0, but since the upgrade to 2.0 and now Rolling Edition, IDA is no longer present.  Since the evaluation version is available as 32-bit binaries only, getting it running requires figuring out the rather large set of dependent 32-bit libraries that must be installed on Kali 64-bit.

For a quick fix, run the following commands:

$ sudo dpkg --add-architecture i386
$ sudo apt-get update
$ sudo apt-get install libglib2.0-0:i386 libx11-xcb1:i386 libxi6:i386 libsm6:i386 libfontconfig1:i386 libqt5gui5:i386

Now IDA should successfully execute from the CLI and give you a graphical window to accept the IDA License Agreement.

~/Downloads/idademo69$ ./idaq

How to determine what libraries are missing and which packages provide them involves the iterative process of:
  1. Check for missing shared objects
  2. Check which package provides them
  3. Install that package
For example:

~/Downloads/idademo69$ ldd idaq | grep "not found"
    libgobject-2.0.so.0 => not found
    libgthread-2.0.so.0 => not found
    libglib-2.0.so.0 => not found
    libXext.so.6 => not found
    libX11.so.6 => not found
    libgthread-2.0.so.0 => not found
    libglib-2.0.so.0 => not found
~/Downloads/idademo69$ dpkg -S libXext.so.6
libxext6:amd64: /usr/lib/x86_64-linux-gnu/libXext.so.6.4.0
libxext6:amd64: /usr/lib/x86_64-linux-gnu/libXext.so.6
~/Downloads/idademo69$ sudo apt-get install libxext6:i386

 

References